/
util.py
634 lines (455 loc) · 16.7 KB
/
util.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
from warnings import warn
from libpysal import cg
from libpysal.common import requires
from rtree import Rtree
import numpy
try:
import geopandas
from shapely.geometry import Point, LineString
except ImportError:
err_msg = (
"geopandas/shapely not available. " + "Some functionality will be disabled."
)
warn(err_msg)
def compute_length(v0, v1):
"""Compute the euclidean distance between two points.
Parameters
----------
v0 : tuple
Coordinate sequence in the form x,y.
vq : tuple
Coordinate sequence in the form x,y.
Returns
--------
euc_dist : float
Euclidean distance.
Examples
--------
>>> import spaghetti
>>> point1, point2 = (0,0), (1,1)
>>> spaghetti.util.compute_length(point1, point2)
1.4142135623730951
"""
euc_dist = cg.standalone.get_points_dist(v0, v1)
return euc_dist
def get_neighbor_distances(ntw, v0, l):
"""Get distances to the nearest vertex neighbors along
connecting arcs.
Parameters
----------
ntw : spaghetti.Network
A spaghetti network object.
v0 : int
The vertex ID.
l : dict
The key is a tuple (start vertex, end vertex); value is ``float``.
Cost per arc to travel, e.g. distance.
Returns
-------
neighbors : dict
The key is an integer (vertex ID); value is ``float`` (distance).
Examples
--------
>>> import spaghetti
>>> from libpysal import examples
>>> ntw = spaghetti.Network(examples.get_path("streets.shp"))
>>> neighs = spaghetti.util.get_neighbor_distances(ntw, 0, ntw.arc_lengths)
>>> neighs[1]
102.62353453439829
"""
# fetch links associated with vertices
arcs = ntw.enum_links_vertex(v0)
# create neighbor distance lookup
neighbors = {}
# iterate over each associated link
for arc in arcs:
# set distance from vertex1 to vertex2 (link length)
if arc[0] != v0:
neighbors[arc[0]] = l[arc]
else:
neighbors[arc[1]] = l[arc]
return neighbors
def generatetree(pred):
"""Rebuild the shortest path from root origin to destination.
Parameters
----------
pred : list
List of preceding vertices for traversal route.
Returns
--------
tree : dict
The key is the root origin; value is the root origin to destination.
Examples
--------
>>> import spaghetti
>>> from libpysal import examples
>>> ntw = spaghetti.Network(examples.get_path("streets.shp"))
>>> distance, pred = spaghetti.util.dijkstra(ntw, 0)
>>> tree = spaghetti.util.generatetree(pred)
>>> tree[3]
[23, 22, 20, 19, 170, 2, 0]
"""
# instantiate tree lookup
tree = {}
# iterate over the list of predecessor vertices
for i, p in enumerate(pred):
# if the route begins/ends with itself set the
# root vertex and continue to next iteration
if p == -1:
# tree keyed by root vertex with root vertex as path
tree[i] = [i]
continue
# set the initial vertex `p` as `idx`
idx = p
# and add it as the first vertex in the path
path = [idx]
# iterate through the path until back to home vertex
while idx >= 0:
# set the next vertex on the path
next_vertex = pred[idx]
# and redeclare the current `idx`
idx = next_vertex
# add the vertex to path while not at home vertex
if idx >= 0:
path.append(next_vertex)
# tree keyed by root vertex with network vertices as path
tree[i] = path
return tree
def dijkstra(ntw, v0, initial_dist=numpy.inf):
"""Compute the shortest path between a start vertex and
all other vertices in an origin-destination matrix.
Parameters
----------
ntw : spaghetti.Network
A spaghetti network object.
v0 : int
Start vertex ID.
initial_dist : float
Integer break point to stop iteration and return n neighbors.
Default is ``numpy.inf``.
Returns
-------
distance : list
List of distances from vertex to all other vertices.
pred : list
List of preceeding vertices for traversal route.
Notes
-----
Based on :cite:`Dijkstra1959a`.
Examples
--------
>>> import spaghetti
>>> from libpysal import examples
>>> ntw = spaghetti.Network(examples.get_path("streets.shp"))
>>> distance, pred = spaghetti.util.dijkstra(ntw, 0)
>>> round(distance[196], 4)
5505.6682
>>> pred[196]
133
"""
# cost per arc to travel, e.g. distance
cost = ntw.arc_lengths
# initialize travel costs as `inf` for all distances
distance = [initial_dist for x in ntw.vertex_list]
# label distance to self as 0
distance[ntw.vertex_list.index(v0)] = 0
# instantiate set of unvisited vertices
unvisited = set([v0])
# initially label as predecessor vertices with -1 as path
pred = [-1 for x in ntw.vertex_list]
# iterate over `unvisited` until all vertices have been visited
while len(unvisited) > 0:
# get vertex with the lowest value from distance
dist = initial_dist
for vertex in unvisited:
if distance[vertex] < dist:
dist = distance[vertex]
current = vertex
# remove that vertex from the set
unvisited.remove(current)
# get the neighbors (and costs) to the current vertex
neighbors = get_neighbor_distances(ntw, current, cost)
# iterate over neighbors to find least cost along path
for v1, indiv_cost in neighbors.items():
# if the labeled cost is greater than
# the currently calculated cost
if distance[v1] > distance[current] + indiv_cost:
# relabel to the currently calculated cost
distance[v1] = distance[current] + indiv_cost
# set the current vertex as a predecessor on the path
pred[v1] = current
# add the neighbor vertex to `unvisted`
unvisited.add(v1)
# cast preceding vertices list as an array of integers
pred = numpy.array(pred, dtype=numpy.int)
return distance, pred
def dijkstra_mp(ntw_vertex):
"""Compute the shortest path between a start vertex and all other
vertices in the matrix utilizing multiple cores upon request.
Parameters
----------
ntw_vertex : tuple
Tuple of arguments to pass into ``dijkstra()`` as
(1) ``ntw`` - ``spaghetti.Network object``;
(2) ``vertex`` - int (start node ID)
Returns
-------
distance : list
List of distances from vertex to all other vertices.
pred : list
List of preceeding vertices for traversal route.
Notes
-----
Based on :cite:`Dijkstra1959a`.
Examples
--------
>>> import spaghetti
>>> from libpysal import examples
>>> ntw = spaghetti.Network(examples.get_path("streets.shp"))
>>> distance, pred = spaghetti.util.dijkstra_mp((ntw, 0))
>>> round(distance[196], 4)
5505.6682
>>> pred[196]
133
"""
# unpack network object and source vertex
ntw, vertex = ntw_vertex
# calculate shortest path distances and predecessor vertices
distance, pred = dijkstra(ntw, vertex)
return distance, pred
def squared_distance_point_link(point, link):
"""Find the squared distance between a point and a link.
Parameters
----------
point : tuple
Point coordinates (x,y).
link : list
List of 2 point coordinate tuples [(x0, y0), (x1, y1)].
Returns
-------
sqd : float
The distance squared between the point and edge.
nearp : numpy.ndarray
An array of (xb, yb); the nearest point on the edge.
Examples
--------
>>> import spaghetti
>>> point, link = (1,1), ((0,0), (2,0))
>>> spaghetti.util.squared_distance_point_link(point, link)
(1.0, array([1., 0.]))
"""
# cast vertices comprising the network link as an array
p0, p1 = [numpy.array(p) for p in link]
# cast the observation point as an array
p = numpy.array(point)
# subtract point 0 coords from point 1
v = p1 - p0
# subtract point 0 coords from the observation coords
w = p - p0
# if the point 0 vertex is the closest point along the link
c1 = numpy.dot(w, v)
if c1 <= 0.0:
sqd = numpy.dot(w.T, w)
nearp = p0
return sqd, nearp
# if the point 1 vertex is the closest point along the link
c2 = numpy.dot(v, v)
if c2 <= c1:
dp1 = p - p1
sqd = numpy.dot(dp1.T, dp1)
nearp = p1
return sqd, nearp
# otherwise the closest point along the link lies between p0 and p1
b = c1 / c2
bv = numpy.dot(b, v)
pb = p0 + bv
d2 = p - pb
sqd = numpy.dot(d2, d2)
nearp = pb
return sqd, nearp
def snap_points_to_links(points, links):
"""Place points onto closest link in a set of links (arc/edges).
Parameters
----------
points : dict
Point ID as key and (x,y) coordinate as value.
links : list
Elements are of type ``libpysal.cg.shapes.Chain``
** Note ** each element is a link represented as a chain with
*one head and one tail vertex* in other words one link only.
Returns
-------
point2link : dict
Key [point ID (see points in arguments)]; value [a 2-tuple
((head, tail), point) where (head, tail) is the target link,
and point is the snapped location on the link.
Examples
--------
>>> import spaghetti
>>> from libpysal.cg.shapes import Point, Chain
>>> points = {0: Point((1,1))}
>>> link = [Chain([Point((0,0)), Point((2,0))])]
>>> spaghetti.util.snap_points_to_links(points, link)
{0: ([(0.0, 0.0), (2.0, 0.0)], array([1., 0.]))}
"""
# instantiate an rtree
rtree = Rtree()
# set the smallest possible float epsilon on machine
SMALL = numpy.finfo(float).eps
# initialize network vertex to link lookup
vertex_2_link = {}
# iterate over network links
for i, link in enumerate(links):
# extract network link (x,y) vertex coordinates
head, tail = link.vertices
x0, y0 = head
x1, y1 = tail
if (x0, y0) not in vertex_2_link:
vertex_2_link[(x0, y0)] = []
if (x1, y1) not in vertex_2_link:
vertex_2_link[(x1, y1)] = []
vertex_2_link[(x0, y0)].append(link)
vertex_2_link[(x1, y1)].append(link)
# minimally increase the bounding box exterior
bx0, by0, bx1, by1 = link.bounding_box
bx0 -= SMALL
by0 -= SMALL
bx1 += SMALL
by1 += SMALL
# insert the network link and its associated
# rectangle into the rtree
rtree.insert(i, (bx0, by0, bx1, by1), obj=link)
# build a KDtree on link vertices
kdtree = cg.KDTree(list(vertex_2_link.keys()))
point2link = {}
for pt_idx, point in points.items():
# first, find nearest neighbor link vertices for the point
dmin, vertex = kdtree.query(point, k=1)
vertex = tuple(kdtree.data[vertex])
closest = vertex_2_link[vertex][0].vertices
# Use this link as the candidate closest link: closest
# Use the distance as the distance to beat: dmin
point2link[pt_idx] = (closest, numpy.array(vertex))
x0 = point[0] - dmin
y0 = point[1] - dmin
x1 = point[0] + dmin
y1 = point[1] + dmin
# Find all links with bounding boxes that intersect
# a query rectangle centered on the point with sides
# of length dmin * dmin
rtree_lookup = rtree.intersection([x0, y0, x1, y1], objects=True)
candidates = [cand.object for cand in rtree_lookup]
dmin += SMALL
dmin2 = dmin * dmin
# of the candidate arcs, find the nearest to the query point
for candidate in candidates:
dist2cand, nearp = squared_distance_point_link(point, candidate.vertices)
if dist2cand <= dmin2:
closest = candidate.vertices
dmin2 = dist2cand
point2link[pt_idx] = (closest, nearp)
return point2link
@requires("geopandas", "shapely")
def _points_as_gdf(
net, vertices, vertices_for_arcs, pp_name, snapped, id_col=None, geom_col=None
):
"""Internal function for returning a point ``geopandas.GeoDataFrame``
called from within ``spaghetti.element_as_gdf()``.
Parameters
----------
vertices_for_arcs : bool
Flag for points being an object returned (``False``) or for merely
creating network arcs (``True``). Set from within the parent
function (``spaghetti.element_as_gdf()``).
Raises
------
KeyError
In order to extract a ``network.PointPattern`` it must already
be a part of the network object. This exception is raised
when a ``network.PointPattern`` is being extracted that does not
exist within the network object.
Returns
-------
points : geopandas.GeoDataFrame
Network point elements (either vertices or ``network.PointPattern``
points) as a simple ``geopandas.GeoDataFrame`` of
``shapely.geometry.Point`` objects with an ``"id"`` column and
``"geometry"`` column.
Notes
-----
1. See ``spaghetti.element_as_gdf()`` for description of arguments.
2. This function requires ``geopandas``.
"""
# vertices / nodes
if vertices or vertices_for_arcs:
pts_dict = net.vertex_coords
# raw point pattern
if pp_name and not snapped:
try:
pp_pts = net.pointpatterns[pp_name].points
except KeyError:
err_msg = "Available point patterns are {}"
raise KeyError(err_msg.format(list(net.pointpatterns.keys())))
n_pp_pts = range(len(pp_pts))
pts_dict = {point: pp_pts[point]["coordinates"] for point in n_pp_pts}
# snapped point pattern
elif pp_name and snapped:
pts_dict = net.pointpatterns[pp_name].snapped_coordinates
# instantiate geopandas.GeoDataFrame
pts_list = list(pts_dict.items())
points = geopandas.GeoDataFrame(pts_list, columns=[id_col, geom_col])
points.geometry = points.geometry.apply(lambda p: Point(p))
return points
@requires("geopandas", "shapely")
def _arcs_as_gdf(net, points, id_col=None, geom_col=None):
"""Internal function for returning an arc ``geopandas.GeoDataFrame``
called from within ``spaghetti.element_as_gdf()``.
Returns
-------
arcs : geopandas.GeoDataFrame
Network arc elements as a ``geopandas.GeoDataFrame`` of
``shapely.geometry.LineString`` objects with an ``"id"``
column and ``geometry`` column.
Notes
-----
1. See ``spaghetti.element_as_gdf()`` for description of arguments.
2. This function requires ``geopandas``.
"""
# arcs
arcs = {}
# iterate over network arcs
for (vtx1_id, vtx2_id) in net.arcs:
# extract vertices comprising the network arc
vtx1 = points.loc[(points[id_col] == vtx1_id), geom_col].squeeze()
vtx2 = points.loc[(points[id_col] == vtx2_id), geom_col].squeeze()
# create a LineString for the network arc
arcs[(vtx1_id, vtx2_id)] = LineString((vtx1, vtx2))
# instantiate GeoDataFrame
arcs = geopandas.GeoDataFrame(
sorted(list(arcs.items())), columns=[id_col, geom_col]
)
# additional columns
if hasattr(net, "network_component_labels"):
arcs["comp_label"] = net.network_component_labels
return arcs
@requires("geopandas", "shapely")
def _routes_as_gdf(paths, id_col=None, geom_col=None):
"""Internal function for returning a shortest paths
``geopandas.GeoDataFrame`` called from within
``spaghetti.element_as_gdf()``.
Returns
-------
paths : geopandas.GeoDataFrame
Network shortest paths as a ``geopandas.GeoDataFrame`` of
``shapely.geometry.LineString`` objects with an ``"id"``
column and ``geometry`` column.
Notes
-----
1. See ``spaghetti.element_as_gdf()`` for description of arguments.
2. This function requires ``geopandas``.
"""
paths = {k: [LineString(v)] for k, v in paths.items()}
paths = geopandas.GeoDataFrame.from_dict(paths, orient="index")
paths.reset_index(inplace=True)
paths.rename(columns={"index": id_col, 0: geom_col}, inplace=True)
return paths