forked from MIERUNE/GTFS-GO
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gtfs_go_dialog.py
executable file
·569 lines (492 loc) · 21.4 KB
/
gtfs_go_dialog.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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
# -*- coding: utf-8 -*-
"""
/***************************************************************************
GTFSGoDockWidget
A QGIS plugin
The plugin to show routes and stops from GTFS
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2020-10-29
git sha : $Format:%H$
copyright : (C) 2020 by MIERUNE Inc.
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import datetime
import json
import os
import shutil
import tempfile
import urllib
import uuid
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from qgis.core import *
from qgis.gui import *
from qgis.PyQt import uic
from qgis.utils import iface
from . import constants, repository
from .gtfs_go_labeling import get_labeling_for_stops
from .gtfs_go_renderer import Renderer
from .gtfs_go_settings import (
STOPS_MINIMUM_VISIBLE_SCALE,
)
from .gtfs_parser import gtfs_parser
from .repository.japan_dpf.table import HEADERS, HEADERS_TO_HIDE
DATALIST_JSON_PATH = os.path.join(os.path.dirname(__file__), "gtfs_go_datalist.json")
TEMP_DIR = os.path.join(tempfile.gettempdir(), "GTFSGo")
REPOSITORY_ENUM = {"preset": 0, "japanDpf": 1}
class GTFSGoDialog(QDialog):
def __init__(self, iface):
"""Constructor."""
super().__init__()
self.ui = uic.loadUi(
os.path.join(os.path.dirname(__file__), "gtfs_go_dialog_base.ui"), self
)
with open(DATALIST_JSON_PATH, encoding="utf-8") as f:
self.datalist = json.load(f)
self.iface = iface
self.combobox_zip_text = self.tr("---Load local ZipFile---")
self.init_gui()
def init_gui(self):
# repository combobox
self.repositoryCombobox.addItem(self.tr("Preset"), REPOSITORY_ENUM["preset"])
self.repositoryCombobox.addItem(
self.tr("[Japan]GTFS data repository"), REPOSITORY_ENUM["japanDpf"]
)
# local repository data select combobox
self.ui.comboBox.addItem(self.combobox_zip_text, None)
for data in self.datalist:
self.ui.comboBox.addItem(self.make_combobox_text(data), data)
self.init_local_repository_gui()
self.init_japan_dpf_gui()
# set refresh event on some ui
self.ui.repositoryCombobox.currentIndexChanged.connect(self.refresh)
self.ui.outputDirFileWidget.fileChanged.connect(self.refresh)
self.ui.unifyCheckBox.stateChanged.connect(self.refresh)
self.ui.timeFilterCheckBox.stateChanged.connect(self.refresh)
self.ui.simpleCheckbox.clicked.connect(self.refresh)
self.ui.aggregateCheckbox.clicked.connect(self.refresh)
# time filter - validate user input
self.ui.beginTimeLineEdit.editingFinished.connect(
lambda: self.validate_time_lineedit(self.ui.beginTimeLineEdit)
)
self.ui.endTimeLineEdit.editingFinished.connect(
lambda: self.validate_time_lineedit(self.ui.endTimeLineEdit)
)
# set today DateEdit
now = datetime.datetime.now()
self.ui.filterByDateDateEdit.setDate(QDate(now.year, now.month, now.day))
self.refresh()
self.ui.pushButton.clicked.connect(self.execution)
def init_local_repository_gui(self):
self.ui.comboBox.currentIndexChanged.connect(self.refresh)
self.ui.zipFileWidget.fileChanged.connect(self.refresh)
def init_japan_dpf_gui(self):
self.japanDpfResultTableView.clicked.connect(self.refresh)
self.japanDpfResultTableView.setSelectionBehavior(QAbstractItemView.SelectRows)
self.japan_dpf_set_table([])
for idx, header in enumerate(HEADERS):
if header in HEADERS_TO_HIDE:
self.japanDpfResultTableView.hideColumn(idx)
# set default column width
self.japanDpfResultTableView.setColumnWidth(HEADERS.index("organization"), 110)
self.japanDpfResultTableView.setColumnWidth(HEADERS.index("feed"), 150)
self.japanDpfPrefectureCombobox.addItem(self.tr("any"), None)
for prefname in constants.JAPAN_PREFS_NAME_TO_CODE.keys():
self.japanDpfPrefectureCombobox.addItem(prefname, prefname)
now = datetime.datetime.now()
self.ui.japanDpfTargetDateEdit.setDate(QDate(now.year, now.month, now.day))
self.japanDpfExtentGroupBox.setMapCanvas(iface.mapCanvas())
self.japanDpfExtentGroupBox.setOutputCrs(
QgsCoordinateReferenceSystem("EPSG:4326")
)
self.japanDpfSearchButton.clicked.connect(self.japan_dpf_search)
def make_combobox_text(self, data):
"""
parse data to combobox-text
data-schema: {
country: str,
region: str,
name: str,
url: str
}
Args:
data ([type]): [description]
Returns:
str: combobox-text
"""
return "[" + data["country"] + "]" + "[" + data["region"] + "]" + data["name"]
def download_zip(self, url: str) -> str:
data = urllib.request.urlopen(url).read()
download_path = os.path.join(TEMP_DIR, str(uuid.uuid4()) + ".zip")
with open(download_path, mode="wb") as f:
f.write(data)
return download_path
def get_target_feed_infos(self):
feed_infos = []
if self.repositoryCombobox.currentData() == REPOSITORY_ENUM["preset"]:
if self.ui.comboBox.currentData():
feed_infos.append(
{
"path": self.ui.comboBox.currentData().get("url"),
"group": self.ui.comboBox.currentData().get("name"),
"dir": self.ui.comboBox.currentData().get("name"),
}
)
elif (
self.ui.comboBox.currentData() is None
and self.ui.zipFileWidget.filePath()
):
feed_infos.append(
{
"path": self.ui.zipFileWidget.filePath(),
"group": os.path.basename(
self.ui.zipFileWidget.filePath()
).split(".")[0],
"dir": os.path.basename(self.ui.zipFileWidget.filePath()).split(
"."
)[0],
}
)
elif self.repositoryCombobox.currentData() == REPOSITORY_ENUM["japanDpf"]:
selected_rows = self.japanDpfResultTableView.selectionModel().selectedRows()
for row in selected_rows:
row_data = self.get_selected_row_data_in_japan_dpf_table(row.row())
feed_infos.append(
{
"path": row_data["file_url"],
"group": row_data["organization"] + "-" + row_data["feed"],
"dir": row_data["organization_id"]
+ "-"
+ row_data["feed_id"]
+ "-"
+ row_data["file_uid"],
}
)
return feed_infos
def execution(self):
if os.path.exists(TEMP_DIR):
shutil.rmtree(TEMP_DIR)
os.makedirs(TEMP_DIR, exist_ok=True)
for feed_info in self.get_target_feed_infos():
if feed_info["path"].startswith("http"):
feed_info["path"] = self.download_zip(feed_info["path"])
output_dir = os.path.join(
self.outputDirFileWidget.filePath(), feed_info["dir"]
)
os.makedirs(output_dir, exist_ok=True)
written_files = {
"routes": "",
"stops": "",
"aggregated_routes": "",
"aggregated_stops": "",
"aggregated_csv": "",
}
gtfs = gtfs_parser.GTFS(feed_info["path"])
if self.ui.simpleCheckbox.isChecked():
routes_geojson = {
"type": "FeatureCollection",
"features": gtfs_parser.parse.read_routes(
gtfs, ignore_shapes=self.ui.ignoreShapesCheckbox.isChecked()
),
}
stops_geojson = {
"type": "FeatureCollection",
"features": gtfs_parser.parse.read_stops(
gtfs,
ignore_no_route=self.ui.ignoreNoRouteStopsCheckbox.isChecked(),
),
}
# write
written_files["routes"] = os.path.join(output_dir, "routes.geojson")
written_files["stops"] = os.path.join(output_dir, "stops.geojson")
with open(
written_files["routes"],
mode="w",
encoding="utf-8",
) as f:
json.dump(routes_geojson, f, ensure_ascii=False)
with open(
written_files["stops"],
mode="w",
encoding="utf-8",
) as f:
json.dump(stops_geojson, f, ensure_ascii=False)
if self.ui.aggregateCheckbox.isChecked():
aggregator = gtfs_parser.aggregate.Aggregator(
gtfs,
no_unify_stops=not self.ui.unifyCheckBox.isChecked(),
delimiter=self.get_delimiter(),
yyyymmdd=self.get_yyyymmdd(),
begin_time=self.get_time_filter(self.ui.beginTimeLineEdit),
end_time=self.get_time_filter(self.ui.endTimeLineEdit),
)
aggregated_routes_geojson = {
"type": "FeatureCollection",
"features": aggregator.read_route_frequency(),
}
aggregated_stops_geojson = {
"type": "FeatureCollection",
"features": aggregator.read_interpolated_stops(),
}
# write
written_files["aggregated_routes"] = os.path.join(
output_dir, "aggregated_routes.geojson"
)
written_files["aggregated_stops"] = os.path.join(
output_dir, "aggregated_stops.geojson"
)
written_files["aggregated_csv"] = os.path.join(output_dir, "result.csv")
with open(
written_files["aggregated_stops"],
mode="w",
encoding="utf-8",
) as f:
json.dump(aggregated_stops_geojson, f, ensure_ascii=False)
with open(
written_files["aggregated_routes"],
mode="w",
encoding="utf-8",
) as f:
json.dump(aggregated_routes_geojson, f, ensure_ascii=False)
with open(
written_files["aggregated_csv"],
mode="w",
encoding="cp932",
errors="ignore",
) as f:
aggregator.gtfs["stops"][
["stop_id", "stop_name", "similar_stop_id", "similar_stop_name"]
].to_csv(f, index=False)
self.show_geojson(
feed_info["group"],
written_files["stops"],
written_files["routes"],
written_files["aggregated_stops"],
written_files["aggregated_routes"],
written_files["aggregated_csv"],
)
def get_yyyymmdd(self):
if not self.ui.filterByDateCheckBox.isChecked():
return ""
date = self.ui.filterByDateDateEdit.date()
yyyy = str(date.year()).zfill(4)
mm = str(date.month()).zfill(2)
dd = str(date.day()).zfill(2)
return yyyy + mm + dd
def get_delimiter(self):
if not self.ui.unifyCheckBox.isChecked():
return ""
if not self.ui.delimiterCheckBox.isChecked():
return ""
return self.ui.delimiterLineEdit.text()
def get_time_filter(self, lineEdit):
if not self.ui.timeFilterCheckBox.isChecked():
return ""
return lineEdit.text().replace(":", "")
def show_geojson(
self,
group_name: str,
stops_geojson: str,
routes_geojson: str,
aggregated_stops_geojson: str,
aggregated_routes_geojson: str,
aggregated_csv: str,
):
root = QgsProject().instance().layerTreeRoot()
group = root.insertGroup(0, group_name)
group.setExpanded(True)
if routes_geojson != "":
routes_vlayer = QgsVectorLayer(
routes_geojson, os.path.basename(routes_geojson).split(".")[0], "ogr"
)
routes_renderer = Renderer(routes_vlayer, "route_name")
routes_vlayer.setRenderer(routes_renderer.make_renderer())
QgsProject.instance().addMapLayer(routes_vlayer, False)
group.insertLayer(0, routes_vlayer)
if stops_geojson != "":
stops_vlayer = QgsVectorLayer(
stops_geojson, os.path.basename(stops_geojson).split(".")[0], "ogr"
)
# make and set labeling for stops
stops_labeling = get_labeling_for_stops("stop_names")
stops_vlayer.setLabelsEnabled(True)
stops_vlayer.setLabeling(stops_labeling)
# adjust layer visibility
stops_vlayer.setMinimumScale(STOPS_MINIMUM_VISIBLE_SCALE)
stops_vlayer.setScaleBasedVisibility(True)
stops_renderer = Renderer(stops_vlayer, "stop_name")
stops_vlayer.setRenderer(stops_renderer.make_renderer())
QgsProject.instance().addMapLayer(stops_vlayer, False)
group.insertLayer(0, stops_vlayer)
if aggregated_routes_geojson != "":
aggregated_routes_vlayer = QgsVectorLayer(
aggregated_routes_geojson,
os.path.basename(aggregated_routes_geojson).split(".")[0],
"ogr",
)
aggregated_routes_vlayer.loadNamedStyle(
os.path.join(os.path.dirname(__file__), "aggregated_routes.qml")
)
QgsProject.instance().addMapLayer(aggregated_routes_vlayer, False)
group.insertLayer(0, aggregated_routes_vlayer)
if aggregated_stops_geojson != "":
aggregated_stops_vlayer = QgsVectorLayer(
aggregated_stops_geojson,
os.path.basename(aggregated_stops_geojson).split(".")[0],
"ogr",
)
aggregated_stops_vlayer.loadNamedStyle(
os.path.join(os.path.dirname(__file__), "aggregated_stops.qml")
)
scale_stop_size = self.ui.scaleStopSizeCheckBox.isChecked()
dd_props = (
aggregated_stops_vlayer.renderer()
.symbol()
.symbolLayers()[0]
.dataDefinedProperties()
)
if dd_props.hasProperty(QgsSymbolLayer.PropertySize):
dd_props.property(QgsSymbolLayer.PropertySize).setActive(
scale_stop_size
)
QgsProject.instance().addMapLayer(aggregated_stops_vlayer, False)
group.insertLayer(0, aggregated_stops_vlayer)
if aggregated_csv != "":
aggregated_csv_vlayer = QgsVectorLayer(
aggregated_csv,
os.path.basename(aggregated_csv).split(".")[0],
"ogr",
)
QgsProject.instance().addMapLayer(aggregated_csv_vlayer, False)
group.insertLayer(0, aggregated_csv_vlayer)
self.iface.messageBar().pushInfo(
self.tr("finish"), self.tr("generated geojson files: ")
)
self.ui.close()
def refresh(self):
self.localDataSelectAreaWidget.setVisible(
self.repositoryCombobox.currentData() == REPOSITORY_ENUM["preset"]
)
self.japanDpfDataSelectAreaWidget.setVisible(
self.repositoryCombobox.currentData() == REPOSITORY_ENUM["japanDpf"]
)
# idiom to shrink window to fit its content
self.resize(0, 0)
self.adjustSize()
self.ui.zipFileWidget.setEnabled(
self.ui.comboBox.currentText() == self.combobox_zip_text
)
# set executable
self.ui.pushButton.setEnabled(
(len(self.get_target_feed_infos()) > 0)
and (self.ui.outputDirFileWidget.filePath() != "")
and (
self.ui.simpleCheckbox.isChecked()
or self.ui.aggregateCheckbox.isChecked()
)
)
# stops unify mode
is_unify = self.ui.unifyCheckBox.isChecked()
self.ui.delimiterCheckBox.setEnabled(is_unify)
self.ui.delimiterLineEdit.setEnabled(is_unify)
# filter by times mode
has_time_filter = self.ui.timeFilterCheckBox.isChecked()
self.ui.beginTimeLineEdit.setEnabled(has_time_filter)
self.ui.endTimeLineEdit.setEnabled(has_time_filter)
# mode toggle
self.ui.simpleFrame.setEnabled(self.ui.simpleCheckbox.isChecked())
self.ui.freqFrame.setEnabled(self.ui.aggregateCheckbox.isChecked())
@staticmethod
def validate_time_lineedit(lineedit):
digits = "".join(
list(filter(lambda char: char.isdigit(), list(lineedit.text())))
).ljust(6, "0")[-6:]
# limit to 29:59:59
hh = str(min(29, int(digits[0:2]))).zfill(2)
mm = str(min(59, int(digits[2:4]))).zfill(2)
ss = str(min(59, int(digits[4:6]))).zfill(2)
formatted_time_text = hh + ":" + mm + ":" + ss
lineedit.setText(formatted_time_text)
def japan_dpf_search(self):
self.ui.pushButton.setEnabled(False)
self.japanDpfSearchButton.setEnabled(False)
self.japanDpfSearchButton.setText(self.tr("Searching..."))
target_date = self.ui.japanDpfTargetDateEdit.date()
yyyy = str(target_date.year()).zfill(4)
mm = str(target_date.month()).zfill(2)
dd = str(target_date.day()).zfill(2)
extent = (
None
if self.japanDpfExtentGroupBox.outputExtent().isEmpty()
else self.japanDpfExtentGroupBox.outputExtent()
.toString()
.replace(" : ", ",")
)
pref_code = (
None
if self.japanDpfPrefectureCombobox.currentData() is None
else constants.JAPAN_PREFS_NAME_TO_CODE.get(
self.japanDpfPrefectureCombobox.currentData()
)
)
try:
results = repository.japan_dpf.api.get_feeds(
f"{yyyy}-{mm}-{dd}",
extent=extent,
pref=pref_code,
)
self.japan_dpf_set_table(results)
except Exception as e:
QMessageBox.information(
self,
self.tr("Error"),
self.tr(
"Error occured, please check:\n- Internet connection.\n- Repository-server"
)
+ "\n\n"
+ e,
)
finally:
self.japanDpfSearchButton.setEnabled(True)
self.japanDpfSearchButton.setText(self.tr("Search"))
self.refresh()
def japan_dpf_set_table(self, results: list):
# replace pref code to pref name
for result in results:
result["feed_pref"] = constants.JAPAN_PREFS_CODE_TO_NAME[
result["feed_pref_id"]
]
model = repository.japan_dpf.table.Model(results)
proxyModel = QSortFilterProxyModel()
proxyModel.setDynamicSortFilter(True)
proxyModel.setSortCaseSensitivity(Qt.CaseInsensitive)
proxyModel.setSourceModel(model)
self.japanDpfResultTableView.setModel(proxyModel)
self.japanDpfResultTableView.setCornerButtonEnabled(True)
self.japanDpfResultTableView.setSortingEnabled(True)
# -1 is no sort indicator
self.japanDpfResultTableView.sortByColumn(-1, Qt.AscendingOrder)
# resize columns and rows
self.japanDpfResultTableView.resizeColumnToContents(HEADERS.index("pref"))
self.japanDpfResultTableView.resizeColumnToContents(HEADERS.index("license"))
self.japanDpfResultTableView.resizeColumnToContents(HEADERS.index("from_date"))
self.japanDpfResultTableView.resizeColumnToContents(HEADERS.index("to_date"))
self.japanDpfResultTableView.resizeRowsToContents()
def get_selected_row_data_in_japan_dpf_table(self, row: int):
data = {}
for col_idx, col_name in enumerate(repository.japan_dpf.table.HEADERS):
data[col_name] = (
self.japanDpfResultTableView.model().index(row, col_idx).data()
)
return data