-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindWaysBelongingToRoutesStartingFromStops.jy
More file actions
862 lines (807 loc) · 40.7 KB
/
FindWaysBelongingToRoutesStartingFromStops.jy
File metadata and controls
862 lines (807 loc) · 40.7 KB
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
#!/bin/jython
'''
FindWaysBelongingToRoutesStartingFromStops.jy
- Given a list of stops, find all ways belonging to the route
This code is released under the GNU General
Public License v2 or later.
The GPL v3 is accessible here:
http://www.gnu.org/licenses/gpl.html
The GPL v2 is accessible here:
http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
It comes with no warranty whatsoever.
'''
from javax.swing import JOptionPane
from types import *
from org.openstreetmap.josm import Main
import org.openstreetmap.josm.command as Command
import org.openstreetmap.josm.data.osm.Node as Node
import org.openstreetmap.josm.data.osm.Way as Way
import org.openstreetmap.josm.data.osm.Relation as Relation
import org.openstreetmap.josm.data.Bounds as Bounds
import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor as BoundingXYVisitor
import org.openstreetmap.josm.data.osm.TagCollection as TagCollection
import org.openstreetmap.josm.data.osm.DataSet as DataSet
import org.openstreetmap.josm.data.osm.RelationMember as RelationMember
import org.openstreetmap.josm.gui.dialogs.relation.DownloadRelationMemberTask as DownloadRelationMemberTask
import org.openstreetmap.josm.actions.DownloadReferrersAction as DownloadReferrersAction
import org.openstreetmap.josm.actions.search.SearchAction as SearchAction
import re, time
import codecs
import org.openstreetmap.josm.gui.dialogs.relation.RelationDialogManager as RelationDialogManager
import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor as RelationEditor
import org.openstreetmap.josm.actions.AutoScaleAction as AutoScaleAction
dummyRelation = Relation(); dummyWay = Way()
print
print "=========================="
print
sideEffects = {
'addWayToRoute': None,
'downloadIncompleteMembers': None,
}
logVerbosity = 30
'''
10: only report problems that require attention
20: report on collection
30: report on network nodes
40: report on which routes are being checked
50: report everything
'''
suitableWaysFor = {'bus': {'highway':['primary', 'secondary',
'tertiary', 'unclassified',
'residential', 'service',
'trunk']},
'tram': {'railway':['tram']}
}
def getMapView():
if Main.main and Main.main.map:
return Main.main.map.mapView
else:
return None
def getEndNodes(way):
if not(way.getType()) == dummyWay.getType(): return None
allNodes = way.getNodes()
# print way
# print 'All nodes', allNodes
if way.get('junction')=='roundabout':
return allNodes
else:
length = len(allNodes)
# print length
if length < 1:
if JOptionPane.showInputDialog('enter q to check this way, it has no nodes', '') == 'q':
Main.main.getEditLayer().data.setSelected([way])
AutoScaleAction.zoomToSelection()
quit
elif length < 2:
if JOptionPane.showInputDialog('enter q to check this way, it has only 1 node', '') == 'q':
Main.main.getEditLayer().data.setSelected([way])
AutoScaleAction.zoomToSelection()
quit
else:
return way.getNodes()
else:
return [way.getNode(0),way.getNode(length-1)]
def isWaySuitable(way, startingNode = None, checkDeadEnd = True, checkOneWay = True,modeOfTransport = 'bus'):
if not(way.getType() == dummyWay.getType()): return False
endNodes = getEndNodes(way)
if checkDeadEnd:
'''check if it's a dead end street'''
if way.isIncomplete() or way.get('area') == 'yes' or way.get('noexit') == 'yes':
'''if it's not completely downloaded, we don't want to consider it'''
'''deprecated way of tagging dead end streets'''
return False
for endNode in endNodes:
if endNode == startingNode:
continue
if endNode.get('highway') == 'bus_stop':
break
if endNode.get('noexit') == 'yes':
return False
'''are there suitable parent ways?'''
noParentWaysFound = True
for parentWayOfOppositeEndNode in endNode.getReferrers():
if isWaySuitable(parentWayOfOppositeEndNode, endNode, checkDeadEnd = False, checkOneWay = False, modeOfTransport = modeOfTransport):
noParentWaysFound = False
break
if noParentWaysFound: return False
if startingNode and checkOneWay:
oneWayPSV = way.get('oneway:psv')
if oneWayPSV:
oneWay = oneWayPSV
else:
oneWay = way.get('oneway')
if oneWay in ['yes', 'true', '1']: oneWay = True; reversed = False
elif oneWay in ['-1']: oneWay = True; reversed = True
else: oneWay = False
if oneWay:
if reversed:
if startingNode != endNodes[-1]: return False
else:
if startingNode != endNodes[0]: return False
# print suitableWaysFor[modeOfTransport]
for typeOfWay, goodTypes in suitableWaysFor[modeOfTransport].iteritems():
# print typeOfWay, goodTypes
if typeOfWay in way.getKeys() and\
way.get(typeOfWay) in goodTypes:
return True
return False
def areThese2WaysConnected(way1,way2):
if not(way1.getType() == way2.getType() == dummyWay.getType()): return False
for endnode in getEndNodes(way1):
if endnode:
endNodesWay2 = getEndNodes(way2)
if endNodesWay2 and endnode in endNodesWay2:
return endnode
return False
def isSideWaySuitable(way, sideway, modeOfTransport='bus'):
if not(way == sideway):
commonNode = areThese2WaysConnected(way, sideway)
if commonNode: return isWaySuitable(sideway, commonNode, modeOfTransport=modeOfTransport)
return False
checkedWays = {}
def extendEdge(ways, result = []):
return ways
# TODO rewrite this function
# print way
# print result
# if JOptionPane.showInputDialog('check', '') == 'q':
# quit
for way in ways:
if way in checkedWays: return result
checkedWays[way] = None
if not(result): result = [way]
endnodes = getEndNodes(way)
'''first check that this way is only connected to 2 other ways at its end nodes'''
for node in way.getNodes():
if not(node in endnodes):
for sideway in node.getReferrers():
if sideway.getType() == dummyWay.getType() and \
sideway.get('highway') in suitableWaysForBus:
print 'Forking way'
return result
suitableSideWays = 0
for sideway in endnodes[0].getReferrers():
if isSideWaySuitable(way, sideway):
suitableSideWays += 1
if suitableSideWays > 1:
print 'More than 1 branch'
else:
new = extendEdge(sideway, result = result)
print 'add way to start of sequence'
if not(new == result): result.insert(0,new[0])
suitableSideWays = 0
for sideway in endnodes[1].getReferrers():
if isSideWaySuitable(way, sideway):
suitableSideWays += 1
if suitableSideWays > 1:
print 'More than 1 branch'
else:
new = extendEdge(sideway, result = result)
print 'add way to end of sequence'
if not(new == result): result.append(new[0])
return result
def findConnectingWay(way1,way2):
'''If there is only one way in between these 2 ways, return it'''
solution = None; way2EndNodes = getEndNodes(way2)
for endnode in getEndNodes(way1):
parentways=endnode.getReferrers()
for parentway in parentways:
if isSideWaySuitable(way1, parentway):
endnodeInParentWays=getEndNodes(parentway)
for endnodeInParentWay in endnodeInParentWays:
if endnodeInParentWay in way2EndNodes:
solution = parentway
break
if not(solution) and way1.get('name') == way2.get('name') and \
parentway.get('name') == way1.get('name'): solution = parentway
return solution
waysNextToPlatform = {}
platformsNextToWay = {}
stopPositions = {}
def findWaysPassingByPlatformNode(node, route, member):
found = False
'''Did we do this already?'''
nodeId = node.getUniqueId(); nodelayer = node.get('layer')
if nodeId in waysNextToPlatform: return waysNextToPlatform[nodeId]
'''First try to use a stop_area relation'''
stop_positions = []; platforms = []
for parentRelationOfNode in node.getReferrers():
if found: return waysNextToPlatform[nodeId]
if parentRelationOfNode.getType() == dummyRelation.getType():
if parentRelationOfNode.get('type') in ('public_transport') and \
parentRelationOfNode.get('public_transport') in ('stop_area','stop_position'):
for member in parentRelationOfNode.getMembers(): # now we are sure it's the correct kind of relation, drill down to find parent way of stop_position node
if member.isNode():
memberNode=member.getNode()
if memberNode.get('public_transport') in ['stop_position']:
stop_positions.append(memberNode)
stopPositions.setdefault(nodeId, []).append(memberNode)
if memberNode.get('public_transport') in ['platform']:
platforms.append(memberNode)
# print 'sp: '
# print stop_positions
# print platforms
# quit
for sp in stop_positions:
for parentWayCandidate in sp.getReferrers():
if isWaySuitable(parentWayCandidate, sp, modeOfTransport=route.get('route')):
print 'connected through stop_area: '
waysNextToPlatform.setdefault(node, []).append(parentWayCandidate)
for pf in platforms:
platformsNextToWay.setdefault(parentWayCandidate.getUniqueId(), []).append(pf)
if nodeId in waysNextToPlatform:
return waysNextToPlatform[nodeId]
'''If there is no stop_area relation, try to find a way nearby, preferably with a stop_position node'''
else:
# We couldn't determine the way by means of the stop_area relation
bboxCalculator = BoundingXYVisitor()
bboxCalculator.computeBoundingBox([node])
bboxCalculator.enlargeBoundingBox()
if bboxCalculator.getBounds():
mv.zoomTo(bboxCalculator)
#mv.zoomTo(node.getEastNorth())
ignorelist = [node]
stopPosition = Node()
for i in range(1,20):
candidateWays = mv.getAllNearest(mv.getPoint(node),ignorelist,Way().wayPredicate)
if candidateWays:
candidateNodes = mv.getAllNearest(mv.getPoint(node),[],Node().nodePredicate)
foundStopPosition = False
for candidateNode in candidateNodes:
# is there a stop_position node in the candidates?
if candidateNode.get('public_transport') in ['stop_position']:
stopPosition = candidateNode
stopPositions.setdefault(nodeId, []).append(stopPosition)
ignorelist.append(candidateNode)
foundStopPosition = True
break
for candidateWay in candidateWays:
if not(candidateWay.get('highway')):
ignorelist.append(candidateWay)
continue
waylayer = candidateWay.get('layer')
if (nodelayer or waylayer) and not(waylayer == nodelayer):
ignorelist.append(candidateWay)
continue
elif isWaySuitable(candidateWay, modeOfTransport = route.get('route')):
if foundStopPosition:
if not(stopPosition in candidateWay.getNodes()):
'''A stop position node was found, but this candidate way doesn't contain it'''
continue
elif stopPosition in getEndNodes(candidateWay):
waysNextToPlatform.setdefault(node, []).append(candidateWay)
print 'using '
print candidateWay.getKeys()
waysNextToPlatform[nodeId] = [candidateWay]
platformsNextToWay.setdefault(candidateWay.getUniqueId(), []).append(node)
else:
ignorelist.append(candidateWay)
print 'ignoring '
print candidateWay.getKeys()
if nodeId in waysNextToPlatform:
if len(waysNextToPlatform[nodeId])==2:
connectionNode = areThese2WaysConnected(waysNextToPlatform[nodeId])
if connectionNode and waysNextToPlatform[nodeId][0].getNode(0) == connectionNode:
waysNextToPlatform[nodeId] = [waysNextToPlatform[nodeId][1], waysNextToPlatform[nodeId][0]]
return waysNextToPlatform[nodeId]
bboxCalculator.enlargeBoundingBox() # zoom out a bit and try again
if bboxCalculator.getBounds():
mv.zoomTo(bboxCalculator)
if not(found):
print 'Found no suitable candidate way for this stop'
return None
def isRouteRelationSuitable(routeRelation):
if routeRelation.getType() == dummyRelation.getType() and\
not(routeRelation.hasIncompleteMembers()):
relationType = routeRelation.get('type')
if relationType and relationType == 'route':
ptVersion = routeRelation.get('public_transport:version')
if ptVersion:
ptVersion = float(ptVersion)
if not(ptVersion < 2.0):
foundWaysInRoute = False
for member in routeRelation.getMembers():
'''Are there already ways in this relation?'''
if member.isWay():
foundWaysInRoute = True; break
if foundWaysInRoute:
return True
return False
def waysLeadingToNextStop(currentRoute, nextStopNode, previousWay):
waysToNextStop = []; allDone = False; parentRelationOfWay = None
for parentRelationOfWay in previousWay.getReferrers():
if allDone: break
if parentRelationOfWay.getUniqueId() != currentRoute.getUniqueId():
if isRouteRelationSuitable(parentRelationOfWay):
containsStopMember = parentRelationOfWay.getMembersFor([nextStopNode])
if containsStopMember:
startAdding = False
for member in parentRelationOfWay.getMembers():
if member.isWay():
foundWay = member.getWay()
if waysToNextStop and not(areThese2WaysConnected(waysToNextStop[-1],foundWay)):
'''The sequence of ways in this relation is broken, so it's not suitable after all'''
waysToNextStop = []
break
if startAdding:
waysToNextStop.append(foundWay)
print 'added', foundWay.get('name'), 'from', parentRelationOfWay.get('name')
if not(nextStopNode.getUniqueId() in waysNextToPlatform):
findWaysPassingByPlatformNode(nextStopNode, currentRoute, RelationMember("",Node()))
if nextStopNode.getUniqueId() in waysNextToPlatform and \
foundWay in waysNextToPlatform[nextStopNode.getUniqueId()]:
allDone = parentRelationOfWay
break
if foundWay == previousWay:
startAdding = True
continue
return allDone, waysToNextStop
def buildSequenceOfNextStops(route, node):
nextStops = ''
relationType = route.get('type')
if relationType and relationType == 'route':
startAdding = False
for member in route.getMembers():
if member.isNode():
foundNode = member.getNode()
if foundNode == node: startAdding = True
if startAdding: nextStops += str(foundNode.getUniqueId()) + ';'
return nextStops
def findRouteRelationWithTheLongestSequenceOfStopsInCommon(route, node):
'''First find our own parent route and build up a sequence of stops which follow after our stop node'''
foundOurOwnParent = False
for parentRelationOfNode in node.getReferrers():
if parentRelationOfNode == route:
foundOurOwnParent = True
nextStops = buildSequenceOfNextStops(route, node)
if not(foundOurOwnParent):
print 'This node is not a member of that route relation'
return None, None
if not(nextStops):
print 'No further stops found'
return None, []
'''Now that we have a list to compare with, let's look for another route
which has the same sequence of stops'''
overviewOfCommonStops = {}; longest = 0; routeWithLongestSequence = None
goodCandidateParentRoutes = []
for parentRelationOfNode in node.getReferrers():
if parentRelationOfNode.getId() in goodCandidateParentRoutes:
rc = JOptionPane.showInputDialog(str(parentRelationOfNode.getId()),'processing')
if rc == 'q':
quit
stopsInCommon = ''; stopsInCommonList = []
if parentRelationOfNode.getUniqueId() != route.getUniqueId() and \
isRouteRelationSuitable(parentRelationOfNode):
startComparing = False
firstNextStop = nextStops.split(';')[0]; firstNewStopInCommon = None
waysInRelation = []
for member in parentRelationOfNode.getMembers():
if member.isWay():
foundWay = member.getWay()
if waysInRelation and not(areThese2WaysConnected(waysInRelation[-1],foundWay)):
'''The sequence of ways in this relation is broken, so it's not suitable after all'''
waysInRelation = []
break
if member.isNode():
foundNode = member.getNode()
if foundNode == node:
startComparing = True
if startComparing:
if not(firstNewStopInCommon):
firstNewStopInCommon = str(foundNode.getUniqueId())
newStopsInCommon = firstNewStopInCommon + ';'
else:
newStopsInCommon = stopsInCommon + str(foundNode.getUniqueId()) + ';'
if firstNewStopInCommon == firstNextStop and \
newStopsInCommon in nextStops:
# print 'Keep building up the list'
stopsInCommon = newStopsInCommon
stopsInCommonList.append(foundNode)
# print 'Adding', foundNode.get('name'), 'to the list'
else:
print 'Done'
# print nextStops
# print stopsInCommon
# for platform in stopsInCommonList:
# print platform.get('name')
overviewOfCommonStops[parentRelationOfNode.getUniqueId()] = stopsInCommonList
length = len(overviewOfCommonStops[parentRelationOfNode.getUniqueId()])
print length, longest
if parentRelationOfNode.getId() in goodCandidateParentRoutes:
rc = JOptionPane.showInputDialog(str(parentRelationOfNode.getUniqueId()) + ' ' + str(length),str(longest))
if rc == 'q':
quit
if length > longest:
longest = length
routeWithLongestSequence = parentRelationOfNode
print 'longer one found'
break
# print 'overviewOfCommonStops', overviewOfCommonStops
if longest:
# rc = JOptionPane.showInputDialog('chosen: ' + str(routeWithLongestSequence.getUniqueId()),str(longest))
# if rc == 'q':
# quit
return routeWithLongestSequence, overviewOfCommonStops[routeWithLongestSequence.getUniqueId()]
else:
'''No other parent route has a sequence of stops in common'''
return None, None
sideWayAlreadyChecked = {}
def sideWays(way):
result = []
for node in getEndNodes(way):
for sideWay in node.getReferrers():
if sideWay not in sideWayAlreadyChecked and isSideWaySuitable(way, sideWay):
sideWayAlreadyChecked[sideWay] = None
result.append(sideWay)
return result
def getSequenceOfWays(stopsSequence, route, comparableRoute):
adjacentWays = {}; startFrom = 0
# print 'stopsSequence', stopsSequence
for platformNode in stopsSequence:
print platformNode.get('name')
# Main.main.getEditLayer().data.setSelected(comparableRoute)
ways = findWaysPassingByPlatformNode(platformNode, route, RelationMember("",Node()))
# Main.main.getEditLayer().data.setSelected(ways)
# quit
# print 'way', ways
# print 'route', route
if ways:
index = 0
for member in comparableRoute.getMembers():
index += 1
if index < startFrom: continue
if member.isWay():
memberWay = member.getWay()
# print 'memberWay', memberWay
# rc = JOptionPane.showInputDialog('','')
# if rc == 'q':
# quit
if memberWay in ways: # memberWay in sideWays(way) or
platformNodeId = platformNode.getUniqueId()
adjacentWays[platformNodeId] = [[index, memberWay]]
startFrom = index
for nodeId in adjacentWays:
if adjacentWays[nodeId]: print len(adjacentWays[nodeId]), nodeId, adjacentWays[nodeId][0]
else: print '*', nodeId, adjacentWays[nodeId]
#print 'adjacentWays', adjacentWays
# print 'first stop in sequence', stopsSequence[0]
# print 'last stop in sequence', stopsSequence[-1]
found = False; startIndex = endIndex = 0
for stop in stopsSequence:
stopId = stop.getUniqueId()
# print stop.get('name')
if stopId in adjacentWays: found=True; break
if found: startIndex = adjacentWays[stopId][0][0] # TODO what to do when stop was found more than once?
found = False
for stop in reversed(stopsSequence):
stopId = stop.getUniqueId()
print stop.get('name')
if stopId in adjacentWays: found=True; break
if found: endIndex = adjacentWays[stopId][0][0] # TODO what to do when stop was found more than once?
#; Main.main.getEditLayer().data.setSelected(adjacentWays[stop][0][1])
waysSequence = []
index = 0; startAddingWays = False
# print 'startIndex', startIndex, 'endIndex', endIndex
for member in comparableRoute.getMembers():
index += 1
if index >= startIndex: startAddingWays = True
if index > endIndex: break
if startAddingWays:
# Main.main.getEditLayer().data.setSelected(member.getMember())
if member.isWay(): waysSequence.append(member.getMember())
return waysSequence
def addWayToRoute(wayToAdd, newRelation, pos, numberOfStops, nameForRole, waymemberslist):
depth = len(waymemberslist)
if depth > 3: depth = -3
else: depth = -1 * depth
if wayToAdd and not(wayToAdd in waymemberslist[depth:]):
# print pos, numberOfStops, nameForRole
if not(nameForRole): nameForRole = ''
if numberOfStops:
role = str(pos - numberOfStops + 1) + ' ' + nameForRole
else:
role = str(pos+1) + ' ' + nameForRole
newMember = RelationMember(role,wayToAdd)
position = pos
if position < 0: position = 0
newRelation.addMember(position, newMember)
waymemberslist.append(wayToAdd)
pos+=1
return pos, True
return pos, None
def addWaysToRoute(waysToAdd, newRelation, pos, numberOfStops, nameForRole, waymemberslist, addOneOfUsFirst):
rc = None
if waysToAdd:
if addOneOfUsFirst:
firstWayToAdd = waysToAdd[0]
for way in addOneOfUsFirst:
connectingNode = areThese2WaysConnected(way, firstWayToAdd)
if connectingNode:
waysToAdd = [way] + waysToAdd
break
for way in waysToAdd:
pos, rc = addWayToRoute(way, newRelation, pos, numberOfStops, nameForRole, waymemberslist)
return pos, rc, waymemberslist + waysToAdd
def transposeRouteRelation(existingRoute, routeWithNewInformation):
commandsList = []
newRoute = Relation(existingRoute)
for tag in routeWithNewInformation.getKeys():
print 'setting', tag, 'to', routeWithNewInformation.get(tag)
newRoute.put(tag,routeWithNewInformation.get(tag))
for tag in ['source']:
newRoute.remove(tag)
for member in reversed(newRoute.getMembers()):
'''Remove existing stops, an updated list will be added'''
if member.isNode():
newRoute.removeMembersFor(member.getNode())
for member in routeWithNewInformation.getMembers():
'''Add fresh list of stops'''
newRoute.addMember(len(newRoute.getMembers()), member)
parentRelation = None
for parentRelation in routeWithNewInformation.getReferrers():
newParentRoute = parentRelation
newParentRoute.removeMembersFor(routeWithNewInformation)
break
if parentRelation: commandsList.append(Command.ChangeCommand(parentRelation, newParentRoute))
commandsList.append(Command.ChangeCommand(existingRoute, newRoute))
commandsList.append(Command.DeleteCommand(routeWithNewInformation))
Main.main.undoRedo.add(Command.SequenceCommand("Transposing tags and stops", commandsList))
def checkPTroute(route, aDownloadWasNeeded):
if aDownloadWasNeeded:
return None, False, ''
print
waymemberslist = []
allWaysInRoute = []
# waysAlreadyInRoute = {}
modified = False
routeMembers = route.getMembers()
i = numberOfStops = len(routeMembers)
newRelation = Relation(route); commandsList = []; previousway = None; skip = 0
previousWaysSequence = []
firstStopPlatformId = None
for member in routeMembers:
if member.isNode():
stopPlatform = member.getNode()
if stopPlatform.get('highway') == 'bus_stop' or stopPlatform.get('railway') == 'tram_stop':
lastStopPlatformId = stopPlatform.getUniqueId()
if not(firstStopPlatformId): firstStopPlatformId = lastStopPlatformId
# if member.isWay():
# way = member.getWay()
# role = member.getRole()
# if role == '':
# waysAlreadyInRoute[way] = None
firstAdd1ofThese2 = None
for member in routeMembers:
"""Algorithm:
Is the node a member of a public_transport=stop_area?
Grab way from stop_area (ways connected to stop_position)
Search near to the node for "highway -highway=bus_stop inview type:way -closed"
If one more than one highways are found: Is one of them member of another route=bus relation?
Also search for "public_transport=stop_position type:node"
If found: use the parent way(s)
"""
if skip:
skip-=1
if member.isNode(): print 'skipping', member.getNode().get('name')
continue
if member.isNode():
stopPlatform = member.getNode()
stopPlatformId = stopPlatform.getUniqueId()
print stopPlatform.get('name')
comparableRoute, stopsSequence = findRouteRelationWithTheLongestSequenceOfStopsInCommon(route, stopPlatform)
# for stop in stopsSequence: print stop.get('name')
# quit
# print 'comparableRoute', comparableRoute
# Main.main.getEditLayer().data.setSelected(comparableRoute)
# quit
# print 'stopsSequence', stopsSequence
#Main.main.getEditLayer().data.setSelected(stopsSequence)
rc1 = rc2 = None
notSolved = True
if comparableRoute:
'''Best solution is to copy from another relation containing the same sequence of stops and hence normally a correct sequence of ways'''
waysSequence = getSequenceOfWays(stopsSequence, route, comparableRoute)
firstAdd1ofThese2 = []
if stopPlatformId == firstStopPlatformId:
for iway in waysSequence[:2]:
for inode in getEndNodes(iway):
if inode.get('public_transport') == 'stop_position':
firstAdd1ofThese2.append(iway)
if len(firstAdd1ofThese2)>1:
waysSequence = waysSequence[2:]
else:
firstAdd1ofThese2 = None
if len(waysSequence)>1:
i,rc1,allWaysInRoute =addWaysToRoute(waysSequence, newRelation, i, numberOfStops, comparableRoute.get('name'), waymemberslist, firstAdd1ofThese2)
if rc1:
skip = len(stopsSequence)-1; modified = True
notSolved = False
previousWaysSequence = waysSequence
else:
previousWaysSequence = []
if notSolved and allWaysInRoute:
'''second best is to use the ways of another route, which have our last way and the next stop in common'''
# print allWaysInRoute
# print allWaysInRoute[-1]
comparableRoute, waysSequence = waysLeadingToNextStop(route, stopPlatform, allWaysInRoute[-1])
if comparableRoute:
print comparableRoute.get('name')
print 'waysSequence', waysSequence
print 'firstAdd1ofThese2', firstAdd1ofThese2
i,rc1,allWaysInRoute =addWaysToRoute(waysSequence, newRelation, i, numberOfStops, comparableRoute.get('name'), waymemberslist, firstAdd1ofThese2)
if rc1:
skip = 0; modified = True
notSolved = False
previousWaysSequence = waysSequence
if notSolved and allWaysInRoute:
'''If that doesn't work, try from one of the adjacent ways'''
found = False
for endNode in getEndNodes(allWaysInRoute[-1]):
print endNode.get('public_transport')
if endNode.get('public_transport') == 'stop_position':
found = True; break
if found:
for way in endNode.getReferrers():
rc = JOptionPane.showInputDialog('Trying with a sideway',str(way.get('name')))
if rc == 'q':
quit
if isSideWaySuitable(allWaysInRoute[-1], way):
comparableRoute, waysSequence = waysLeadingToNextStop(route, stopPlatform, way)
if comparableRoute:
rc = JOptionPane.showInputDialog('found a route',str(comparableRoute.get('name')))
if rc == 'q':
quit
i,rc1,allWaysInRoute =addWaysToRoute(waysSequence, newRelation, i, numberOfStops, comparableRoute.get('name'), waymemberslist, firstAdd1ofThese2)
if rc1:
skip = 0; modified = True
notSolved = False
previousWaysSequence = waysSequence
if notSolved:
'''If all else fails, simply add the nearest suitable way'''
ways = findWaysPassingByPlatformNode(stopPlatform, route, member)
if ways:
if stopPlatformId == firstStopPlatformId:
firstAdd1ofThese2 = previousWaysSequence = allWaysInRoute = ways
continue
elif stopPlatformId == lastStopPlatformId and \
stopPlatformId in stopPositions and \
(stopPositions[stopPlatformId] in getEndNodes(waymemberslist[-1])):
edge = []
for lway in ways:
# print newRelation.getMembers()
# print lway
# print lway in allWaysInRoute
# rc = JOptionPane.showInputDialog(str(lway),str(lway in allWaysInRoute))
# if not(lway in allWaysInRoute):
# print dir(newRelation)
if not(newRelation.getMembersFor([lway])):
edge.append(lway)
else:
edge = extendEdge(ways)
i,rc2,allWaysInRoute =addWaysToRoute(edge, newRelation, i, numberOfStops, stopPlatform.get('name'), waymemberslist, firstAdd1ofThese2)
if rc2: modified = True
newRelation.put('odbl', 'new'); notFound = True
'''remove all ways which were in this relation previously, but store them in a dictionary
they might still prove useful'''
i = len(newRelation.getMembers())-1; allExistingMemberWays = {}
nextWay = None
while i:
member = newRelation.getMember(i)
if member.isWay():
way = member.getWay()
role = member.getRole()
if role in ['', 'forward', 'backward', 'route']:
if nextWay:
connectingNode = areThese2WaysConnected(way, nextWay)
if connectingNode: allExistingMemberWays.setdefault(connectingNode.getUniqueId(), []).append(nextWay)
if way in allWaysInRoute: newRelation.removeMember(i)
nextWaysEndNodes = getEndNodes(way)
nextWay = way
i-=1
i=0; previousWay = None
while i < len(newRelation.getMembers()):
'''try to fill in the gaps'''
member = newRelation.getMember(i)
i+=1
if member.isWay():
way = member.getWay()
if previousWay:
connectingWay=previousWay
# '''first try to use ways which were in the relation previously'''
# commonNode = areThese2WaysConnected(way, connectingWay)
# ens = getEndNodes(connectingWay)
# if commonNode in ens:
# ens.remove(commonNode)
# otherEndNode = ens[0]
# keepAdding = True
# while keepAdding and otherEndNode:
##TODO: there might be more than 1 way in this list
# oenId =otherEndNode.getUniqueId()
# if oenId in allExistingMemberWays:
# newWay = allExistingMemberWays[oenId][0]
# else:
# break
# commonNode = areThese2WaysConnected(connectingWay,newWay)
# if commonNode:
# keepAdding = False
# if newWay:
# newMember = RelationMember('',newWay)
# newRelation.addMember(i-1, newMember)
# i+=1
# ens = getEndNodes(connectingWay)
# if commonNode in ens:
# ens.remove(commonNode)
# otherEndNode = ens[0]; connectingWay = newWay
j=16
while j and connectingWay and not(areThese2WaysConnected(connectingWay, way)):
j-=1
previousConnectingWay = connectingWay
connectingWay=findConnectingWay(connectingWay,way)
if connectingWay and not(newRelation.getMembersFor([connectingWay])):
allWaysInRoute.append(connectingWay)
#JOptionPane.showInputDialog(unicode(previousConnectingWay.get('name'))+ ' ' +unicode(connectingWay.get('name')), str(i) + ' ' + str(j))
newMember = RelationMember('connection ' + str(j),connectingWay)
newRelation.addMember(i-1, newMember)
i+=1
else:
break
previousWay = way
if modified:
commandsList.append(Command.ChangeCommand(route, newRelation))
Main.main.undoRedo.add(Command.SequenceCommand("Adding ways directly adjacent to stop nodes", commandsList))
commandsList = []
modified = False
firstMember=newRelation.getMembers()[0]
Main.main.getEditLayer().data.setSelected(firstMember)
AutoScaleAction.zoomToSelection()
# print (dir(mv))
# RelationEditor.getEditor(Main.main.getEditLayer(), newRelation, [firstMember]).setVisible(True)
aDownloadWasNeeded = False
'''
Since Downloading referrers or missing members happens asynchronously in a separate worker thread
the script can run in three modes
1. No downloads allowed/offline run; output mentions that data was incomplete in its reports.
2. Download run; When incomplete items are encountered, they are scheduled to be downloaded. From then on, no more quality checks are performed on the data.
All hierarchies are still checked, looking for more incomplete data for which more downloads need to be scheduled.
3. Normal run; All data is available and proper reporting can be performed.
'''
mv = getMapView()
#print dir(mv)
if mv and mv.editLayer and mv.editLayer.data:
selectedRelations = mv.editLayer.data.getSelectedRelations()
if not(selectedRelations):
JOptionPane.showMessageDialog(Main.parent, "Please select a route relation")
else:
routeWithNewInformation = existingRoute = None
if len(selectedRelations)==2:
for relation in selectedRelations:
if relation.isNew():
routeWithNewInformation = relation
else:
existingRoute = relation
if routeWithNewInformation and existingRoute:
transposeRouteRelation(existingRoute, routeWithNewInformation)
selectedRelations = [existingRoute]
notFound = True
for relation in mv.editLayer.data.getRelations():
if relation.get('odbl') == 'new' and relation.get('type') == 'route':
notFound = False
break
for relation in selectedRelations:
if logVerbosity> 49: print relation
if relation.hasIncompleteMembers():
if 'downloadIncompleteMembers' in sideEffects:
aDownloadWasNeeded = True
print 'Downloading referrers for ', str(relation.get('name')), ' ', str(relation.get('note'))
DownloadRelationMemberTask.run(DownloadRelationMemberTask(relation, relation.getIncompleteMembers(), mv.editLayer ))
continue
else:
JOptionPane.showMessageDialog(Main.parent, 'Please download all incomplete member of the relations first')
exit()
relationType = relation.get('type')
if relationType == 'route':
checkPTroute(relation, aDownloadWasNeeded)
if aDownloadWasNeeded:
JOptionPane.showMessageDialog(Main.parent, 'There was incomplete data and downloading mode was initiated,\nNo further quality checks were performed.\nPlease run the script again when all downloads have completed')
else:
SearchAction.search('type:relation type=route odbl=new',SearchAction.SearchMode.fromCode('R'))