-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
osm_sidewalkreator.py
executable file
·3540 lines (2243 loc) · 138 KB
/
osm_sidewalkreator.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 -*-
"""
/***************************************************************************
sidewalkreator
A QGIS plugin
Plugin designated to create the Geometries of Sidewalks (separated from streets) based on OpenStreetMap Streets, given a bounding polygon, outputting a geojson intended to be imported at JOSM. It is mostly intended for accessibility Mapping.
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2021-09-29
git sha : $Format:%H$
copyright : (C) 2021 by Kauê de Moraes Vestena
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 os.path
import os, requests, codecs, time
# from os import environ
# standard libraries
# import codecs # for osm2geojson
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.gui import QgsMapLayerComboBox, QgsMapCanvas
from qgis.PyQt.QtWidgets import QAction
# additional qgis/qt imports:
from processing.gui.AlgorithmExecutor import execute_in_place
from qgis.core import QgsMapLayerProxyModel, QgsFeature, QgsCoordinateReferenceSystem, QgsVectorLayer, QgsProject, QgsApplication, edit, QgsGeometryUtils, QgsFeatureRequest, Qgis, NULL, QgsStatisticalSummary
from qgis.utils import iface
# pure Qt imports, keep at minimun =P
from PyQt5.QtWidgets import QTableWidgetItem
from PyQt5.QtWidgets import QDialogButtonBox
from PyQt5.QtCore import QVariant
# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the dialog
from .osm_sidewalkreator_dialog import sidewalkreatorDialog
# for third-party libraries installation
import subprocess
import sys
# for output folder unique naming
import datetime
# small calculations
import math
############################
##### GLOBAL-SCOPE
###########################
# to path stuff don't get messy:
# homepath = os.environ['HOME']
# homepath = os.path.expanduser('~')
# TODO: adapt for windows aswell (actually we may only need to test the current solution)
# basepathp1 = '.local/share/QGIS/QGIS3/profiles'
# basepath = os.path.join(homepath,basepathp1,user_profile,basepathp2)
# # internal dependencies, part1:
from .generic_functions import *
from .parameters import *
profilepath = QgsApplication.qgisSettingsDirPath()
base_pluginpath_p2 = 'python/plugins/osm_sidewalkreator'
basepath = os.path.join(profilepath,base_pluginpath_p2)
temps_path = os.path.join(basepath,'temporary')
print(basepath)
reports_path = os.path.join(basepath,'reports')
assets_path = os.path.join(basepath,'assets')
# this two are here because of the dependency structure
# in future they should be moved to generic_functions
def stylepath(filename):
return os.path.join(assets_path,filename)
def apply_style(layer,filename):
layer.loadNamedStyle(stylepath(filename))
basic_folderpathlist = [temps_path,reports_path,assets_path]
for folderpath in basic_folderpathlist:
create_dir_ifnotexists(folderpath)
# importing osm2geojson directly or use the whl version:
try:
import osm2geojson
except:
# # try:
# # # at first, try to install by pypi, using the up-to-date-version
# # subprocess.check_call([sys.executable, "-m", "pip", "install", 'osm2geojson'])
# # except:
# if does not work use the frozen (whl) package
import sys
whl_path = os.path.join(basepath,'dependencies/osm2geojson-0.1.33-py3-none-any.whl')
sys.path.append(whl_path)
import osm2geojson
# # then again, because its better to raise an error...
import osm2geojson
# import ogr2osm
# # internal dependencies, part2:
from .osm_fetch import *
class sidewalkreator:
"""QGIS Plugin Implementation."""
# to control current language:
current_lang = 'en'
# variables to control wheter change in language should change labels
change_input_labels = True
# to control wheter one shall ignore a "sidewalks already drawn" warning:
ignore_sidewalks_already_drawn = True
# no buildings is the most general situation
no_buildings = True
# if method to split sidewalks using addrs and/or building centroids (HERE NAMED POIS) are avaliable (unavaliable is the most general situation, there's lots of areas without a single one)
POI_split_avaliable = False
# ready for "OK" button pressing:
ok_ready = False
# if the plugin is ready to export results (avoid the problem when user click again at the plugin icon)
export_ready = False
# a pre-declaration
already_existing_sidewalks_layer = None
# hint texts:
en_hint = "Sometimes it's better to\ncorrect errors on OSM data first!"
ptbr_hint = 'Pode ser melhor consertar\nerros na base do OSM antes!'
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: QgsInterface
"""
# Save reference to the QGIS interface
self.iface = iface
# 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',
'sidewalkreator_{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&OSM SidewalKreator')
# Check if plugin was started the first time in current QGIS session
# Must be set in initGui() to survive plugin reloads
self.first_start = None
###############################################
#### My code on __init__
#########################################
# language_selector
# self.dlg.opt_ptbr.checked.connect(self.change_language)
# self.session_debugpath = os.path.join(reports_path,'session_debug.txt')
# with open(self.session_debugpath,'w+') as session_report:
# session_report.write('session_report:\n')
# # session_report.write(session_debugpath+'\n')
# # session_report.write(homepath)
# 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('sidewalkreator', 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:
# Adds plugin icon to Plugins toolbar
self.iface.addToolBarIcon(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."""
icon_path = ':/plugins/osm_sidewalkreator/icon.png'
self.add_action(
icon_path,
text=self.tr(u'Create Sidewalks for OSM'),
callback=self.run,
parent=self.iface.mainWindow())
# will be set False in run()
self.first_start = True
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
for action in self.actions:
self.iface.removePluginMenu(
self.tr(u'&OSM SidewalKreator'),
action)
self.iface.removeToolBarIcon(action)
def run(self):
"""Run method that performs all the real work"""
# Create the dialog with elements (after translation) and keep reference
# Only create GUI ONCE in callback, so that it will only load when the plugin is started
if self.first_start == True:
self.first_start = False
self.dlg = sidewalkreatorDialog()
# setting items that should not be visible at beginning:
self.dlg.sidewalks_warning.setHidden(True)
self.dlg.hint_text.setHidden(True)
self.dlg.ignore_already_drawn_btn.setHidden(True)
# # # THE FUNCTION CONNECTIONS
self.dlg.datafetch.clicked.connect(self.call_get_osm_data)
self.dlg.clean_data.clicked.connect(self.data_clean)
self.dlg.generate_sidewalks.clicked.connect(self.draw_sidewalks)
self.dlg.ignore_already_drawn_btn.clicked.connect(self.ignore_already_drawn_fcn)
self.dlg.add_osm_basemap.clicked.connect(self.add_osm_basemap_func)
self.dlg.add_bing_base.clicked.connect(self.add_bing_baseimg_func)
self.dlg.generate_crossings.clicked.connect(self.draw_crossings)
self.dlg.split_sidewalks.clicked.connect(self.sidewalks_splitting)
self.dlg.alongside_vor_checkbox.clicked.connect(self.alongside_voronoi_opts)
self.dlg.output_folder_selector.fileChanged.connect(self.change_folderselector_name)
# cancel means reset AND close
self.dlg.button_box.button(QDialogButtonBox.Reset).clicked.connect(self.reset_fields)
self.dlg.button_box.button(QDialogButtonBox.Cancel).clicked.connect(self.reset_fields)
self.dlg.button_box.button(QDialogButtonBox.Ok).setEnabled(False)
# language stuff
self.dlg.opt_ptbr.clicked.connect(self.change_language_ptbr)
self.dlg.opt_en.clicked.connect(self.go_back_to_english)
self.dlg.input_layer_selector.layerChanged.connect(self.get_input_layer)
self.dlg.input_layer_feature_selector.featureChanged.connect(self.get_input_feature)
# # # handles and modifications/ors:
self.dlg.input_layer_selector.setFilters(QgsMapLayerProxyModel.PolygonLayer)
self.dlg.input_layer_selector.setAllowEmptyLayer(True)
self.dlg.input_layer_selector.setLayer(None)
# thx: https://github.com/qgis/QGIS/issues/38472
# check in runtime if those folders actually exists
for folderpath in basic_folderpathlist:
create_dir_ifnotexists(folderpath)
# show the dialog
self.dlg.show()
# Run the dialog event loop
result = self.dlg.exec_()
# See if OK was pressed
if result:
self.ok_ready = True
if self.export_ready:
self.outputting_files()
self.reset_fields() # so "rebooting" for next execution
##################################
##### THE CLASS SCOPE
##################################
def set_hint_text(self):
self.dlg.hint_text.setText(
self.string_according_language(self.en_hint,self.ptbr_hint)
)
def add_layer_canvas(self,layer):
# canvas = QgsMapCanvas()
QgsProject.instance().addMapLayer(layer)
QgsMapCanvas().setExtent(layer.extent())
# canvas.setLayerSet([QgsMapCanvasLayer(layer)])
def remove_layer_canvas(self,layername):
# canvas = QgsMapCanvas()
id = QgsProject.instance().mapLayersByName(layername)[0]
QgsProject.instance().removeMapLayer(id)
# canvas.setLayerSet([QgsMapCanvasLayer(layer)])
def change_language_ptbr(self):
self.current_lang = 'ptbr'
# # frozing selection if you opt for ptbr:
# self.dlg.opt_ptbr.setEnabled(False)
# self.dlg.opt_en.setEnabled(False)
self.change_all_labels_bylang()
def go_back_to_english(self):
self.current_lang = 'en'
self.change_all_labels_bylang()
def change_all_labels_bylang(self):
info_tuples = [
# tuples: (qt-dlg_element,english_text,ptbr_text)
(self.dlg.lang_label,"Language: ","Idioma: "),
(self.dlg.input_pol_label,"Input Polygon: ","Polígono de Entrada" ),
(self.dlg.table_txt1,'default widths for tag values','larguras-padrão para valores'),
(self.dlg.table_txt2,'"0" means ignore features','"0": ignorar feições'),
(self.dlg.output_file_label,'Output File:','Arquivo de Saída:'),
(self.dlg.datafetch,'Fetch Data','Obter Dados'),
(self.dlg.input_status,'waiting a valid input...','aguardando uma entrada válida...',self.change_input_labels),
(self.dlg.input_status_of_data,'waiting for data...','aguardando dados...',self.change_input_labels),
(self.dlg.button_box.button(QDialogButtonBox.Cancel),"Cancel","Cancelar"),
(self.dlg.button_box.button(QDialogButtonBox.Reset),"Reset","Reiniciar"),
(self.dlg.clean_data,'Clean OSM Data and\nCompute Intersections','Limp. dados OSM e\nGerar Interseções'),
(self.dlg.sidewalks_warning,"Some Sidewalks are already drawn!!! You must reshape your input polygon!!!\n(in a future release,this stuff shall be handled properly...)","Já há algumas calçadas mapeadas!! Você deverá Redesenhar seu polígono de entrada!!\n(em uma versão futura será lidado adequadamente)"),
(self.dlg.check_if_overlaps_buildings,'Check if Overlaps\n Buildings\n(much slower)','Testar se Sobrepõe\nEdificações\n(mais lento)'),
(self.dlg.hint_text,self.en_hint,self.ptbr_hint),
(self.dlg.generate_sidewalks,'Generate Sidewalks','Gerar Calçadas'),
(self.dlg.ignore_already_drawn_btn,"I Have Reviewed the Data\nAnd It's OK!!\n(or want to draw anyway)",'Eu Revisei os Dados\nE está tudo certo!!\n(ou gerar de qualquer jeito)'),
(self.dlg.ch_ignore_buildings,'ignore buildings\n(much faster)','ignorar edificações\n(mais rápido)'),
(self.dlg.min_d_label,'Min Distance\nto Buildings','Distância Mínima\np. Edificaçoes'),
(self.dlg.min_d_label,'Min Distance\nto Buildings','Dist. Min.\np. Edificaçoes'),
(self.dlg.curveradius_label,'Curve\nRadius','Raio de\nCurvatura'),
(self.dlg.d_to_add_label,'Distance to\nadd to Width','D. Adic.\nàs Larguras'),
(self.dlg.min_width_label,'Min Width','Largura\nMínima'),
(self.dlg.add_osm_basemap,'+ OSM\nBase Map','+Mapa-Base\nOSM'),
(self.dlg.add_bing_base,'+ BING\nBase Img.','+Imagens\nBING'),
(self.dlg.generate_crossings,'Generate Crossings','Gerar Cruzamentos'),
(self.dlg.dead_end_iters_label,'Iters. to remove\ndead-end-streets\n(0 to keep all of them)','Iter. p/ remover\nruas-sem-fim\n(0 para manter todas)'),
(self.dlg.split_sidewalks,'Split Sidewalk Geometries','Subdividir Calçadas (Geometrias)'),
(self.dlg.perc_tol_crossings_label,'len.\ntol.','tol.\ndist.'),
(self.dlg.perc_draw_kerbs_label,'Kerbs\nat','Kerb*\nem.'),
(self.dlg.opt_parallel_crossings,'in parallel to\ntransversal seg.','paralelo ao\nseg. transversal'),
(self.dlg.opt_perp_crossings,'perpen-\ndicularly','perpendi-\ncularmente'),
(self.dlg.label_inward_d,'distance\ninward','distância\nadentro'),
(self.dlg.voronoi_checkbox,'Use Voronoi Polygons Rule','Usar Polígonos de Voronoi'),
(self.dlg.alongside_vor_checkbox,'Alongside another option','Junto à Outra Opção'),
(self.dlg.maxlensplit_checkbox,'Max Len.','Larg. Máx.'),
(self.dlg.segsbynum_checkbox,'In x\nsegments','Em x\nsegmentos'),
(self.dlg.onlyfacades_checkbox,'Only Facades',' Faces Q.'),
(self.dlg.dontsplit_checkbox,"Don't Split",'Não Dividir'),
(self.dlg.input_feature_text,"input feature:\n(-1: none)",'Feição de Entrada\n(-1: nenhuma)'),
(self.dlg.min_seg_len_label,"min road\nsegment length",'comprimento min.\n(seg. via)'),
(self.dlg.ch_remove_abovetol,"remove above tolerance",'remover se acima da tol.'),
# (self.dlg.,'',''),
# (self.dlg.,'',''),
# (self.dlg.,'',''),
# (self.dlg.,'',''),
]
for info_set in info_tuples:
# What an elegant solution!!!
self.set_text_based_on_language(*info_set)
preffix_tuples = [
(self.dlg.minimum_pois_box,'min. POIs: ','min. pts.: '),
]
for preffixes in preffix_tuples:
self.set_prefix_based_on_language(*preffixes)
def data_clean(self):
# getting table values, before table deactivation
highway_valuestable_dict = {}
for i,val in enumerate(self.unique_highway_values):
# self.dlg.higway_values_table
try:
width_value = float(self.dlg.higway_values_table.item(i,1).text())
except:
# if the user input value not convertible to float, just use the value from
print('invalid input value: ',self.dlg.higway_values_table.item(i,1).text(),', using default: ',default_widths.get(val,fallback_default_width))
width_value = default_widths.get(val,fallback_default_width)
highway_valuestable_dict[val] = width_value
# disabling what should not be used afterwards
self.dlg.clean_data.setEnabled(False)
self.dlg.dead_end_iters_label.setEnabled(False)
self.dlg.dead_end_iters_box.setEnabled(False)
self.dlg.higway_values_table.setEnabled(False)
# removing undesired tag values:
for i,value in enumerate(self.unique_highway_values):
# if a too small value is set (including negatives, lol), then also remove it:
# saving already existing sidewalks and crossings in layers:
if value == "footway":
# for sidewalks:
already_existing_sidewalks_list = select_feats_by_attr(self.clipped_reproj_datalayer,'footway','sidewalk')
self.already_existing_sidewalks_layer = layer_from_featlist(already_existing_sidewalks_list,'already_existing_sidewalks','linestring',CRS=self.custom_localTM_crs)
#for crossings:
already_existing_crossings_list = select_feats_by_attr(self.clipped_reproj_datalayer,'footway','crossing')
self.already_existing_crossings_layer = layer_from_featlist(already_existing_crossings_list,'already_existing_crossings','linestring',CRS=self.custom_localTM_crs)
'''
layer declaration inside a loop?
Yes,
but it's granted to happen only once
'''
if highway_valuestable_dict[value] < 0.5:
remove_features_byattr(self.clipped_reproj_datalayer,highway_tag,value)#self.unique_highway_values[i])
# creating the 'protoblocks' layer, is a poligonization of the streets layers
# self.add_layer_canvas(self.already_existing_sidewalks_layer)
# self.add_layer_canvas(self.already_existing_crossings_layer)
# protoblocks have been moved to here:
self.protoblocks = polygonize_lines(self.clipped_reproj_datalayer)
self.protoblocks.setCrs(self.custom_localTM_crs) # better safe than sorry kkkk
'''
NEW PROTOBLOCKS FILTERING TO INFER IF THERE'S ALREADY A SIDEWALK NETWORK DRAWN
'''
if self.already_existing_sidewalks_layer:
create_incidence_field_layers_A_B(self.protoblocks,self.already_existing_sidewalks_layer,'inc_sidewalk_len',True)
# calculating the approximate area of the enclosed already drawn sidewalks (assuming squared shape) in order to judge if the protoblock contains sidewalks:
protoblocks_ratio_id = create_new_layerfield(self.protoblocks,'sidewalks_ratio')
with edit(self.protoblocks):
for feature in self.protoblocks.getFeatures():
# dividing by 4 approximates the side of a squared shape block
ratio = (((feature['inc_sidewalk_len']/4)**2) / feature.geometry().area()) * 100
self.protoblocks.changeAttributeValue(feature.id(),protoblocks_ratio_id,ratio)
if ratio > cutoff_percent_protoblock:
self.protoblocks.deleteFeature(feature.id())
# self.add_layer_canvas(self.protoblocks)
'''
END OF THE NEW PROTOBLOCKS FILTERING
'''
# dissolving so will become just one geometry:
self.dissolved_protoblocks_0 = dissolve_tosinglegeom(self.protoblocks)
self.dissolved_protoblocks_0.setCrs(self.custom_localTM_crs) # better safe than sorry kkkk
#adding little buffer, so features touching boundaries will be fully within
self.dissolved_protoblocks_buff = generate_buffer(self.
dissolved_protoblocks_0,protoblocks_buffer)
self.dissolved_protoblocks_buff.setCrs(self.custom_localTM_crs) # better safe than sorry kkkk
# self.add_layer_canvas(self.dissolved_protoblocks_buff)
# self.add_layer_canvas(self.dissolved_protoblocks_0)
# splitting into segments:
self.splitted_lines_name = self.string_according_language('Splitted_OSM_Lines','OSM_subdividido')
self.splitted_lines = split_lines(self.clipped_reproj_datalayer,self.clipped_reproj_datalayer,'memory:'+self.splitted_lines_name)
self.splitted_lines.setCrs(self.custom_localTM_crs)
# removing lines that does not serve to form a block ('quarteirão')
if self.dlg.dead_end_iters_box.value() == 0:
remove_lines_from_no_block(self.splitted_lines,self.dissolved_protoblocks_buff)
else:
for i in range(self.dlg.dead_end_iters_box.value()):
# without second input, the function will work just as before
remove_lines_from_no_block(self.splitted_lines)
# adding same style again:
# style_line_random_colors(self.clipped_reproj_datalayer,highway_tag,self.streets_styledict)
# adding the style:
apply_style(self.splitted_lines,roads_p2_stylefilename)
##### creating points of intersection:
intersection_points = get_intersections(self.splitted_lines,self.splitted_lines,'TEMPORARY_OUTPUT')
intersection_points.setCrs(self.custom_localTM_crs)
self.filtered_intersection_name = self.string_according_language('Road_Intersections','Intersecoes_Ruas')
self.filtered_intersection_points = remove_duplicate_geometries(intersection_points,'memory:'+self.filtered_intersection_name)
self.filtered_intersection_points.setCrs(self.custom_localTM_crs)
# creating a voronoi polygons layer for the road_intersections, that may be used for validation projects
road_intersection_voronois_0 = gen_voronoi_polygons_layer(self.filtered_intersection_points)
road_intersection_voronois_0.setCrs(self.custom_localTM_crs)
# TODO: check if will always work properly without being on same CRS
self.road_intersection_voronois = cliplayer_v2(road_intersection_voronois_0,self.only_inputfeature_layer)
self.road_intersection_voronois.setCrs(self.custom_localTM_crs)
# self.add_layer_canvas(self.road_intersection_voronois)
#### checking if there's a "width" column, adding if not:
if not widths_fieldname in get_column_names(self.splitted_lines):
create_new_layerfield(self.splitted_lines,widths_fieldname)
# filling empty widths with values in the table:
widths_index = self.splitted_lines.fields().indexOf(widths_fieldname)
higway_index = self.splitted_lines.fields().indexOf(highway_tag)
with edit(self.splitted_lines):
for feature in self.splitted_lines.getFeatures():
feature_attrs_list = feature.attributes()
# only fill if no value is present
if not feature_attrs_list[widths_index]:
highway_tag_val = feature_attrs_list[higway_index]
self.splitted_lines.changeAttributeValue(feature.id(),widths_index,highway_valuestable_dict[highway_tag_val])
"""
THX: https://gis.stackexchange.com/a/133669/49900
NEVER USE index from enumeration (ordinal) as feature key (ID), as sometimes it's not the actual feature key (ID)
index (idx) =/= id
"""
# filling a column with original id within layer to recover after a operation like
create_fill_id_field(self.splitted_lines)
# adding layers to canvas:
apply_style(self.filtered_intersection_points,road_intersections_stylefilename)
self.add_layer_canvas(self.filtered_intersection_points)
self.add_layer_canvas(self.splitted_lines)
# hint texts:
self.en_hint = 'Hint: You Can Set Widths\nmanually for Each Segment...'
self.ptbr_hint = 'Dica: Você pode Inserir manualmente\numa Largura Para Cada Segmento!'
self.set_hint_text()
# always cleaning stuff that user does not need anymore
remove_layerlist([osm_higway_layer_finalname])
# enabling next button and stuff:
self.dlg.generate_sidewalks.setEnabled(True)
self.dlg.curve_radius_box.setEnabled(True)
self.dlg.d_to_add_box.setEnabled(True)
self.dlg.curveradius_label.setEnabled(True)
self.dlg.d_to_add_label.setEnabled(True)
self.dlg.hint_text.setHidden(False)
# to say to the user: it's not the global progress,
# its just to that part
self.dlg.datafetch_progressbar.setEnabled(False)
if not self.no_buildings:
self.dlg.check_if_overlaps_buildings.setEnabled(True)
self.dlg.min_d_label.setEnabled(True)
self.dlg.min_d_buildings_box.setEnabled(True)
self.dlg.min_width_box.setEnabled(True)
self.dlg.min_width_label.setEnabled(True)
# self.replace_vectorlayer(osm_higway_layer_finalname,outputpath_splitted)
def add_osm_basemap_func(self):
layername = self.string_according_language('OSM Default','OSM Padrão')
add_tms_layer(osm_basemap_str,layername)
self.dlg.add_osm_basemap.setEnabled(False)
def add_bing_baseimg_func(self):
layername = self.string_according_language('BING Aerial','Imagens BING')
add_tms_layer(bing_baseimg_str,layername)
self.dlg.add_bing_base.setEnabled(False)
def prepare_split_options(self):
if self.POI_split_avaliable:
self.dlg.voronoi_checkbox.setEnabled(True)
self.dlg.voronoi_checkbox.setChecked(True)
self.dlg.minimum_pois_box.setEnabled(True)
self.dlg.alongside_vor_checkbox.setEnabled(True)
else:
self.dlg.maxlensplit_checkbox.setEnabled(True)
self.dlg.maxlensplit_box.setEnabled(True)
self.dlg.segsbynum_checkbox.setEnabled(True)
self.dlg.segsbynum_box.setEnabled(True)
self.dlg.onlyfacades_checkbox.setEnabled(True)
self.dlg.dontsplit_checkbox.setEnabled(True)
def alongside_voronoi_opts(self):
if self.dlg.alongside_vor_checkbox.isChecked():
self.dlg.maxlensplit_checkbox.setEnabled(True)
self.dlg.maxlensplit_box.setEnabled(True)
# self.dlg.segsbynum_checkbox.setEnabled(True)
# self.dlg.segsbynum_box.setEnabled(True)
self.dlg.onlyfacades_checkbox.setEnabled(True)
self.dlg.dontsplit_checkbox.setEnabled(True)
else:
self.dlg.maxlensplit_checkbox.setEnabled(False)
self.dlg.maxlensplit_box.setEnabled(False)
self.dlg.segsbynum_checkbox.setEnabled(False)
self.dlg.segsbynum_box.setEnabled(False)
self.dlg.onlyfacades_checkbox.setEnabled(False)
self.dlg.dontsplit_checkbox.setEnabled(False)
def sidewalks_splitting(self):
# disabling what wouldnt be needed adterwards:
self.dlg.split_sidewalks.setEnabled(False)
self.dlg.split_progressbar.setEnabled(False)
self.dlg.voronoi_checkbox.setEnabled(False)
self.dlg.minimum_pois_box.setEnabled(False)
self.dlg.alongside_vor_checkbox.setEnabled(False)
self.dlg.maxlensplit_checkbox.setEnabled(False)
self.dlg.maxlensplit_box.setEnabled(False)
self.dlg.segsbynum_checkbox.setEnabled(False)
self.dlg.segsbynum_box.setEnabled(False)
self.dlg.onlyfacades_checkbox.setEnabled(False)
self.dlg.dontsplit_checkbox.setEnabled(False)
self.dlg.hint_text.setHidden(True)
# just the name for a field that will be deleted afterwards
self.split_field_name = 'split_len'
# action tree according to checkboxes:
if not self.dlg.dontsplit_checkbox.isChecked():
# firstly, splitting using protoblocks corners
# finding which block "belongs" to each protoblock
create_incidence_field_layers_A_B(self.protoblocks,self.whole_sidewalks)
# self.add_layer_canvas(self.protoblocks)
# creating field to store splitting distance:
self.split_len_field_id = create_new_layerfield(self.whole_sidewalks,self.split_field_name)
#keeping only relevant vertices:
relevant_vertices = {}
self.protoblock_wholesidewalk_inc_dict = {}
self.protoblocks_idx_perc = {}
number_protoblocks = len([feature.id() for feature in self.protoblocks.getFeatures()])
for i,feature in enumerate(self.protoblocks.getFeatures()):
self.dlg.split_progressbar.setValue(round(100*i/number_protoblocks))
self.protoblocks_idx_perc[feature.id()]=i
# vertex_list = select_vertex_pol_nodes(feature)
# incident_sidewalk_number = int(feature['incident'])
self.protoblock_wholesidewalk_inc_dict[feature.id()] = []
for incident in feature['incident'].split():
relevant_vertices[int(incident)] = select_vertex_pol_nodes(feature)
self.protoblock_wholesidewalk_inc_dict[feature.id()].append(int(incident))
self.protoblocks_idx_perc = {key: round(100*self.protoblocks_idx_perc[key]/len(self.protoblocks_idx_perc.keys())) for key in self.protoblocks_idx_perc.keys()}
# print(feature['incident'],vertex_list)
# print(self.protoblock_wholesidewalk_inc_dict)
self.split_sidewalks_by_protoblocks(relevant_vertices)
if self.dlg.voronoi_checkbox.isChecked():
self.dlg.split_progressbar.setValue(0)
self.voronoi_splitting()
if self.dlg.alongside_vor_checkbox.isChecked():
if self.dlg.maxlensplit_checkbox.isChecked():
self.splitting_by_distance_or_ndivisions(self.dlg.maxlensplit_box.value())
# elif self.dlg.maxlensplit_checkbox.isChecked():
# pass
else:
self.dlg.split_progressbar.setValue(0)
if self.dlg.maxlensplit_checkbox.isChecked():
self.splitting_by_distance_or_ndivisions(self.dlg.maxlensplit_box.value())
elif self.dlg.segsbynum_checkbox.isChecked():
self.splitting_by_distance_or_ndivisions(self.dlg.segsbynum_box.value(),True)
else: # if we have voronoi and dontsplit:
self.dlg.split_progressbar.setValue(0)
if self.dlg.voronoi_checkbox.isChecked():
self.voronoi_splitting()
# # # adjusting the fields of the output layers
# sidewalks:
# if self.split_field_name in get_column_names(self.whole_sidewalks):
# remove_layerfields(self.whole_sidewalks,[self.split_field_name])
# now we will always have layerfields, so we will remove all of them:
remove_all_layerfields(self.whole_sidewalks)
# removing previous layerfields:
remove_all_layerfields(self.kerbs_layer)
"""
trying to fix some bugs:
"""
# lots of double points being reported:
self.whole_sidewalks = remove_duplicate_vertices(self.whole_sidewalks,tolerance=duplicate_points_tol)
# and then disjoint sidewalk stretches:
self.whole_sidewalks = snap_layers(self.whole_sidewalks,self.whole_sidewalks,tolerance=snap_disjointed_tol+0.01,behavior_code=0)
# # trying to solve lack of snapping in some crossings
self.crossings_layer = snap_layers(self.crossings_layer,self.whole_sidewalks,tolerance=.1,behavior_code=5,dontcheckinvalid=True,outputlayer='memory:CROSSINGS_')
splitted_name = 'splitted_SIDEWALKS'
# snapping once again:
self.whole_sidewalks = snap_layers(self.whole_sidewalks,self.crossings_layer,tolerance=0.1,behavior_code=1,dontcheckinvalid=True,outputlayer='memory:'+splitted_name)
#trying to merge too small stretches with a neighbour for each
self.try_to_merge_small_stretches()
"""
end of it
"""
# maybe in a future release:
# # # # excluding exclusion zones once again:
# # # if self.exclusion_zones.featureCount() != self.exclusion_zones_count:
# # # self.excluding_exclusion_zones()
# workaround for the reference of layers changing
self.remove_layer_canvas(self.whole_sidewalklayer_name)
self.remove_layer_canvas('CROSSINGS')
# print(QgsProject.instance().mapLayers())
self.add_layer_canvas(self.whole_sidewalks)
# self.whole_sidewalks.loadNamedStyle(self.sidewalk_stylefile_path)
apply_style(self.whole_sidewalks,sidewalks_stylefilename)
self.add_layer_canvas(self.crossings_layer)
# self.crossings_layer.loadNamedStyle(self.crossings_stylefile_path)
apply_style(self.crossings_layer,crossings_stylefilename)
# kerbs:
create_filled_newlayerfield(self.kerbs_layer,'barrier','kerb',QVariant.String)
# crossings:
create_filled_newlayerfield(self.crossings_layer,'highway','footway',QVariant.String)
create_filled_newlayerfield(self.crossings_layer,'footway','crossing',QVariant.String)
'''
tags to denote it's a sidewalk
footway=sidewalk
highway=footway
then filling:
'''
create_filled_newlayerfield(self.whole_sidewalks,'highway','footway',QVariant.String)
create_filled_newlayerfield(self.whole_sidewalks,'footway','sidewalk',QVariant.String)
# enabling for aftewards:
self.dlg.button_box.button(QDialogButtonBox.Ok).setEnabled(True)
self.dlg.output_file_label.setEnabled(True)
self.dlg.output_folder_selector.setEnabled(True)
# saying that is complete:
self.dlg.split_progressbar.setValue(100)
# global control variables:
self.export_ready = True
def draw_crossings(self):
# stuff to be disabled:
self.dlg.generate_crossings.setEnabled(False)
self.dlg.perc_draw_kerbs_box.setEnabled(False)
self.dlg.perc_tol_crossings_box.setEnabled(False)
self.dlg.perc_tol_crossings_label.setEnabled(False)
self.dlg.perc_draw_kerbs_label.setEnabled(False)
self.dlg.d_to_add_inward_box.setEnabled(False)
self.dlg.label_inward_d.setEnabled(False)
self.dlg.opt_parallel_crossings.setEnabled(False)
self.dlg.opt_perp_crossings.setEnabled(False)
self.dlg.min_seg_len_label.setEnabled(False)
self.dlg.min_seg_len_box.setEnabled(False)
self.dlg.ch_remove_abovetol.setEnabled(False)
# moved from draw_sidewalks
# to (probably) speed up intersections:
self.dissolved_sidewalks = dissolve_tosinglegeom(self.whole_sidewalks)
self.dissolved_sidewalks_geom = get_first_feature_or_geom(self.dissolved_sidewalks,True)
# analyzing if the endpoits of splitted lines are elegible for
# iterating again each street segment:
# storing innerpoints, to then create a layer with them
inner_pts_featlist = []
# storing the direction vectors of crossings
dirvecs_dict = {}
# creating a spatial index for sidewalks
# sidewalks_spatial_index = gen_layer_spatial_index(self.whole_sidewalks,False)