forked from ifgi-sil/orientationMapsCreator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
orientationMapsCreator.py
executable file
·5305 lines (4225 loc) · 238 KB
/
orientationMapsCreator.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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#from PyQt4.QtCore import *
from PyQt4.QtCore import Qt, QSettings, QObject, SIGNAL, QTranslator, QCoreApplication
#from PyQt4.QtGui import *
from PyQt4.QtGui import QIcon, QAction, QApplication, QMessageBox, QMessageBox, QColor
#from qgis.core import *
from qgis.core import QgsLayerTreeLayer, QgsProject, QgsMapLayerRegistry, QgsVectorLayer, QgsFeature, QgsRectangle, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsGeometry
#from qgis.gui import *
from qgis.gui import QgsVertexMarker, QgsRubberBand, QgsMapToolEmitPoint
from orientationMapsCreator_dockwidget import orientationMapsCreatorDockWidget
import orientationMapsCreator_utils as Utils
import dbConnection
import os
from __builtin__ import str
plugin_path = os.path.dirname(os.path.realpath(__file__)) # Potentially fix subdirectories
import psycopg2 #DatabaseError
import re #RegularExpressions
import glob
import timeit
import sys
#sys.path.append('/usr/share/qgis/python/plugins') #Import python processing tools
from processing.core.Processing import Processing
Processing.initialize()
#from processing.tools import *
# Initialize Qt resources from file resources.py
import resources
#from qgis._core import QgsVectorLayer
conn = dbConnection.ConnectionManager()
from functions import routeCalculator
class orientationMapsCreator:
"""QGIS Plugin Implementation."""
SUPPORTED_FUNCTIONS = [
'dijkstra']
EDGES_COLUMN_CONTROLS = [ #replace with commonControls, commonBoxes and getControlNames() from functions
'lblGeometryColumn', 'lineEditGeometryColumn',
'lblIDColumn', 'lineEditIDColumn',
'lblSourceColumn', 'lineEditSourceColumn',
'lblTargetColumn', 'lineEditTargetColumn',
'lblCostColumn', 'lineEditCostColumn',
'lblReverseCostColumn', 'lineEditReverseCostColumn']
FIND_RADIUS = 10
def __init__(self, iface):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgisInterface
"""
print "** _init_" # this is executed when the QGIS/plugin is loaded
# Save reference to the QGIS interface
self.iface = iface
# Init markers for route calculation
self.idsVertexMarkers = []
self.sourceIdsVertexMarkers = []
self.sourceIdVertexMarker = QgsVertexMarker(self.iface.mapCanvas())
self.sourceIdVertexMarker.setColor(Qt.blue)
self.sourceIdVertexMarker.setPenWidth(2)
self.sourceIdVertexMarker.setVisible(False)
self.targetIdsVertexMarkers = []
self.targetIdVertexMarker = QgsVertexMarker(self.iface.mapCanvas())
self.targetIdVertexMarker.setColor(Qt.green)
self.targetIdVertexMarker.setPenWidth(2)
self.targetIdVertexMarker.setVisible(False)
self.idsRubberBands = []
self.sourceIdRubberBand = QgsRubberBand(self.iface.mapCanvas(), Utils.getRubberBandType(False))
self.sourceIdRubberBand.setColor(Qt.cyan)
self.sourceIdRubberBand.setWidth(4)
self.targetIdRubberBand = QgsRubberBand(self.iface.mapCanvas(), Utils.getRubberBandType(False))
self.targetIdRubberBand.setColor(Qt.yellow)
self.targetIdRubberBand.setWidth(4)
# Init marker for current location
self.currentLocationVertexMarkers = []
self.currentLocationVertexMarker = QgsVertexMarker(self.iface.mapCanvas())
self.currentLocationVertexMarker.setColor(Qt.red)
self.currentLocationVertexMarker.setPenWidth(2)
self.currentLocationVertexMarker.setVisible(False)
self.currentLocationRubberBand = QgsRubberBand(self.iface.mapCanvas(), Utils.getRubberBandType(False))
self.currentLocationRubberBand.setColor(Qt.magenta)
self.currentLocationRubberBand.setWidth(4)
self.currentLocation = None
# Init marker for current functional scale
self.currentFunctionalScaleMarkers = []
self.currentFunctionalScaleRubberBand = QgsRubberBand(self.iface.mapCanvas(), Utils.getRubberBandType(False))
self.currentFunctionalScaleRubberBand.setColor(Qt.red)
self.currentFunctionalScaleRubberBand.setWidth(1)
#Items drawn on the canvas without saving to a layer
self.canvasItemList = {}
self.canvasItemList['markers'] = []
self.canvasItemList['annotations'] = []
self.canvasItemList['paths'] = []
resultPathRubberBand = QgsRubberBand(self.iface.mapCanvas(), Utils.getRubberBandType(False))
resultPathRubberBand.setColor(QColor(255, 0, 0, 128))
resultPathRubberBand.setWidth(4)
self.canvasItemList['path'] = resultPathRubberBand
resultAreaRubberBand = QgsRubberBand(self.iface.mapCanvas(), Utils.getRubberBandType(True))
resultAreaRubberBand.setColor(Qt.magenta)
resultAreaRubberBand.setWidth(2)
if not Utils.isQGISv1():
resultAreaRubberBand.setBrushStyle(Qt.Dense4Pattern)
self.canvasItemList['area'] = resultAreaRubberBand
# Layer Panel Groups
self.projectLayerPanel = {}
#Layers added to the project
self.projectLayerList = {}
# DB-Schema List for saving previous selections in comboBoxes
self.dbResultsSchemaSettings = {}
self.dbSchemaSettings = {}
self.dbEdgesTableSettings = {}
self.dbVerticesTableSettings = {}
self.dbRouteTableSettings = {}
self.dbOpenNRWSchemaSettings = {}
self.dbOpenNRWDLMSettings = {}
self.dbOSMSchemaSettings = {}
self.dbOSMPointsSettings = {}
self.dbOSMLinesSettings = {}
self.dbOSMPolygonsSettings = {}
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
locale = QSettings().value('locale/userLocale')[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'orientationMapsCreator_{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
if qVersion() > '4.3.3':
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&Orientation Maps Creator')
# TODO: We are going to let the user set this up in a future iteration
self.toolbar = self.iface.addToolBar(u'orientationMapsCreator')
self.toolbar.setObjectName(u'orientationMapsCreator')
print "** INITIALIZING orientationMapsCreator"
self.pluginIsActive = False
self.dockwidget = None
## Test routeCalculator
self.routeCalculator = routeCalculator.routeCalculator()
# noinspection PyMethodMayBeStatic
def tr(self, message):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate('orientationMapsCreator', message)
def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param add_to_toolbar: Flag indicating whether the action should also
be added to the toolbar. Defaults to True.
:type add_to_toolbar: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_toolbar:
self.toolbar.addAction(action)
if add_to_menu:
self.iface.addPluginToMenu(
self.menu,
action)
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
print "** initGui" # this is executed when the QGIS/plugin is loaded
icon_path = ':/plugins/orientationMapsCreator/icon.png'
self.add_action(
icon_path,
text=self.tr(u'Orientation Maps Creator'),
callback=self.run,
parent=self.iface.mainWindow())
if self.dockwidget == None:
# Create the dockwidget (after translation) and keep reference
self.dockwidget = orientationMapsCreatorDockWidget()
self.idsEmitPoint = QgsMapToolEmitPoint(self.iface.mapCanvas())
self.sourceIdEmitPoint = QgsMapToolEmitPoint(self.iface.mapCanvas())
self.targetIdEmitPoint = QgsMapToolEmitPoint(self.iface.mapCanvas())
self.currentLocationEmitPoint = QgsMapToolEmitPoint(self.iface.mapCanvas())
# connect UI actions to methods
QObject.connect(self.dockwidget.btnPrepareProject, SIGNAL("clicked()"), self.prepareProject)
QObject.connect(self.dockwidget.btnLoadDefaults, SIGNAL("clicked()"), self.loadDefaultConnections)
QObject.connect(self.dockwidget.btnRunAllFunctions, SIGNAL("clicked()"), self.runAllFunctions)
QObject.connect(self.dockwidget.btnClearDatasets, SIGNAL("clicked()"), self.clearDatasets)
QObject.connect(self.dockwidget.btnDatabaseRefresh, SIGNAL("clicked()"), self.reloadConnections)
QObject.connect(self.dockwidget.comboBoxDatabase, SIGNAL("currentIndexChanged(const QString&)"), self.updateDatabaseConnectionEnabled)
QObject.connect(self.dockwidget.comboBoxResultsSchema, SIGNAL("currentIndexChanged(const QString&)"), self.updateResultsSchemaIndexChanged)
QObject.connect(self.dockwidget.comboBoxEdgesSchema, SIGNAL("currentIndexChanged(const QString&)"), self.updateEdgesSchemaIndexChanged)
QObject.connect(self.dockwidget.comboBoxEdgesTable, SIGNAL("currentIndexChanged(const QString&)"), self.updateEdgesTableIndexChanged)
QObject.connect(self.dockwidget.comboBoxVerticesTable, SIGNAL("currentIndexChanged(const QString&)"), self.updateVerticesTableIndexChanged)
QObject.connect(self.dockwidget.comboBoxRouteTable, SIGNAL("currentIndexChanged(const QString&)"), self.updateRouteTableIndexChanged)
QObject.connect(self.dockwidget.btnPreviewRoute, SIGNAL("clicked()"), self.previewRoute)
QObject.connect(self.dockwidget.btnClearPreview, SIGNAL("clicked()"), self.clearPreview)
QObject.connect(self.dockwidget.btnSaveRoute, SIGNAL("clicked()"), self.saveRoute)
QObject.connect(self.dockwidget.btnRemoveRoute, SIGNAL("clicked()"), self.removeRoute)
QObject.connect(self.dockwidget.btnLoadRoute, SIGNAL("clicked()"), self.loadRoute)
#QObject.connect(self.dockwidget.btnSaveRoute, SIGNAL("clicked()"), self.routeCalculator.saveRoute)
QObject.connect(self.dockwidget.btnBufferNetwork, SIGNAL("clicked()"), self.bufferNetwork)
QObject.connect(self.dockwidget.btnAnalyzeRoute, SIGNAL("clicked()"), self.analyzeRoute)
# One source id can be selected in some functions/version
QObject.connect(self.dockwidget.btnSelectSourceID, SIGNAL("clicked(bool)"), self.selectSourceId)
QObject.connect(self.sourceIdEmitPoint, SIGNAL("canvasClicked(const QgsPoint&, Qt::MouseButton)"), self.setSourceId)
QObject.connect(self.dockwidget.btnSelectRandomSource, SIGNAL("clicked()"), self.setRandomSourceId)
QObject.connect(self.dockwidget.btnSelectTargetID, SIGNAL("clicked(bool)"), self.selectTargetId)
QObject.connect(self.targetIdEmitPoint, SIGNAL("canvasClicked(const QgsPoint&, Qt::MouseButton)"), self.setTargetId)
QObject.connect(self.dockwidget.btnSelectRandomTarget, SIGNAL("clicked()"), self.setRandomTargetId)
# Context
QObject.connect(self.dockwidget.btnSelectCurrentLocation, SIGNAL("clicked(bool)"), self.selectCurrentLocation)
QObject.connect(self.currentLocationEmitPoint, SIGNAL("canvasClicked(const QgsPoint&, Qt::MouseButton)"), self.setCurrentLocation)
QObject.connect(self.dockwidget.btnSelectRandomCurrentLocation, SIGNAL("clicked()"), self.setRandomCurrentLocation)
QObject.connect(self.dockwidget.btnShowFunctionalScale, SIGNAL("clicked()"), self.showFunctionalScale)
# OPEN NRW
QObject.connect(self.dockwidget.comboBoxOpenNRWSchema, SIGNAL("currentIndexChanged(const QString&)"), self.updateOpenNRWSchemaIndexChanged)
QObject.connect(self.dockwidget.comboBoxOpenNRWDLM, SIGNAL("currentIndexChanged(const QString&)"), self.updateOpenNRWDLMIndexChanged)
QObject.connect(self.dockwidget.btnGetUrbanAreas, SIGNAL("clicked()"), self.getUrbanAreas)
#QObject.connect(self.dockwidget.btnAddUrbanAreasNetwork, SIGNAL("clicked()"), self.addUrbanAreasNetwork)
QObject.connect(self.dockwidget.btnGetAdministrativeRegions, SIGNAL("clicked()"), self.getAdministrativeRegions)
# OSM
QObject.connect(self.dockwidget.comboBoxOSMSchema, SIGNAL("currentIndexChanged(const QString&)"), self.updateOSMSchemaIndexChanged)
QObject.connect(self.dockwidget.comboBoxOSMPointsTable, SIGNAL("currentIndexChanged(const QString&)"), self.updateOSMPointsIndexChanged)
QObject.connect(self.dockwidget.comboBoxOSMLinesTable, SIGNAL("currentIndexChanged(const QString&)"), self.updateOSMLinesIndexChanged)
QObject.connect(self.dockwidget.comboBoxOSMPolygonsTable, SIGNAL("currentIndexChanged(const QString&)"), self.updateOSMPolygonsIndexChanged)
QObject.connect(self.dockwidget.btnGetAdministrativeRegions, SIGNAL("clicked()"), self.getAdministrativeRegions)
QObject.connect(self.dockwidget.btnGetEnvironmentalRegions, SIGNAL("clicked()"), self.getEnvironmentalRegions)
QObject.connect(self.dockwidget.btnSelectOSMPoints, SIGNAL("clicked()"), self.selectOSMPoints)
QObject.connect(self.dockwidget.btnSelectOSMLines, SIGNAL("clicked()"), self.selectOSMLines)
QObject.connect(self.dockwidget.btnSelectOSMPolygons, SIGNAL("clicked()"), self.selectOSMPolygons)
self.functions = {} #Route Calculation Functions: here only dijkstra
for funcfname in self.SUPPORTED_FUNCTIONS:
# import the function
exec("from functions import %s as function" % funcfname)
funcname = function.Function.getName()
self.functions[funcname] = function.Function(self.dockwidget)
#populate the combo with connections
self.reloadMessage = False
self.reloadConnections()
self.loadSettings()
#Utils.logMessage("startup version " + str(self.version))
self.reloadMessage = True
# --------------------------------------------------------------------------
def onClosePlugin(self):
"""Cleanup necessary items here when plugin dockwidget is closed"""
print "** CLOSING orientationMapsCreator"
# disconnects
self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
# remove this statement if dockwidget is to remain
# for reuse if plugin is reopened
# Commented next statement since it causes QGIS crashe
# when closing the docked window:
# self.dockwidget = None
self.pluginIsActive = False
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
print "** UNLOAD orientationMapsCreator"
self.clearPreview()
self.clearLayerList()
self.saveSettings()
for action in self.actions:
self.iface.removePluginMenu(
self.tr(u'&Orientation Maps Creator'),
action)
self.iface.removeToolBarIcon(action)
# remove the toolbar
del self.toolbar
def loadDefaultConnections(self):
"""Load Default connection parameter"""
#print "** loadDefaultConnections"
#TODO
function = self.functions['dijkstra']
self.setDefaultArguments(function.getControlNames(self.version))
def reloadConnections(self):
"""Reload connection to Database"""
#print "** reloadConnections"
oldReloadMessage = self.reloadMessage
self.reloadMessage = False
database = str(self.dockwidget.comboBoxDatabase.currentText())
self.dockwidget.comboBoxDatabase.clear()
connections = conn.getAvailableConnections() #here: gets postgis connection from the postgis connector
self.connectionsDB = {}
for a in connections:
self.connectionsDB[ unicode(a.text()) ] = a #here: postgis databases
for dbname in self.connectionsDB:
db = None
try:
db = self.connectionsDB[dbname].connect()
con = db.con
version = Utils.getPgrVersion(con) #version of the particular connection
if (Utils.getPgrVersion(con) != 0):
self.dockwidget.comboBoxDatabase.addItem(dbname)
except dbConnection.DbError, e:
Utils.logMessage("dbname:" + dbname + ", " + e.msg)
finally:
if db and db.con:
db.con.close() #database connection is close again
#restore previously selected database if exists
idx = self.dockwidget.comboBoxDatabase.findText(database)
if idx >= 0:
self.dockwidget.comboBoxDatabase.setCurrentIndex(idx) #reset to previous selection
else:
self.dockwidget.comboBoxDatabase.setCurrentIndex(0)
self.reloadMessage = oldReloadMessage
#self.updateDatabaseConnectionEnabled()
def updateDatabaseConnectionEnabled(self):
"""Connect to selected Database"""
#print "** updateDatabaseConnectionEnabled"
dbname = str(self.dockwidget.comboBoxDatabase.currentText())
if dbname =='':
return
db = self.connectionsDB[dbname].connect()
con = db.con
self.version = Utils.getPgrVersion(con) #save overall version of selected database connection
# if self.reloadMessage:
# QMessageBox.information(self.dockwidget, self.dockwidget.windowTitle(),
# 'Selected database: ' + dbname + '\npgRouting version: ' + str(self.version))
self.reloadDatabaseConnectionSchemas()
def reloadDatabaseConnectionSchemas(self):
"""Reload Schemas of connected Database"""
#print "** reloadDatabaseConnectionSchemas"
dbname = str(self.dockwidget.comboBoxDatabase.currentText())
if dbname =='':
return
# temp save previous results_schema
curResultsSchema = ''
if dbname in self.dbResultsSchemaSettings:
curResultsSchema = self.dbResultsSchemaSettings[dbname]
self.dockwidget.comboBoxResultsSchema.clear()
# temp save previous edges_schema
curSchema = ''
if dbname in self.dbSchemaSettings:
curSchema = self.dbSchemaSettings[dbname]
self.dockwidget.comboBoxEdgesSchema.clear()
# temp save previous open_nrw_schema
curOpenNRWSchema = ''
if dbname in self.dbOpenNRWSchemaSettings:
curOpenNRWSchema = self.dbOpenNRWSchemaSettings[dbname]
self.dockwidget.comboBoxOpenNRWSchema.clear()
# retrieve schemas for new database
try:
db = self.connectionsDB[dbname].connect()
con = db.con
for schema in db.list_schemas():
self.dockwidget.comboBoxResultsSchema.addItem(schema[1])
self.dockwidget.comboBoxEdgesSchema.addItem(schema[1])
self.dockwidget.comboBoxOpenNRWSchema.addItem(schema[1])
self.dockwidget.comboBoxOSMSchema.addItem(schema[1])
#print "** schema = ", schema[1]
except dbConnection.DbError, e:
Utils.logMessage("dbname:" + dbname + ", " + e.msg)
finally:
if db and db.con:
db.con.close()
#restore previously selected results schema if exists
idx = self.dockwidget.comboBoxResultsSchema.findText(curResultsSchema)
if idx >= 0:
self.dockwidget.comboBoxResultsSchema.setCurrentIndex(idx) #reset to previous selection
else:
self.dockwidget.comboBoxResultsSchema.setCurrentIndex(0)
self.dbResultsSchemaSettings[dbname] = str(self.dockwidget.comboBoxResultsSchema.currentText())
#restore previously selected schema if exists
idx = self.dockwidget.comboBoxEdgesSchema.findText(curSchema)
if idx >= 0:
self.dockwidget.comboBoxEdgesSchema.setCurrentIndex(idx) #reset to previous selection
else:
self.dockwidget.comboBoxEdgesSchema.setCurrentIndex(0)
self.dbSchemaSettings[dbname] = str(self.dockwidget.comboBoxEdgesSchema.currentText())
#restore previously selected open_nrw_schema if exists
idx = self.dockwidget.comboBoxOpenNRWSchema.findText(curOpenNRWSchema)
if idx >= 0:
self.dockwidget.comboBoxOpenNRWSchema.setCurrentIndex(idx) #reset to previous selection
else:
self.dockwidget.comboBoxOpenNRWSchema.setCurrentIndex(0)
self.dbOpenNRWSchemaSettings[dbname] = str(self.dockwidget.comboBoxOpenNRWSchema.currentText())
self.updateEdgesSchemaIndexChanged()
def updateResultsSchemaIndexChanged(self):
"""Reload Tables of connected Schema"""
#print "** updateResultsSchemaIndexChanged"
dbname = str(self.dockwidget.comboBoxDatabase.currentText())
if dbname =='':
return
schema = str(self.dockwidget.comboBoxResultsSchema.currentText())
self.dbResultsSchemaSettings[dbname] = schema
# temp save previous route table
curRouteTable = ''
if dbname+'.'+schema in self.dbRouteTableSettings:
curRouteTable = self.dbRouteTableSettings[dbname+'.'+schema]
# empty route fields
self.dockwidget.comboBoxRouteTable.clear()
# retrieve route tables for new schema
try:
db = self.connectionsDB[dbname].connect()
con = db.con
for table in db.list_geotables(schema):
self.dockwidget.comboBoxRouteTable.addItem(table[0])
#print "** edgesVerticesTable = ", table[0]
except dbConnection.DbError, e:
Utils.logMessage("dbname:" + dbname + ", " + e.msg)
finally:
if db and db.con:
db.con.close()
# restore previously selected route table if exists
idx = self.dockwidget.comboBoxRouteTable.findText(curRouteTable)
if idx >= 0:
self.dockwidget.comboBoxRouteTable.setCurrentIndex(idx) #reset to previous selection
# comboBox updates but route load needs to be triggered manually if required
else:
self.dockwidget.comboBoxRouteTable.setCurrentIndex(0)
self.dbRouteTableSettings[dbname+'.'+schema] = str(self.dockwidget.comboBoxRouteTable.currentText())
def updateEdgesSchemaIndexChanged(self):
"""Reload Tables of connected Schema"""
#print "** updateEdgesSchemaIndexChanged"
dbname = str(self.dockwidget.comboBoxDatabase.currentText())
if dbname =='':
return
# save name of changed schema
schema = str(self.dockwidget.comboBoxEdgesSchema.currentText())
self.dbSchemaSettings[dbname] = schema
# temp save previous edges table
curEdgesTable = ''
if dbname+'.'+schema in self.dbEdgesTableSettings:
curEdgesTable = self.dbEdgesTableSettings[dbname+'.'+schema]
# temp save previous vertices table
curVerticesTable = ''
if dbname+'.'+schema in self.dbVerticesTableSettings:
curVerticesTable = self.dbVerticesTableSettings[dbname+'.'+schema]
# empty edges and vertices fields
self.dockwidget.comboBoxEdgesTable.clear()
self.dockwidget.comboBoxVerticesTable.clear()
# retrieve edges and vertices tables for new schema
try:
db = self.connectionsDB[dbname].connect()
con = db.con
for table in db.list_geotables(schema):
self.dockwidget.comboBoxEdgesTable.addItem(table[0])
self.dockwidget.comboBoxVerticesTable.addItem(table[0])
#print "** edgesVerticesTable = ", table[0]
except dbConnection.DbError, e:
Utils.logMessage("dbname:" + dbname + ", " + e.msg)
finally:
if db and db.con:
db.con.close()
# restore previously selected edges table if exists
idx = self.dockwidget.comboBoxEdgesTable.findText(curEdgesTable)
if idx >= 0:
self.dockwidget.comboBoxEdgesTable.setCurrentIndex(idx) #reset to previous selection
else:
self.dockwidget.comboBoxEdgesTable.setCurrentIndex(0)
self.dbEdgesTableSettings[dbname+'.'+schema] = str(self.dockwidget.comboBoxEdgesTable.currentText())
# restore previously selected edges table if exists
idx = self.dockwidget.comboBoxVerticesTable.findText(curVerticesTable)
if idx >= 0:
self.dockwidget.comboBoxVerticesTable.setCurrentIndex(idx) #reset to previous selection
else:
self.dockwidget.comboBoxVerticesTable.setCurrentIndex(0)
self.dbVerticesTableSettings[dbname+'.'+schema] = str(self.dockwidget.comboBoxVerticesTable.currentText())
def updateEdgesTableIndexChanged(self):
#print "** updateEdgesTableIndexChanged"
dbname = str(self.dockwidget.comboBoxDatabase.currentText())
schema = str(self.dockwidget.comboBoxEdgesSchema.currentText())
table = str(self.dockwidget.comboBoxEdgesTable.currentText())
self.dbEdgesTableSettings[dbname+'.'+schema] = table
def updateVerticesTableIndexChanged(self):
#print "** updateVerticesTableIndexChanged"
dbname = str(self.dockwidget.comboBoxDatabase.currentText())
schema = str(self.dockwidget.comboBoxResultsSchema.currentText())
table = str(self.dockwidget.comboBoxVerticesTable.currentText())
self.dbVerticesTableSettings[dbname+'.'+schema] = table
def updateRouteTableIndexChanged(self):
#print "** updateRouteTableIndexChanged"
dbname = str(self.dockwidget.comboBoxDatabase.currentText())
schema = str(self.dockwidget.comboBoxResultsSchema.currentText())
table = str(self.dockwidget.comboBoxRouteTable.currentText())
self.dbRouteTableSettings[dbname+'.'+schema] = table
def updateOpenNRWSchemaIndexChanged(self):
"""Reload Tables of OPEN NRW Schema"""
#print "** updateOpenNRWSchemaIndexChanged"
dbname = str(self.dockwidget.comboBoxDatabase.currentText())
if dbname =='':
return
schema = str(self.dockwidget.comboBoxOpenNRWSchema.currentText())
self.dbOpenNRWSchemaSettings[dbname] = schema
# temp save previous edges table
curDLM = ''
if dbname+'.'+schema in self.dbOpenNRWDLMSettings:
curDLM = self.dbOpenNRWDLMSettings[dbname+'.'+schema]
# empty edges and vertices fields
self.dockwidget.comboBoxOpenNRWDLM.clear()
# retrieve edges and vertices tables for new schema
try:
db = self.connectionsDB[dbname].connect()
con = db.con
for table in db.list_geotables(schema):
self.dockwidget.comboBoxOpenNRWDLM.addItem(table[0])
#print "** edgesVerticesTable = ", table[0]
except dbConnection.DbError, e:
Utils.logMessage("dbname:" + dbname + ", " + e.msg)
finally:
if db and db.con:
db.con.close()
# restore previously selected edges table if exists
idx = self.dockwidget.comboBoxOpenNRWDLM.findText(curDLM)
if idx >= 0:
self.dockwidget.comboBoxOpenNRWDLM.setCurrentIndex(idx) #reset to previous selection
else:
self.dockwidget.comboBoxOpenNRWDLM.setCurrentIndex(0)
self.dbOpenNRWDLMSettings[dbname+'.'+schema] = str(self.dockwidget.comboBoxOpenNRWDLM.currentText())
def updateOpenNRWDLMIndexChanged(self):
"""Reload Tables of OPEN NRW Schema"""
#print "** updateOpenNRWDLMIndexChanged"
dbname = str(self.dockwidget.comboBoxDatabase.currentText())
schema = str(self.dockwidget.comboBoxOpenNRWSchema.currentText())
table = str(self.dockwidget.comboBoxOpenNRWDLM.currentText())
self.dbOpenNRWDLMSettings[dbname+'.'+schema] = table
def updateOSMSchemaIndexChanged(self):
"""Reload Tables of OSM Schema"""
#print "** updateOSMSchemaIndexChanged"
dbname = str(self.dockwidget.comboBoxDatabase.currentText())
if dbname =='':
return
schema = str(self.dockwidget.comboBoxOSMSchema.currentText())
self.dbOSMSchemaSettings[dbname] = schema
# temp save previous edges table
curPoints = ''
if dbname+'.'+schema in self.dbOSMPointsSettings:
curPoints = self.dbOSMPointsSettings[dbname+'.'+schema]
# temp save previous edges table
curLines = ''
if dbname+'.'+schema in self.dbOSMLinesSettings:
curLines = self.dbOSMLinesSettings[dbname+'.'+schema]
curPolygons = ''
if dbname+'.'+schema in self.dbOSMPolygonsSettings:
curPolygons = self.dbOSMPolygonsSettings[dbname+'.'+schema]
# empty edges and vertices fields
self.dockwidget.comboBoxOSMPointsTable.clear()
self.dockwidget.comboBoxOSMLinesTable.clear()
self.dockwidget.comboBoxOSMPolygonsTable.clear()
# retrieve edges and vertices tables for new schema
try:
db = self.connectionsDB[dbname].connect()
con = db.con
for table in db.list_geotables(schema):
self.dockwidget.comboBoxOSMPointsTable.addItem(table[0])
self.dockwidget.comboBoxOSMLinesTable.addItem(table[0])
self.dockwidget.comboBoxOSMPolygonsTable.addItem(table[0])
except dbConnection.DbError, e:
Utils.logMessage("dbname:" + dbname + ", " + e.msg)
finally:
if db and db.con:
db.con.close()
# restore previously selected edges table if exists
idx = self.dockwidget.comboBoxOSMPointsTable.findText(curPoints)
if idx >= 0:
self.dockwidget.comboBoxOSMPointsTable.setCurrentIndex(idx) #reset to previous selection
else:
self.dockwidget.comboBoxOSMPointsTable.setCurrentIndex(0)
self.dbOSMPointsSettings[dbname+'.'+schema] = str(self.dockwidget.comboBoxOSMPointsTable.currentText())
idx = self.dockwidget.comboBoxOSMLinesTable.findText(curLines)
if idx >= 0:
self.dockwidget.comboBoxOSMLinesTable.setCurrentIndex(idx) #reset to previous selection
else:
self.dockwidget.comboBoxOSMLinesTable.setCurrentIndex(0)
self.dbOSMLinesSettings[dbname+'.'+schema] = str(self.dockwidget.comboBoxOSMLinesTable.currentText())
idx = self.dockwidget.comboBoxOSMPolygonsTable.findText(curPolygons)
if idx >= 0:
self.dockwidget.comboBoxOSMPolygonsTable.setCurrentIndex(idx) #reset to previous selection
else:
self.dockwidget.comboBoxOSMPolygonsTable.setCurrentIndex(0)
self.dbOSMPolygonsSettings[dbname+'.'+schema] = str(self.dockwidget.comboBoxOSMPolygonsTable.currentText())
def updateOSMPointsIndexChanged(self):
"""Reload Tables of OSM Schema"""
#print "** updateOSMPointsIndexChanged"
dbname = str(self.dockwidget.comboBoxDatabase.currentText())
schema = str(self.dockwidget.comboBoxOSMSchema.currentText())
table = str(self.dockwidget.comboBoxOSMPointsTable.currentText())
self.dbOSMPointsSettings[dbname+'.'+schema] = table
def updateOSMLinesIndexChanged(self):
"""Reload Tables of OSM Schema"""
#print "** updateOSMLinesIndexChanged"
dbname = str(self.dockwidget.comboBoxDatabase.currentText())
schema = str(self.dockwidget.comboBoxOSMSchema.currentText())
table = str(self.dockwidget.comboBoxOSMLinesTable.currentText())
self.dbOSMLinesSettings[dbname+'.'+schema] = table
def updateOSMPolygonsIndexChanged(self):
"""Reload Tables of OSM Schema"""
#print "** updateOSMPolygonsIndexChanged"
dbname = str(self.dockwidget.comboBoxDatabase.currentText())
schema = str(self.dockwidget.comboBoxOSMSchema.currentText())
table = str(self.dockwidget.comboBoxOSMPolygonsTable.currentText())
self.dbOSMPolygonsSettings[dbname+'.'+schema] = table
# --------------------------------------------------------------------------
# Plugin Functions
def prepareProject(self):
"""Modify layer panel to add subsequent layers directly into right groups
"""
print "** prepareProject"
root = QgsProject.instance().layerTreeRoot()
self.projectLayerPanel['root'] = root
self.projectLayerPanel['default'] = root.addGroup("Default")
self.projectLayerPanel['route'] = root.addGroup("Route")
self.projectLayerPanel['network_selection'] = root.addGroup("Network Selection")
self.projectLayerPanel['point_features'] = root.addGroup("Point Features")
self.projectLayerPanel['line_features'] = root.addGroup("Line Features")
self.projectLayerPanel['polygon_features'] = root.addGroup("Polygon Features")
self.projectLayerPanel['structural_regions'] = root.addGroup("Structural Regions")
self.projectLayerPanel['administrative_regions'] = self.projectLayerPanel['structural_regions'].addGroup("Administrative Regions")
self.projectLayerPanel['environmental_regions'] = self.projectLayerPanel['structural_regions'].addGroup("Environmental Regions")
def runAllFunctions(self):
"""Run all functions one after another.
"""
print "** runAllFunctions"
start = timeit.default_timer()
self.dockwidget.btnSaveRoute.click()
self.dockwidget.btnBufferNetwork.click()
self.dockwidget.btnAnalyzeRoute.click()
self.dockwidget.btnGetUrbanAreas.click()
#self.dockwidget.btnAddUrbanAreasNetwork.click()
stop = timeit.default_timer()
print('runAllFunctions time: ', stop - start)
def clearDatasets(self):
"""Clear all datasets from previous calculations.
"""
print "** clearDatasets"
for l in self.projectLayerList.copy():
layer = self.projectLayerList[l]
#source = layer.dataProvider().dataSourceUri()
QgsMapLayerRegistry.instance().removeMapLayer(layer)
del layer
for p in self.projectLayerPanel.copy():
panel = self.projectLayerPanel[p]
if panel != self.projectLayerPanel['root']:
self.projectLayerPanel['root'].removeChildNode(panel)
del panel
del self.projectLayerPanel['root']
def previewRoute(self):
"""Calculate Route from specified source to target using default postgis dijkstra function.
Previews Route.
"""
print "** previewRoute"
#function = self.functions[str(self.dockwidget.comboBoxFunction.currentText())]
function = self.functions['dijkstra']
args = self.getArguments(function.getControlNames(self.version))
empties = []
for key in args.keys():
if not args[key]:
empties.append(key)
if len(empties) > 0:
QApplication.restoreOverrideCursor()
QMessageBox.warning(self.dockwidget, self.dockwidget.windowTitle(),
'Following argument is not specified.\n' + ','.join(empties))
return
db = None
try:
dbname = str(self.dockwidget.comboBoxDatabase.currentText())
db = self.connectionsDB[dbname].connect()
con = db.con
version = Utils.getPgrVersion(con)
args['version'] = version
if (self.version!=version) :
QMessageBox.warning(self.dockwidget, self.dockwidget.windowTitle(),
'versions are different')
srid, geomType = Utils.getSridAndGeomType(con, args)
function.prepare(self.canvasItemList) #clears previous route
query = function.getQuery(args)
#QMessageBox.information(self.dockwidget, self.dockwidget.windowTitle(), 'Geometry Query:' + query)
cur = con.cursor()
cur.execute(query)
rows = cur.fetchall()
if len(rows) == 0:
QMessageBox.information(self.dockwidget, self.dockwidget.windowTitle(), 'No paths found in ' + self.getLayerName(args))
return
args['srid'] = srid
args['canvas_srid'] = Utils.getCanvasSrid(Utils.getDestinationCrs(self.iface.mapCanvas()))
Utils.setTransformQuotes(args, srid, args['canvas_srid'])
#TODO add route as new layer
function.draw(rows, con, args, geomType, self.canvasItemList, self.iface.mapCanvas())
except psycopg2.DatabaseError, e:
print "** Database Error"
QApplication.restoreOverrideCursor()
QMessageBox.critical(self.dockwidget, self.dockwidget.windowTitle(), '%s' % e)
except SystemError, e:
print "** SystemError Error"
QApplication.restoreOverrideCursor()
QMessageBox.critical(self.dockwidget, self.dockwidget.windowTitle(), '%s' % e)
finally:
QApplication.restoreOverrideCursor()
if db and db.con:
try:
db.con.close()
except:
QMessageBox.critical(self.dockwidget, self.dockwidget.windowTitle(),
'server closed the connection unexpectedly')
def saveRoute(self):
"""Calculate Route from specified source to target using default postgis dijkstra function.
Saves Route to layer.
"""
print "** saveRoute"