network-topology 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- network_topology/__init__.py +2 -0
- network_topology/match.py +478 -0
- network_topology/topo.py +478 -0
- network_topology-0.3.0.dist-info/METADATA +47 -0
- network_topology-0.3.0.dist-info/RECORD +8 -0
- network_topology-0.3.0.dist-info/WHEEL +5 -0
- network_topology-0.3.0.dist-info/licenses/license.txt +43 -0
- network_topology-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
"""Module for map-matching source linestrings back to the topological graph."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from itertools import count
|
|
5
|
+
from heapq import heappush, heappop
|
|
6
|
+
import networkx as nx
|
|
7
|
+
from rtree import index
|
|
8
|
+
from shapely.geometry import Point
|
|
9
|
+
import numpy as np
|
|
10
|
+
import logging
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger('network-topology')
|
|
13
|
+
logger.setLevel(logging.INFO)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def getMatchedRoutes(lineStrings, DG, increment=100., scope=30.):
|
|
17
|
+
"""List the segments/edges that best match each linestring."""
|
|
18
|
+
idx = _buildIndex(DG)
|
|
19
|
+
paths = {}
|
|
20
|
+
for i, ls in lineStrings.items():
|
|
21
|
+
logger.info('Matching shape {}'.format(i))
|
|
22
|
+
adjacency_list, s, t = _findCandidatePoints(DG, idx, ls,
|
|
23
|
+
increment=increment,
|
|
24
|
+
scope=scope)
|
|
25
|
+
path = _viterbi_search(adjacency_list, s, t, DG, increment)
|
|
26
|
+
paths[i] = path
|
|
27
|
+
return paths
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _buildIndex(DG):
|
|
31
|
+
shapeIdx = index.Index()
|
|
32
|
+
for idx, (u, v, i, data) in enumerate(DG.edges(data=True, keys=True)):
|
|
33
|
+
shapeIdx.insert(idx, data['geom'].bounds, obj=(u, v, i))
|
|
34
|
+
return shapeIdx
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _getDirection(line, distance):
|
|
38
|
+
if distance == line.length:
|
|
39
|
+
n1 = 1. - 1e-9
|
|
40
|
+
n2 = 1.
|
|
41
|
+
else:
|
|
42
|
+
n1 = distance / line.length
|
|
43
|
+
n2 = n1 + 1e-9
|
|
44
|
+
p1 = line.interpolate(n1, normalized=True)
|
|
45
|
+
p2 = line.interpolate(n2, normalized=True)
|
|
46
|
+
return (p2.x - p1.x, p2.y - p1.y)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _findCandidatePoints(DG, shapeIdx, lineString, increment=100., scope=30.):
|
|
50
|
+
adjacency_list = {}
|
|
51
|
+
totalLength = lineString.length
|
|
52
|
+
s = Candidate(DG, start=True)
|
|
53
|
+
t = Candidate(DG, end=True)
|
|
54
|
+
lastRound = [s]
|
|
55
|
+
adjacency_list[t] = []
|
|
56
|
+
|
|
57
|
+
simpleLine = lineString.simplify(scope/2.)
|
|
58
|
+
cornerPts = [Point(c) for c in simpleLine.coords[1:-1]]
|
|
59
|
+
|
|
60
|
+
points = [(Point(lineString.coords[0]), _getDirection(lineString, 0))]
|
|
61
|
+
searchRange = [increment, min(increment*2.0, totalLength - increment)]
|
|
62
|
+
failureCount = 0
|
|
63
|
+
while searchRange[1] > searchRange[0]:
|
|
64
|
+
d = np.random.uniform(*searchRange)
|
|
65
|
+
p = lineString.interpolate(d)
|
|
66
|
+
collision = False
|
|
67
|
+
for corner in cornerPts:
|
|
68
|
+
if abs(p.x - corner.x) < scope and abs(p.y - corner.y) < scope:
|
|
69
|
+
if p.distance(corner) < scope:
|
|
70
|
+
failureCount += 1
|
|
71
|
+
collision = True
|
|
72
|
+
break
|
|
73
|
+
if failureCount >= 20:
|
|
74
|
+
searchRange = [searchRange[1],
|
|
75
|
+
min(searchRange[1]+scope, totalLength-increment)]
|
|
76
|
+
failureCount = 0
|
|
77
|
+
if not collision:
|
|
78
|
+
points.append((p, _getDirection(lineString, d)))
|
|
79
|
+
searchRange = [d + increment,
|
|
80
|
+
min(d + 2. * increment, totalLength-increment)]
|
|
81
|
+
points.append((Point(lineString.coords[-1]),
|
|
82
|
+
_getDirection(lineString, totalLength)))
|
|
83
|
+
|
|
84
|
+
firstLast = points[::len(points)-1]
|
|
85
|
+
for p, pdir in points:
|
|
86
|
+
nextRound = []
|
|
87
|
+
for item in shapeIdx.intersection((p.x-scope, p.y-scope,
|
|
88
|
+
p.x+scope, p.y+scope),
|
|
89
|
+
objects=True):
|
|
90
|
+
u, v, i = item.object
|
|
91
|
+
if DG[u][v][i]['terminal'] and p not in firstLast:
|
|
92
|
+
continue
|
|
93
|
+
candidate = Candidate(DG, segment=item.object, measurement=p)
|
|
94
|
+
if candidate.distance < scope:
|
|
95
|
+
sdir = _getDirection(DG[u][v][i]['geom'], candidate.offset)
|
|
96
|
+
if np.dot(pdir, sdir) >= 0:
|
|
97
|
+
nextRound.append(candidate)
|
|
98
|
+
if nextRound:
|
|
99
|
+
for prev in lastRound:
|
|
100
|
+
adjacency_list[prev] = list(nextRound)
|
|
101
|
+
lastRound = nextRound
|
|
102
|
+
#pprint(nextRound)
|
|
103
|
+
for prev in lastRound:
|
|
104
|
+
adjacency_list[prev] = [t]
|
|
105
|
+
return adjacency_list, s, t
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _viterbi_search(adjacency_list, s, t, DG, increment):
|
|
109
|
+
# With credit to the "Map Matching in a Programmer's Perspective" guide
|
|
110
|
+
# in Valhalla by Mapzen:
|
|
111
|
+
# https://github.com/valhalla/meili/blob/master/docs/meili/algorithms.md
|
|
112
|
+
|
|
113
|
+
# Initialize joint probability for each node
|
|
114
|
+
if 'path_cache' not in DG.graph:
|
|
115
|
+
DG.graph['path_cache'] = SequenceCache()
|
|
116
|
+
cost = {}
|
|
117
|
+
for u in adjacency_list:
|
|
118
|
+
cost[u] = 1e100
|
|
119
|
+
predecessor = {}
|
|
120
|
+
queue = PriorityQueue()
|
|
121
|
+
|
|
122
|
+
cost[s] = s.emission_cost()
|
|
123
|
+
queue.add_or_update(s, cost[s])
|
|
124
|
+
predecessor[s] = None
|
|
125
|
+
while not queue.empty():
|
|
126
|
+
# Extract node u
|
|
127
|
+
u = queue.pop()
|
|
128
|
+
if u == t:
|
|
129
|
+
break
|
|
130
|
+
for v in adjacency_list[u]:
|
|
131
|
+
# Relaxation
|
|
132
|
+
new_cost = (cost[u] +
|
|
133
|
+
u.transition_cost(v, DG.graph['path_cache']) +
|
|
134
|
+
v.emission_cost())
|
|
135
|
+
if cost[v] > new_cost:
|
|
136
|
+
cost[v] = new_cost
|
|
137
|
+
predecessor[v] = u
|
|
138
|
+
queue.add_or_update(v, cost[v])
|
|
139
|
+
return _construct_path(predecessor, s, t, DG, increment)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _construct_path(predecessor, s, t, DG, increment):
|
|
143
|
+
cache = DG.graph['path_cache']
|
|
144
|
+
cur = predecessor[t]
|
|
145
|
+
sequence = [cur.segment]
|
|
146
|
+
prev = predecessor[cur]
|
|
147
|
+
while prev is not s:
|
|
148
|
+
if not(prev.segment == cur.segment and prev.offset <= cur.offset):
|
|
149
|
+
if (prev.segment[1], cur.segment[0]) in cache:
|
|
150
|
+
cVal = cache[prev.segment[1], cur.segment[0]][1]
|
|
151
|
+
sequence = cVal + sequence
|
|
152
|
+
if (len(sequence) == 0 or sequence[0] != prev.segment):
|
|
153
|
+
sequence.insert(0, prev.segment)
|
|
154
|
+
cur = prev
|
|
155
|
+
prev = predecessor[cur]
|
|
156
|
+
sequence = [(u, v, i) for u, v, i in sequence if not DG[u][v][i]['terminal']]
|
|
157
|
+
|
|
158
|
+
duplicates = []
|
|
159
|
+
lastIndex = -10
|
|
160
|
+
for i, (s1, s2) in enumerate(zip(sequence[:-1], sequence[1:])):
|
|
161
|
+
if i == lastIndex:
|
|
162
|
+
continue
|
|
163
|
+
if s1[0] == s2[1] and s1[2] == s2[2]:
|
|
164
|
+
if DG[s1[0]][s1[1]][s1[2]]['geom'].length < increment*4.:
|
|
165
|
+
duplicates.append(i)
|
|
166
|
+
duplicates.append(i+1)
|
|
167
|
+
lastIndex = i + 1
|
|
168
|
+
|
|
169
|
+
return [p for i, p in enumerate(sequence) if i not in duplicates]
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _distanceBetweenNodes(G, a, b):
|
|
173
|
+
x1 = G.nodes[a]['x']
|
|
174
|
+
y1 = G.nodes[a]['y']
|
|
175
|
+
x2 = G.nodes[b]['x']
|
|
176
|
+
y2 = G.nodes[b]['y']
|
|
177
|
+
return math.sqrt((x1-x2)**2. + (y1-y2)**2.)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _astar_path(G, source, target, weight='length'):
|
|
181
|
+
"""Return a list of edges in a shortest path between source and target
|
|
182
|
+
using the A* ("A-star") algorithm.
|
|
183
|
+
There may be more than one shortest path. This returns only one.
|
|
184
|
+
This code is adapted for multigraph from the networkx library
|
|
185
|
+
Parameters
|
|
186
|
+
----------
|
|
187
|
+
G : NetworkX graph
|
|
188
|
+
source : node
|
|
189
|
+
Starting node for path
|
|
190
|
+
target : node
|
|
191
|
+
Ending node for path
|
|
192
|
+
heuristic : function
|
|
193
|
+
A function to evaluate the estimate of the distance
|
|
194
|
+
from the a node to the target. The function takes
|
|
195
|
+
two nodes arguments and must return a number.
|
|
196
|
+
weight: string, optional (default='weight')
|
|
197
|
+
Edge data key corresponding to the edge weight.
|
|
198
|
+
Raises
|
|
199
|
+
------
|
|
200
|
+
NetworkXNoPath
|
|
201
|
+
If no path exists between source and target.
|
|
202
|
+
Examples
|
|
203
|
+
--------
|
|
204
|
+
>>> G = nx.path_graph(5)
|
|
205
|
+
>>> print(nx.astar_path(G, 0, 4))
|
|
206
|
+
[0, 1, 2, 3, 4]
|
|
207
|
+
>>> G = nx.grid_graph(dim=[3, 3]) # nodes are two-tuples (x,y)
|
|
208
|
+
>>> nx.set_edge_attributes(G, {e: e[1][0]*2 for e in G.edges()}, 'cost')
|
|
209
|
+
>>> def dist(a, b):
|
|
210
|
+
... (x1, y1) = a
|
|
211
|
+
... (x2, y2) = b
|
|
212
|
+
... return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
|
|
213
|
+
>>> print(nx.astar_path(G, (0, 0), (2, 2), heuristic=dist, weight='cost'))
|
|
214
|
+
[(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]
|
|
215
|
+
See Also
|
|
216
|
+
--------
|
|
217
|
+
shortest_path, dijkstra_path
|
|
218
|
+
"""
|
|
219
|
+
if source not in G or target not in G:
|
|
220
|
+
msg = 'Either source {} or target {} is not in G'
|
|
221
|
+
raise nx.NodeNotFound(msg.format(source, target))
|
|
222
|
+
|
|
223
|
+
# if heuristic is None:
|
|
224
|
+
# # The default heuristic is h=0 - same as Dijkstra's algorithm
|
|
225
|
+
# def heuristic(u, v):
|
|
226
|
+
# return 0
|
|
227
|
+
|
|
228
|
+
push = heappush
|
|
229
|
+
pop = heappop
|
|
230
|
+
|
|
231
|
+
# The queue stores priority, node, cost to reach, and parent.
|
|
232
|
+
# Uses Python heapq to keep in priority order.
|
|
233
|
+
# Add a counter to the queue to prevent the underlying heap from
|
|
234
|
+
# attempting to compare the nodes themselves. The hash breaks ties in the
|
|
235
|
+
# priority and is guarenteed unique for all nodes in the graph.
|
|
236
|
+
c = count()
|
|
237
|
+
queue = [(0, next(c), source, 0, None, None)]
|
|
238
|
+
|
|
239
|
+
# Maps enqueued nodes to distance of discovered paths and the
|
|
240
|
+
# computed heuristics to target. We avoid computing the heuristics
|
|
241
|
+
# more than once and inserting the node into the queue too many times.
|
|
242
|
+
enqueued = {}
|
|
243
|
+
# Maps explored nodes to parent closest to the source.
|
|
244
|
+
explored = {}
|
|
245
|
+
|
|
246
|
+
while queue:
|
|
247
|
+
# Pop the smallest item from queue.
|
|
248
|
+
_, __, curnode, dist, parent, via = pop(queue)
|
|
249
|
+
|
|
250
|
+
if curnode == target:
|
|
251
|
+
path = []
|
|
252
|
+
node = curnode
|
|
253
|
+
edge = via
|
|
254
|
+
while parent is not None:
|
|
255
|
+
path.append((parent, node, edge))
|
|
256
|
+
node = parent
|
|
257
|
+
parent, edge = explored[node]
|
|
258
|
+
path.reverse()
|
|
259
|
+
return path
|
|
260
|
+
|
|
261
|
+
if curnode in explored:
|
|
262
|
+
continue
|
|
263
|
+
|
|
264
|
+
explored[curnode] = parent, via
|
|
265
|
+
|
|
266
|
+
for neighbor, es in G[curnode].items():
|
|
267
|
+
for edge, w in es.items():
|
|
268
|
+
if neighbor in explored:
|
|
269
|
+
continue
|
|
270
|
+
ncost = dist + w.get(weight, 1)
|
|
271
|
+
if neighbor in enqueued:
|
|
272
|
+
qcost, h = enqueued[neighbor]
|
|
273
|
+
# if qcost < ncost, a longer path to neighbor remains
|
|
274
|
+
# enqueued. Removing it would need to filter the whole
|
|
275
|
+
# queue, it's better just to leave it there and ignore
|
|
276
|
+
# it when we visit the node a second time.
|
|
277
|
+
if qcost <= ncost:
|
|
278
|
+
continue
|
|
279
|
+
else:
|
|
280
|
+
h = _distanceBetweenNodes(G, neighbor, target)
|
|
281
|
+
enqueued[neighbor] = ncost, h
|
|
282
|
+
push(queue, (ncost + h, next(c), neighbor, ncost, curnode, edge))
|
|
283
|
+
|
|
284
|
+
raise nx.NetworkXNoPath("Node %s not reachable from %s" % (source, target))
|
|
285
|
+
|
|
286
|
+
SIGMA_Z = 4.07
|
|
287
|
+
BETA = 3
|
|
288
|
+
INVERSE_2_SIGMA_SQUARED = 1. / (SIGMA_Z ** 2. * 2.)
|
|
289
|
+
INVERSE_BETA = 1. / BETA
|
|
290
|
+
|
|
291
|
+
class Candidate:
|
|
292
|
+
"""Class for candidate segment."""
|
|
293
|
+
|
|
294
|
+
def __init__(self, DG, segment=None, measurement=None,
|
|
295
|
+
start=False, end=False):
|
|
296
|
+
"""Initialize."""
|
|
297
|
+
self.start = start
|
|
298
|
+
self.end = end
|
|
299
|
+
self.measurement = measurement
|
|
300
|
+
self.segment = segment
|
|
301
|
+
self.DG = DG
|
|
302
|
+
if segment:
|
|
303
|
+
geom = DG.get_edge_data(*segment)['geom']
|
|
304
|
+
self.offset = geom.project(measurement)
|
|
305
|
+
self.distance = geom.distance(measurement)
|
|
306
|
+
self.remaining = geom.length - self.offset
|
|
307
|
+
self.hash = hash((self.segment, self.offset))
|
|
308
|
+
else:
|
|
309
|
+
self.distance = 0
|
|
310
|
+
self.offset = 0
|
|
311
|
+
self.remaining = 0
|
|
312
|
+
if self.start:
|
|
313
|
+
self.hash = hash('start')
|
|
314
|
+
else:
|
|
315
|
+
self.hash = hash('end')
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def __hash__(self):
|
|
319
|
+
"""Hash for use as dictionary keys."""
|
|
320
|
+
return self.hash
|
|
321
|
+
|
|
322
|
+
def __str__(self):
|
|
323
|
+
"""String representation as segment id and offset."""
|
|
324
|
+
return '{}>{}'.format(self.segment, self.offset)
|
|
325
|
+
|
|
326
|
+
def __repr__(self):
|
|
327
|
+
"""Just use string representation."""
|
|
328
|
+
return self.__str__()
|
|
329
|
+
|
|
330
|
+
def emission_cost(self):
|
|
331
|
+
"""Gaussian distribution."""
|
|
332
|
+
#c = 1 / (SIGMA_Z * math.sqrt(2 * math.pi))
|
|
333
|
+
#prob = c * math.exp(-(self.distance**2))
|
|
334
|
+
#return -1 * math.log10(max(prob, sys.float_info.min))
|
|
335
|
+
return self.distance ** 2. * INVERSE_2_SIGMA_SQUARED
|
|
336
|
+
|
|
337
|
+
def transition_cost(self, nextCandidate, cache):
|
|
338
|
+
"""Empirical distribution."""
|
|
339
|
+
if self.measurement is None:
|
|
340
|
+
return nextCandidate.offset
|
|
341
|
+
elif nextCandidate.measurement is None:
|
|
342
|
+
return self.remaining
|
|
343
|
+
#c = 1 / BETA
|
|
344
|
+
route_distance, crossed = self._route_distance_to(nextCandidate, cache)
|
|
345
|
+
delta = abs(route_distance -
|
|
346
|
+
self.measurement.distance(nextCandidate.measurement))
|
|
347
|
+
# Apply a small bias against changing edges, to avoid swithcing between
|
|
348
|
+
# opposide edges unnecessarily.
|
|
349
|
+
#delta *= 1.000000000001**crossed
|
|
350
|
+
delta += .001 * crossed
|
|
351
|
+
|
|
352
|
+
#prob = c * math.exp(-delta*c)
|
|
353
|
+
#return -1 * math.log10(max(prob, sys.float_info.min))
|
|
354
|
+
return delta * INVERSE_BETA
|
|
355
|
+
|
|
356
|
+
def _route_distance_to(self, nextCandidate, cache):
|
|
357
|
+
if nextCandidate.segment == self.segment and nextCandidate.offset >= self.offset:
|
|
358
|
+
return nextCandidate.offset - self.offset, 0
|
|
359
|
+
if self.segment is None or nextCandidate.segment is None:
|
|
360
|
+
return 0, 0
|
|
361
|
+
terminalDistance = self.remaining + nextCandidate.offset
|
|
362
|
+
if self.segment[1] == nextCandidate.segment[0]:
|
|
363
|
+
return terminalDistance, 1
|
|
364
|
+
sumDistance = 0
|
|
365
|
+
index = (self.segment[1], nextCandidate.segment[0])
|
|
366
|
+
if index in cache:
|
|
367
|
+
sumDistance, edgeSequence = cache[index]
|
|
368
|
+
else:
|
|
369
|
+
edgeSequence = []
|
|
370
|
+
distances = []
|
|
371
|
+
try:
|
|
372
|
+
sequence = _astar_path(self.DG, self.segment[1],
|
|
373
|
+
nextCandidate.segment[0],
|
|
374
|
+
weight='length')
|
|
375
|
+
#for u, v in zip(sequence[:-1], sequence[1:]):
|
|
376
|
+
# i = min(self.DG[u][v],
|
|
377
|
+
# key=lambda x: self.DG[u][v][x]['length'])
|
|
378
|
+
for u, v, i in sequence:
|
|
379
|
+
edgeSequence.append((u, v, i))
|
|
380
|
+
distances.append(self.DG[u][v][i]['length'])
|
|
381
|
+
except nx.NetworkXException:
|
|
382
|
+
distances = [float('inf')]
|
|
383
|
+
#cache[index] = sumDistance, edgeSequence
|
|
384
|
+
cache.add(distances, edgeSequence)
|
|
385
|
+
return sumDistance + terminalDistance, len(edgeSequence) + 1
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
class PriorityQueue:
|
|
389
|
+
"""Priority queue for use in Dijkstra search."""
|
|
390
|
+
|
|
391
|
+
REMOVED = '<removed-item>' # placeholder for a removed item
|
|
392
|
+
|
|
393
|
+
def __init__(self):
|
|
394
|
+
"""Initialize priority queue."""
|
|
395
|
+
# self.pq = Fibonacci_heap()
|
|
396
|
+
# self.entry_finder = {}
|
|
397
|
+
self.pq = [] # list of entries arranged in a heap
|
|
398
|
+
self.entry_finder = {} # mapping of items to entries
|
|
399
|
+
self.counter = count() # unique sequence count
|
|
400
|
+
|
|
401
|
+
def add_or_update(self, item, priority=0):
|
|
402
|
+
"""Add a new item or update the priority of an existing item."""
|
|
403
|
+
# if item in self.entry_finder:
|
|
404
|
+
# self.pq.decrease_key(self.entry_finder[item], priority)
|
|
405
|
+
# else:
|
|
406
|
+
# entry = self.pq.enqueue(item, priority)
|
|
407
|
+
# self.entry_finder[item] = entry
|
|
408
|
+
if item in self.entry_finder:
|
|
409
|
+
self.remove(item)
|
|
410
|
+
count = next(self.counter)
|
|
411
|
+
entry = [priority, count, item]
|
|
412
|
+
self.entry_finder[item] = entry
|
|
413
|
+
heappush(self.pq, entry)
|
|
414
|
+
|
|
415
|
+
def remove(self, item):
|
|
416
|
+
"""Mark an existing item as REMOVED. Raise KeyError if not found."""
|
|
417
|
+
entry = self.entry_finder.pop(item)
|
|
418
|
+
entry[-1] = self.REMOVED
|
|
419
|
+
|
|
420
|
+
def pop(self):
|
|
421
|
+
"""Remove and return the lowest priority task. Raise error if empty."""
|
|
422
|
+
while self.pq:
|
|
423
|
+
priority, count, item = heappop(self.pq)
|
|
424
|
+
if item is not self.REMOVED:
|
|
425
|
+
del self.entry_finder[item]
|
|
426
|
+
return item
|
|
427
|
+
raise KeyError('pop from an empty priority queue')
|
|
428
|
+
# item = self.pq.dequeue_min().get_value()
|
|
429
|
+
# return item
|
|
430
|
+
|
|
431
|
+
def empty(self):
|
|
432
|
+
"""Return true if the priority queue is empty."""
|
|
433
|
+
return len(self.entry_finder) == 0
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
class SequenceCache(dict):
|
|
437
|
+
def __init__(self, *args, **kwargs):
|
|
438
|
+
self.update(*args, **kwargs)
|
|
439
|
+
|
|
440
|
+
def __contains__(self, key):
|
|
441
|
+
s, t = key
|
|
442
|
+
return dict.__contains__(self, (s, t)) or dict.__contains__(self, (t, s))
|
|
443
|
+
|
|
444
|
+
def __getitem__(self, key):
|
|
445
|
+
s, t = key
|
|
446
|
+
if dict.__contains__(self, (s, t)):
|
|
447
|
+
return dict.__getitem__(self, key)
|
|
448
|
+
elif dict.__contains__(self, (t, s)):
|
|
449
|
+
length, sequence = dict.__getitem__(self, (t, s))
|
|
450
|
+
sequence = [(v, u, i) for u, v, i in reversed(sequence)]
|
|
451
|
+
return length, sequence
|
|
452
|
+
else:
|
|
453
|
+
raise KeyError(key)
|
|
454
|
+
|
|
455
|
+
def add(self, lengths, sequence):
|
|
456
|
+
if sequence:
|
|
457
|
+
s, t = sequence[0][0], sequence[-1][1]
|
|
458
|
+
dict.__setitem__(self, (s, t), (sum(lengths), sequence))
|
|
459
|
+
if len(sequence) > 1:
|
|
460
|
+
s, t = sequence[0][0], sequence[-2][1]
|
|
461
|
+
if (s, t) not in self:
|
|
462
|
+
self.add(lengths[:-1], sequence[:-1])
|
|
463
|
+
s, t = sequence[1][0], sequence[-1][1]
|
|
464
|
+
if (s, t) not in self:
|
|
465
|
+
self.add(lengths[1:], sequence[1:])
|
|
466
|
+
|
|
467
|
+
# def __setitem__(self, key, sequence):
|
|
468
|
+
# dict.__setitem__(self, key, sequence)
|
|
469
|
+
# if len(sequence) > 1:
|
|
470
|
+
# if
|
|
471
|
+
|
|
472
|
+
def __repr__(self):
|
|
473
|
+
dictrepr = dict.__repr__(self)
|
|
474
|
+
return '{}({})'.format(type(self).__name__, dictrepr)
|
|
475
|
+
|
|
476
|
+
def update(self, *args, **kwargs):
|
|
477
|
+
for k, v in dict(*args, **kwargs).items():
|
|
478
|
+
self[k] = v
|
network_topology/topo.py
ADDED
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
"""Module for creating a simplified graph from a set of linestrings."""
|
|
2
|
+
|
|
3
|
+
import networkx as nx
|
|
4
|
+
from triangle import triangulate
|
|
5
|
+
from shapely.geometry import LineString, Point, Polygon, MultiPolygon, mapping
|
|
6
|
+
from shapely.ops import unary_union
|
|
7
|
+
from itertools import combinations
|
|
8
|
+
import numpy as np
|
|
9
|
+
import random
|
|
10
|
+
from rtree import index
|
|
11
|
+
import logging
|
|
12
|
+
import json
|
|
13
|
+
import pyproj
|
|
14
|
+
import shapely
|
|
15
|
+
import os
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger('network-topology')
|
|
18
|
+
logger.setLevel(logging.INFO)
|
|
19
|
+
ch = logging.StreamHandler()
|
|
20
|
+
logger.addHandler(ch)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def getNetworkTopology(lineStrings, thickness=14.0, splitAtTeriminals=None,
|
|
24
|
+
turnThreshold=20.0, minInnerPerimeter=200,
|
|
25
|
+
debugFolder=None):
|
|
26
|
+
"""Generate a bidirectional graph of the topology created by the lines."""
|
|
27
|
+
lineStrings = list(lineStrings)
|
|
28
|
+
# Make buffered shape
|
|
29
|
+
big_shape = _makeBufferedShape(lineStrings, thickness, minInnerPerimeter)
|
|
30
|
+
if debugFolder:
|
|
31
|
+
_dumpBigShape(big_shape, debugFolder)
|
|
32
|
+
|
|
33
|
+
triangles = _triangulate(big_shape, lineStrings, thickness,
|
|
34
|
+
minInnerPerimeter)
|
|
35
|
+
if debugFolder:
|
|
36
|
+
_dumpTriangles(triangles, debugFolder)
|
|
37
|
+
|
|
38
|
+
polygons = _polygonize(triangles, big_shape)
|
|
39
|
+
if debugFolder:
|
|
40
|
+
_dumpPolygons(polygons, triangles, debugFolder)
|
|
41
|
+
|
|
42
|
+
poly_graph = _buildInitialGraph(polygons)
|
|
43
|
+
_tidyIntersections(poly_graph, triangles, polygons)
|
|
44
|
+
skel_graph = _buildSkeletonGraph(poly_graph, triangles, polygons)
|
|
45
|
+
if splitAtTeriminals:
|
|
46
|
+
_insertAtTerminals(skel_graph, splitAtTeriminals)
|
|
47
|
+
graph = _simplifyGraph(skel_graph, turnThreshold, thickness/100.0)
|
|
48
|
+
# _findSegmentsAndIntersections(skel_graph, turnThreshold)
|
|
49
|
+
return graph
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _makeBufferedShape(lineStrings, thickness=14.0, minInnerPerimeter=200):
|
|
53
|
+
logger.info('Creating buffered shape')
|
|
54
|
+
bufferedShapes = []
|
|
55
|
+
buf = thickness / 2.0
|
|
56
|
+
for ls in lineStrings:
|
|
57
|
+
bufferedShapes.append(ls.buffer(buf, quad_segs=2, join_style=3))
|
|
58
|
+
big_shape = unary_union(bufferedShapes)
|
|
59
|
+
if big_shape.geom_type == 'MultiPolygon':
|
|
60
|
+
filled_shape = MultiPolygon([Polygon(g.exterior.coords,
|
|
61
|
+
[ring.coords for ring in g.interiors
|
|
62
|
+
if ring.length > minInnerPerimeter])
|
|
63
|
+
for g in big_shape.geoms])
|
|
64
|
+
else:
|
|
65
|
+
filled_shape = Polygon(big_shape.exterior.coords,
|
|
66
|
+
[ring.coords for ring in big_shape.interiors
|
|
67
|
+
if ring.length > minInnerPerimeter])
|
|
68
|
+
bs = filled_shape.simplify(thickness/10.0)
|
|
69
|
+
logger.info('Completed buffered shape')
|
|
70
|
+
return bs
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _triangulate(big_shape, lineStrings, thickness=14.0, minInnerPerimeter=200):
|
|
74
|
+
logger.info('Reticulating shape')
|
|
75
|
+
tri = {
|
|
76
|
+
'vertices': [],
|
|
77
|
+
'segments': []
|
|
78
|
+
}
|
|
79
|
+
if big_shape.geom_type == 'MultiPolygon':
|
|
80
|
+
geoms = big_shape.geoms
|
|
81
|
+
else:
|
|
82
|
+
geoms = [big_shape]
|
|
83
|
+
for shape in geoms:
|
|
84
|
+
lastIndex = len(tri['vertices'])
|
|
85
|
+
tri['vertices'].append(list(shape.exterior.coords[0]))
|
|
86
|
+
for x, y in shape.exterior.coords[1:]:
|
|
87
|
+
if [x, y] in tri['vertices']:
|
|
88
|
+
currentIndex = tri['vertices'].index([x, y])
|
|
89
|
+
else:
|
|
90
|
+
currentIndex = len(tri['vertices'])
|
|
91
|
+
tri['vertices'].append([x, y])
|
|
92
|
+
tri['segments'].append([lastIndex, currentIndex])
|
|
93
|
+
lastIndex = currentIndex
|
|
94
|
+
|
|
95
|
+
if shape.interiors and 'holes' not in tri:
|
|
96
|
+
tri['holes'] = []
|
|
97
|
+
for ring in shape.interiors:
|
|
98
|
+
if ring.length > minInnerPerimeter:
|
|
99
|
+
x, y = 0, 0
|
|
100
|
+
minx, miny, maxx, maxy = ring.bounds
|
|
101
|
+
while not Polygon(ring).contains(Point(x, y)):
|
|
102
|
+
x = random.uniform(minx, maxx)
|
|
103
|
+
y = random.uniform(miny, maxy)
|
|
104
|
+
tri['holes'].append([x, y])
|
|
105
|
+
lastIndex = len(tri['vertices'])
|
|
106
|
+
tri['vertices'].append(list(ring.coords[0]))
|
|
107
|
+
for x, y in ring.coords[1:]:
|
|
108
|
+
if [x, y] in tri['vertices']:
|
|
109
|
+
currentIndex = tri['vertices'].index([x, y])
|
|
110
|
+
else:
|
|
111
|
+
currentIndex = len(tri['vertices'])
|
|
112
|
+
tri['vertices'].append([x, y])
|
|
113
|
+
tri['segments'].append([lastIndex, currentIndex])
|
|
114
|
+
lastIndex = currentIndex
|
|
115
|
+
|
|
116
|
+
for ls in lineStrings:
|
|
117
|
+
if ls.geom_type == 'LineString':
|
|
118
|
+
geoms = [ls]
|
|
119
|
+
else:
|
|
120
|
+
geoms = ls.geoms
|
|
121
|
+
for geom in geoms:
|
|
122
|
+
for i in [0, -1]:
|
|
123
|
+
coords = list(geom.coords[i])
|
|
124
|
+
if coords not in tri['vertices']:
|
|
125
|
+
tri['vertices'].append(coords)
|
|
126
|
+
tri = triangulate(tri, 'pq0Da{}i'.format(thickness**2.0))
|
|
127
|
+
logger.info('Reticulating complete')
|
|
128
|
+
return tri
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _polygonize(res, big_shape):
|
|
132
|
+
logger.info('Removing internal nodes')
|
|
133
|
+
interior_pts = {}
|
|
134
|
+
for i, v in enumerate(res['vertex_markers']):
|
|
135
|
+
if v == 0:
|
|
136
|
+
interior_pts[i] = []
|
|
137
|
+
for tri, pts in enumerate(res['triangles']):
|
|
138
|
+
for p in pts:
|
|
139
|
+
if p in interior_pts:
|
|
140
|
+
interior_pts[p].append(tri)
|
|
141
|
+
connectivity_graph = nx.Graph()
|
|
142
|
+
for tris in interior_pts.values():
|
|
143
|
+
if len(tris) > 0:
|
|
144
|
+
for tri in tris[1:]:
|
|
145
|
+
connectivity_graph.add_edge(tris[0], tri)
|
|
146
|
+
polys = []
|
|
147
|
+
for cluster in list(nx.connected_components(connectivity_graph)):
|
|
148
|
+
shape_graph = nx.Graph()
|
|
149
|
+
for tri in cluster:
|
|
150
|
+
for v1, v2 in zip(res['triangles'][tri],
|
|
151
|
+
list(res['triangles'][tri][1:]) +
|
|
152
|
+
[res['triangles'][tri][0]]):
|
|
153
|
+
if v1 not in interior_pts and v2 not in interior_pts:
|
|
154
|
+
shape_graph.add_edge(v1, v2)
|
|
155
|
+
|
|
156
|
+
poly = []
|
|
157
|
+
pt = next(iter(shape_graph.nodes()))
|
|
158
|
+
while pt not in poly:
|
|
159
|
+
poly.append(pt)
|
|
160
|
+
for neighbour in shape_graph.neighbors(pt):
|
|
161
|
+
if neighbour not in poly and len(shape_graph[neighbour]) != 1:
|
|
162
|
+
pt = neighbour
|
|
163
|
+
break
|
|
164
|
+
polys.append(poly)
|
|
165
|
+
remaining_triangles = [list(vs) for i, vs in enumerate(res['triangles'])
|
|
166
|
+
if i not in connectivity_graph]
|
|
167
|
+
return remaining_triangles + polys
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _mergeShapes(cluster, TG, polys):
|
|
171
|
+
combined_graph = nx.Graph()
|
|
172
|
+
for shape in cluster:
|
|
173
|
+
if len(polys[shape]) == 0:
|
|
174
|
+
continue
|
|
175
|
+
for p1, p2 in zip(polys[shape], polys[shape][1:] + [polys[shape][0]]):
|
|
176
|
+
if combined_graph.has_edge(p1, p2):
|
|
177
|
+
combined_graph.remove_edge(p1, p2)
|
|
178
|
+
if not combined_graph[p1]:
|
|
179
|
+
combined_graph.remove_node(p1)
|
|
180
|
+
if not combined_graph[p2]:
|
|
181
|
+
combined_graph.remove_node(p2)
|
|
182
|
+
else:
|
|
183
|
+
combined_graph.add_edge(p1, p2)
|
|
184
|
+
poly = []
|
|
185
|
+
pt = next(iter(combined_graph.nodes()))
|
|
186
|
+
while pt not in poly:
|
|
187
|
+
poly.append(pt)
|
|
188
|
+
for neighbour in combined_graph.neighbors(pt):
|
|
189
|
+
if neighbour not in poly:
|
|
190
|
+
pt = neighbour
|
|
191
|
+
break
|
|
192
|
+
cluster = list(cluster)
|
|
193
|
+
base = cluster[0]
|
|
194
|
+
polys[base] = poly
|
|
195
|
+
for shape in cluster[1:]:
|
|
196
|
+
polys[shape] = []
|
|
197
|
+
if shape in TG:
|
|
198
|
+
for n, d in TG[shape].items():
|
|
199
|
+
if n != base:
|
|
200
|
+
TG.add_edge(base, n, **d)
|
|
201
|
+
TG.remove_node(shape)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _buildInitialGraph(polys):
|
|
205
|
+
logger.info('Build polygon graph')
|
|
206
|
+
edge_tri = {}
|
|
207
|
+
TG = nx.Graph()
|
|
208
|
+
|
|
209
|
+
def add_edge(n1, n2, tri, edges, TG):
|
|
210
|
+
n1, n2 = sorted([n1, n2])
|
|
211
|
+
if (n1, n2) not in edges:
|
|
212
|
+
edges[n1, n2] = []
|
|
213
|
+
for other in edges[n1, n2]:
|
|
214
|
+
TG.add_edge(tri, other, v1=n1, v2=n2)
|
|
215
|
+
edges[n1, n2].append(tri)
|
|
216
|
+
|
|
217
|
+
for i, t in enumerate(polys):
|
|
218
|
+
for t1, t2 in zip(t[:-1], t[1:]):
|
|
219
|
+
add_edge(t1, t2, i, edge_tri, TG)
|
|
220
|
+
add_edge(t[0], t[-1], i, edge_tri, TG)
|
|
221
|
+
|
|
222
|
+
# Collapse internal edges
|
|
223
|
+
central_shapes = [t for t in TG.nodes() if len(TG[t]) > 2]
|
|
224
|
+
SG = TG.subgraph(central_shapes)
|
|
225
|
+
clusters = list(nx.connected_components(SG))
|
|
226
|
+
|
|
227
|
+
for cluster in clusters:
|
|
228
|
+
_mergeShapes(cluster, TG, polys)
|
|
229
|
+
|
|
230
|
+
logger.info('Polygon graph complete')
|
|
231
|
+
return TG
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _tidyIntersections(TG, res, polys):
|
|
235
|
+
logger.info('Tyding intersections')
|
|
236
|
+
# 'Tyding T-intersections...'
|
|
237
|
+
toMerge = []
|
|
238
|
+
for node in TG.nodes():
|
|
239
|
+
if TG.degree(node) == 3 and len(polys[node]) == 3:
|
|
240
|
+
points = res['vertices'][polys[node]]
|
|
241
|
+
A = np.array([[p[0]*p[0] + p[1]*p[1], p[0], p[1], 1]
|
|
242
|
+
for p in points])
|
|
243
|
+
M11 = np.linalg.det(A[:, [1, 2, 3]])
|
|
244
|
+
M12 = np.linalg.det(A[:, [0, 2, 3]])
|
|
245
|
+
M13 = np.linalg.det(A[:, [0, 1, 3]])
|
|
246
|
+
M14 = np.linalg.det(A[:, [0, 1, 2]])
|
|
247
|
+
x = 0.5 * M12/M11
|
|
248
|
+
y = -0.5 * M13/M11
|
|
249
|
+
r2 = M14/M11 + x*x + y*y
|
|
250
|
+
TG.nodes[node]['centroid'] = [x, y]
|
|
251
|
+
centroid = Point(x,y)
|
|
252
|
+
|
|
253
|
+
for neighbour, data in TG[node].items():
|
|
254
|
+
points = list(polys[neighbour])
|
|
255
|
+
poly = Polygon([res['vertices'][p] for p in points])
|
|
256
|
+
points.remove(data['v1'])
|
|
257
|
+
points.remove(data['v2'])
|
|
258
|
+
point = res['vertices'][points[0]]
|
|
259
|
+
dx = x - point[0]
|
|
260
|
+
dy = y - point[1]
|
|
261
|
+
if dx*dx + dy*dy < 4*r2 or poly.contains(centroid):
|
|
262
|
+
toMerge.append([node, neighbour])
|
|
263
|
+
|
|
264
|
+
for cluster in toMerge:
|
|
265
|
+
_mergeShapes(cluster, TG, polys)
|
|
266
|
+
|
|
267
|
+
logger.info('Tyding complete')
|
|
268
|
+
# 'Cleaning up angled crossings...'
|
|
269
|
+
# toMerge = []
|
|
270
|
+
# for node in TG.nodes_iter():
|
|
271
|
+
# if TG.degree(node) == 2:
|
|
272
|
+
# sandwiched = True
|
|
273
|
+
# for neighbour in TG[node]:
|
|
274
|
+
# if TG.degree(neighbour) == 2:
|
|
275
|
+
# sandwiched = False
|
|
276
|
+
# if sandwiched:
|
|
277
|
+
# toMerge.append([node] + TG[node].keys())
|
|
278
|
+
#
|
|
279
|
+
# for cluster in toMerge:
|
|
280
|
+
# _mergeShapes(cluster, TG, polys)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _makeKey(t1, t2):
|
|
284
|
+
t1, t2 = sorted([t1, t2])
|
|
285
|
+
return int(t1 * 1e9 + t2)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _normalVector(G, n1, n2):
|
|
289
|
+
ux = G.nodes[n1]['x'] - G.nodes[n2]['x']
|
|
290
|
+
uy = G.nodes[n1]['y'] - G.nodes[n2]['y']
|
|
291
|
+
dist = max(np.sqrt(ux*ux + uy*uy), 1e-18)
|
|
292
|
+
ux /= dist
|
|
293
|
+
uy /= dist
|
|
294
|
+
return ux, uy
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _insertEdge(G, n1, n2, terminal=False):
|
|
298
|
+
if n1 == n2:
|
|
299
|
+
return
|
|
300
|
+
ux, uy = _normalVector(G, n1, n2)
|
|
301
|
+
G.add_edge(n1, n2, ux=ux, uy=uy, terminal=terminal)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _buildSkeletonGraph(TG, res, polys):
|
|
305
|
+
logger.info('Building skeleton graph')
|
|
306
|
+
node_idx = index.Index()
|
|
307
|
+
G = nx.Graph(index=node_idx)
|
|
308
|
+
for t1, t2, d in TG.edges(data=True):
|
|
309
|
+
x = (res['vertices'][d['v1']][0] + res['vertices'][d['v2']][0])/2.0
|
|
310
|
+
y = (res['vertices'][d['v1']][1] + res['vertices'][d['v2']][1])/2.0
|
|
311
|
+
key = _makeKey(t1, t2)
|
|
312
|
+
node_idx.insert(key, (x, y, x, y))
|
|
313
|
+
G.add_node(key, x=x, y=y)
|
|
314
|
+
|
|
315
|
+
for t, d in TG.nodes(data=True):
|
|
316
|
+
if len(TG[t]) == 2:
|
|
317
|
+
pairs = []
|
|
318
|
+
for t2 in TG[t]:
|
|
319
|
+
key = _makeKey(t, t2)
|
|
320
|
+
if key in G:
|
|
321
|
+
pairs.append(key)
|
|
322
|
+
for e1, e2 in combinations(pairs, 2):
|
|
323
|
+
_insertEdge(G, e1, e2)
|
|
324
|
+
else: # if len(TG[t]) != 2:
|
|
325
|
+
if 'centroid' in TG.nodes[t]:
|
|
326
|
+
x, y = TG.nodes[t]['centroid']
|
|
327
|
+
elif len(polys[t]) > 2:
|
|
328
|
+
# calc centroid & add to graph
|
|
329
|
+
poly = Polygon([list(res['vertices'][v])
|
|
330
|
+
for v in polys[t]])
|
|
331
|
+
x, y = poly.centroid.coords[0]
|
|
332
|
+
else:
|
|
333
|
+
x, y = zip(*[list(res['vertices'][v])
|
|
334
|
+
for v in polys[t]])
|
|
335
|
+
x = sum(x)/len(x)
|
|
336
|
+
y = sum(y)/len(y)
|
|
337
|
+
|
|
338
|
+
G.add_node(t, x=x, y=y)
|
|
339
|
+
node_idx.insert(t, [x, y, x, y])
|
|
340
|
+
# join all edges to centroid
|
|
341
|
+
for t2 in TG[t]:
|
|
342
|
+
key = _makeKey(t, t2)
|
|
343
|
+
_insertEdge(G, t, key)
|
|
344
|
+
logger.info('Skeleton graph complete')
|
|
345
|
+
return G
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _insertAtTerminals(G, points):
|
|
349
|
+
logger.info('Inserting terminal nodes')
|
|
350
|
+
node_idx = G.graph['index']
|
|
351
|
+
terminals = []
|
|
352
|
+
#for lid, ls in enumerate(lineStrings):
|
|
353
|
+
# for i in [0, -1]:
|
|
354
|
+
# point = ls.coords[i]
|
|
355
|
+
for i, point in enumerate(points):
|
|
356
|
+
nearest = list(node_idx.nearest(point.bounds, num_results=1))[0]
|
|
357
|
+
pid = -float(i) #-float(lid) + 0.1 * i
|
|
358
|
+
terminals.append((pid, point, nearest))
|
|
359
|
+
for pid, point, nearest in terminals:
|
|
360
|
+
G.add_node(pid, x=point.x, y=point.y, terminal=True)
|
|
361
|
+
_insertEdge(G, pid, nearest, terminal=True)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _simplifyGraph(G, turnThreshold=20.0, simplifyTolerance=0):
|
|
365
|
+
logger.info('Simplifying graph')
|
|
366
|
+
DG = nx.MultiDiGraph()
|
|
367
|
+
threshold = np.cos(turnThreshold/180.0*np.pi)
|
|
368
|
+
for node in G.nodes():
|
|
369
|
+
if node not in DG:
|
|
370
|
+
DG.add_node(node, x=G.nodes[node]['x'], y=G.nodes[node]['y'])
|
|
371
|
+
else:
|
|
372
|
+
DG.nodes[node]['x'] = G.nodes[node]['x']
|
|
373
|
+
DG.nodes[node]['y'] = G.nodes[node]['y']
|
|
374
|
+
if len(G[node]) == 2:
|
|
375
|
+
normals = []
|
|
376
|
+
for neighbour in G[node]:
|
|
377
|
+
n = _normalVector(G, node, neighbour)
|
|
378
|
+
normals.append(n)
|
|
379
|
+
dp = -(normals[0][0] * normals[1][0] +
|
|
380
|
+
normals[0][1] * normals[1][1])
|
|
381
|
+
DG.nodes[node]['turn'] = dp < threshold
|
|
382
|
+
if 'terminal' in G.nodes[node]:
|
|
383
|
+
DG.nodes[node]['terminal'] = True
|
|
384
|
+
for neighbour in G[node]:
|
|
385
|
+
DG.add_edge(node, neighbour, nnodes=[node, neighbour],
|
|
386
|
+
terminal=G[node][neighbour]['terminal'])
|
|
387
|
+
to_remove = []
|
|
388
|
+
for node in DG.nodes():
|
|
389
|
+
if len(DG.edges(node)) == 2 and not DG.nodes[node]['turn'] and node not in DG.neighbors(node):
|
|
390
|
+
(x, n1), (x, n2) = DG.edges(node)
|
|
391
|
+
if DG[node][n1][0]['terminal'] or DG[node][n2][0]['terminal']:
|
|
392
|
+
continue
|
|
393
|
+
seq = DG[n1][node][0]['nnodes'] + DG[node][n2][0]['nnodes'][1:]
|
|
394
|
+
DG.add_edge(n1, n2, nnodes=seq, terminal=False)
|
|
395
|
+
DG.add_edge(n2, n1, nnodes=list(reversed(seq)), terminal=False)
|
|
396
|
+
to_remove.append(node)
|
|
397
|
+
DG.remove_edge(n1, node)
|
|
398
|
+
DG.remove_edge(node, n1)
|
|
399
|
+
DG.remove_edge(n2, node)
|
|
400
|
+
DG.remove_edge(node, n2)
|
|
401
|
+
#if 'terminal' in DG.node[node]:
|
|
402
|
+
# to_remove.append(node)
|
|
403
|
+
for node in to_remove:
|
|
404
|
+
DG.remove_node(node)
|
|
405
|
+
for s, t, data in DG.edges(data=True):
|
|
406
|
+
coords = []
|
|
407
|
+
for node in data['nnodes']:
|
|
408
|
+
coords.append((G.nodes[node]['x'], G.nodes[node]['y']))
|
|
409
|
+
ls = LineString(coords).simplify(simplifyTolerance)
|
|
410
|
+
data['geom'] = ls
|
|
411
|
+
data['length'] = ls.length
|
|
412
|
+
for node, data in DG.nodes(data=True):
|
|
413
|
+
data['geom'] = Point(G.nodes[node]['x'], G.nodes[node]['y'])
|
|
414
|
+
logger.info('Simplificaiton complete')
|
|
415
|
+
return DG
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _utm_proj(lon_like):
|
|
419
|
+
zone = (int((lon_like + 180) / 6) % 60) + 1
|
|
420
|
+
return pyproj.Proj(proj='utm', zone=zone, ellps='WGS84')
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _write_polygon_geojson(vertex_groups, triangles, utm_proj, path):
|
|
424
|
+
features = []
|
|
425
|
+
for vs in vertex_groups:
|
|
426
|
+
coord_list = [
|
|
427
|
+
list(utm_proj(*triangles['vertices'][v], inverse=True))
|
|
428
|
+
for v in vs
|
|
429
|
+
]
|
|
430
|
+
if not coord_list:
|
|
431
|
+
continue
|
|
432
|
+
features.append({
|
|
433
|
+
"type": "Feature",
|
|
434
|
+
"properties": {'stroke-opacity': 0.25},
|
|
435
|
+
"geometry": {
|
|
436
|
+
"type": "Polygon",
|
|
437
|
+
"coordinates": [coord_list],
|
|
438
|
+
},
|
|
439
|
+
})
|
|
440
|
+
data = {"type": "FeatureCollection", "features": features}
|
|
441
|
+
with open(path, 'w') as fp:
|
|
442
|
+
json.dump(data, fp)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _dumpBigShape(big_shape, debugFolder):
|
|
446
|
+
first_geom = big_shape.geoms[0] if big_shape.geom_type == 'MultiPolygon' else big_shape
|
|
447
|
+
utm_proj = _utm_proj(first_geom.exterior.coords[0][0])
|
|
448
|
+
transformer = pyproj.Transformer.from_crs(
|
|
449
|
+
utm_proj.crs, "EPSG:4326", always_xy=True
|
|
450
|
+
)
|
|
451
|
+
projected = shapely.transform(
|
|
452
|
+
big_shape,
|
|
453
|
+
lambda coords: np.column_stack(
|
|
454
|
+
transformer.transform(coords[:, 0], coords[:, 1])
|
|
455
|
+
),
|
|
456
|
+
)
|
|
457
|
+
with open(os.path.join(debugFolder, 'bigshape.geojson'), 'w') as fp:
|
|
458
|
+
json.dump(mapping(projected), fp)
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _dumpTriangles(triangles, debugFolder):
|
|
462
|
+
utm_proj = _utm_proj(triangles['vertices'][0][0])
|
|
463
|
+
_write_polygon_geojson(
|
|
464
|
+
triangles['triangles'],
|
|
465
|
+
triangles,
|
|
466
|
+
utm_proj,
|
|
467
|
+
os.path.join(debugFolder, 'triangles.geojson'),
|
|
468
|
+
)
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _dumpPolygons(polygons, triangles, debugFolder):
|
|
472
|
+
utm_proj = _utm_proj(triangles['vertices'][0][0])
|
|
473
|
+
_write_polygon_geojson(
|
|
474
|
+
polygons,
|
|
475
|
+
triangles,
|
|
476
|
+
utm_proj,
|
|
477
|
+
os.path.join(debugFolder, 'polygons.geojson'),
|
|
478
|
+
)
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: network-topology
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Simplify overlapping lines into a single graph
|
|
5
|
+
Author-email: Mike Boos <mike.boos@tritag.ca>
|
|
6
|
+
License-Expression: BSD-3-Clause
|
|
7
|
+
Project-URL: Homepage, https://github.com/TriTAG/network-topology
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: license.txt
|
|
16
|
+
Requires-Dist: shapely>=2.0
|
|
17
|
+
Requires-Dist: triangle
|
|
18
|
+
Requires-Dist: networkx>=2.4
|
|
19
|
+
Requires-Dist: numpy
|
|
20
|
+
Requires-Dist: rtree
|
|
21
|
+
Requires-Dist: pyproj>=2.6
|
|
22
|
+
Provides-Extra: test
|
|
23
|
+
Requires-Dist: pytest; extra == "test"
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# network-topology
|
|
27
|
+
Simplifies overlapping lines into a single graph
|
|
28
|
+
|
|
29
|
+
## Usage
|
|
30
|
+
```python
|
|
31
|
+
import network_topology
|
|
32
|
+
from shapely.geometry import LineString
|
|
33
|
+
|
|
34
|
+
linestrings = {'route 1': LineString([[...]], ...}
|
|
35
|
+
|
|
36
|
+
# Create a NetworkX MultiDiGraph from a list of linestrings
|
|
37
|
+
simplified_graph = network_topology.getNetworkTopology(linestrings.values(),
|
|
38
|
+
thickness=30.0,
|
|
39
|
+
minInnerPerimeter=100)
|
|
40
|
+
# Each edge of simplified_graph will have a 'geom' attribute, a LineString
|
|
41
|
+
# from the start node to the end node of that edge.
|
|
42
|
+
|
|
43
|
+
# Get a list of all the edges in simplified_graph that each linestring traverses
|
|
44
|
+
route_edges = network_topology.getMatchedRoutes(linestrings,
|
|
45
|
+
simplified_graph)
|
|
46
|
+
# route_edges = {'route_1': [(0, 1, 0), (1, 2, 0), ...], ...}
|
|
47
|
+
```
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
network_topology/__init__.py,sha256=T_1Tg8gnavM34N8BWMsmfCFhPcIdhieJbmJ_1kmuPJY,73
|
|
2
|
+
network_topology/match.py,sha256=tj-eddkQ468aLiwRTTu090tDwjiXMo9vM6A9bEOdq28,17451
|
|
3
|
+
network_topology/topo.py,sha256=LKJOrxjCpeKanvaFo2YadNw5vOnB3dsHN7vnHTgjGXA,17118
|
|
4
|
+
network_topology-0.3.0.dist-info/licenses/license.txt,sha256=L0AzODK_K0mj14Wtf1OxEkTQ5Z0nRhFrW2WIwjQPEY0,1889
|
|
5
|
+
network_topology-0.3.0.dist-info/METADATA,sha256=G3rW_IY8BGTcBM486_x2wbfTyZMszDnt-RDR_3uL8lU,1729
|
|
6
|
+
network_topology-0.3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
network_topology-0.3.0.dist-info/top_level.txt,sha256=Goajh1pcHKWPJMZvTNC5Dn1MCXa6DQcacuLEMEpW4tA,17
|
|
8
|
+
network_topology-0.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
License
|
|
2
|
+
=======
|
|
3
|
+
|
|
4
|
+
Network-topology is distributed with the 3-clause BSD license.
|
|
5
|
+
|
|
6
|
+
::
|
|
7
|
+
Copyright (C) 2017
|
|
8
|
+
Mike Boos <mike.boos@tritag.ca>
|
|
9
|
+
|
|
10
|
+
AStar algorithm uses code from NetworkX:
|
|
11
|
+
Copyright (C) 2004-2017, NetworkX Developers
|
|
12
|
+
Aric Hagberg <hagberg@lanl.gov>
|
|
13
|
+
Dan Schult <dschult@colgate.edu>
|
|
14
|
+
Pieter Swart <swart@lanl.gov>
|
|
15
|
+
All rights reserved.
|
|
16
|
+
|
|
17
|
+
Redistribution and use in source and binary forms, with or without
|
|
18
|
+
modification, are permitted provided that the following conditions are
|
|
19
|
+
met:
|
|
20
|
+
|
|
21
|
+
* Redistributions of source code must retain the above copyright
|
|
22
|
+
notice, this list of conditions and the following disclaimer.
|
|
23
|
+
|
|
24
|
+
* Redistributions in binary form must reproduce the above
|
|
25
|
+
copyright notice, this list of conditions and the following
|
|
26
|
+
disclaimer in the documentation and/or other materials provided
|
|
27
|
+
with the distribution.
|
|
28
|
+
|
|
29
|
+
* Neither the name of the NetworkX Developers nor the names of its
|
|
30
|
+
contributors may be used to endorse or promote products derived
|
|
31
|
+
from this software without specific prior written permission.
|
|
32
|
+
|
|
33
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
34
|
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
35
|
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
36
|
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
37
|
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
38
|
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
39
|
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
40
|
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
41
|
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
42
|
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
43
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
network_topology
|