-
Notifications
You must be signed in to change notification settings - Fork 5
/
my_graph_helpers.py
1308 lines (1020 loc) · 40.2 KB
/
my_graph_helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import shapefile
import math
from collections import defaultdict
import networkx as nx
import random
import itertools
import operator
from scipy.cluster.hierarchy import linkage, dendrogram
import json
# import plotly.plotly as ply
# from plotly.graph_objs import *
import my_graph as mg
""" This file includes a bunch of helper functions for my_graph.py.
There are a bunch of basic spatial geometery functions,
some greedy search probablilty functions,
ways to set up and determine the shortest paths from parcel to a road
the code that exists on optimization problem 2: thinking about how to build in
additional connectivity beyond just minimum access, as well as plotting the
associated matrices
code for creating a mygraph object from a shapefile or a list of myfaces
(used for weak dual calculations)
a couple of test graphs- testGraph, (more or less lollipopo shaped) and
testGraphLattice which is a lattice.
"""
#############################
# BASIC MATH AND GEOMETRY FUNCTIONS
#############################
# myG geometry functions
def distance(mynode0, mynode1):
return np.sqrt(distance_squared(mynode0, mynode1))
def distance_squared(mynode0, mynode1):
return (mynode0.x-mynode1.x)**2+(mynode0.y-mynode1.y)**2
def sq_distance_point_to_segment(target, myedge):
"""returns the square of the minimum distance between mynode
target and myedge. """
n1 = myedge.nodes[0]
n2 = myedge.nodes[1]
if myedge.length == 0:
sq_dist = distance_squared(target, n1)
elif target == n1 or target == n2:
sq_dist = 0
else:
px = float(n2.x - n1.x)
py = float(n2.y - n1.y)
u = float((target.x - n1.x)*px + (target.y - n1.y)*py)/(px*px + py*py)
if u > 1:
u = 1
elif u < 0:
u = 0
x = n1.x + u*px
y = n1.y + u*py
dx = x - target.x
dy = y - target.y
sq_dist = (dx * dx + dy * dy)
return sq_dist
def intersect(e1, e2):
""" returns true if myedges e1 and e2 intersect """
# fails for lines that perfectly overlap.
def ccw(a, b, c):
return (c.y-a.y)*(b.x-a.x) > (b.y-a.y)*(c.x-a.x)
a = e1.nodes[0]
b = e1.nodes[1]
c = e2.nodes[0]
d = e2.nodes[1]
return ccw(a, c, d) != ccw(b, c, d) and ccw(a, b, c) != ccw(a, b, d)
def are_parallel(e1, e2):
""" returns true if myedges e1 and e2 are parallel """
a = e1.nodes[0]
b = e1.nodes[1]
c = e2.nodes[0]
d = e2.nodes[1]
# check if parallel; handling divide by zero errors
if a.x == b.x and c.x == d.x: # check if both segments are flat
parallel = True
# if one is flat and other is not
elif (a.x - b.x)*(c.x - d.x) == 0 and (a.x - b.x) + (c.x - d.x) != 0:
parallel = False
# if neither segment is flat and slopes are equal
elif (a.y-b.y)/(a.x-b.x) == (c.y-d.y)/(c.x-d.x):
parallel = True
# n either segment is flat, slopes are not equal
else:
parallel = False
return parallel
def segment_distance_sq(e1, e2):
"""returns the square of the minimum distance between myedges e1 and e2."""
# check different
if e1 == e2:
sq_distance = 0
# check parallel/colinear:
# lines are not parallel/colinear and intersect
if not are_parallel(e1, e2) and intersect(e1, e2):
sq_distance = 0
# lines don't intersect, aren't parallel
else:
d1 = sq_distance_point_to_segment(e1.nodes[0], e2)
d2 = sq_distance_point_to_segment(e1.nodes[1], e2)
d3 = sq_distance_point_to_segment(e2.nodes[0], e1)
d4 = sq_distance_point_to_segment(e2.nodes[1], e1)
sq_distance = min(d1, d2, d3, d4)
return sq_distance
# vector math
def bisect_angle(a, b, c, epsilon=0.2, radius=1):
""" finds point d such that bd bisects the lines ab and bc."""
ax = a.x - b.x
ay = a.y - b.y
cx = c.x - b.x
cy = c.y - b.y
a1 = mg.MyNode(((ax, ay))/np.linalg.norm((ax, ay)))
c1 = mg.MyNode(((cx, cy))/np.linalg.norm((cx, cy)))
# if vectors are close to parallel, find vector that is perpendicular to ab
# if they are not, then find the vector that bisects a and c
if abs(np.cross(a1.loc, c1.loc)) < 0 + epsilon:
# print("vectors {0}{1} and {1}{2} are close to //)".format(a,b,c)
dx = -ay
dy = ax
else:
dx = (a1.x + c1.x)/2
dy = (a1.y + c1.y)/2
# convert d values into a vector of length radius
dscale = ((dx, dy)/np.linalg.norm((dx, dy)))*radius
myd = mg.MyNode(dscale)
# make d a node in space, not vector around b
d = mg.MyNode((myd.x + b.x, myd.y + b.y))
return d
def find_negative(d, b):
"""finds the vector -d when b is origen """
negx = -1*(d.x - b.x) + b.x
negy = -1*(d.y - b.y) + b.y
dneg = mg.MyNode((negx, negy))
return dneg
# clean up and probability functions
def WeightedPick(d):
"""picks an item out of the dictionary d, with probability proportional to
the value of that item. e.g. in {a:1, b:0.6, c:0.4} selects and returns
"a" 5/10 times, "b" 3/10 times and "c" 2/10 times. """
r = random.uniform(0, sum(d.values()))
s = 0.0
for k, w in d.items():
s += w
if r < s:
return k
return k
def mat_reorder(matrix, order):
"""sorts a square matrix so both rows and columns are
ordered by order. """
Drow = [matrix[i] for i in order]
Dcol = [[r[i] for i in order] for r in Drow]
return Dcol
def myRoll(mylist):
"""rolls a list, putting the last element into the first slot. """
mylist.insert(0, mylist[-1])
del mylist[-1]
return(mylist)
######################
# DUALS HElPER
#######################
def form_equivalence_classes(myG, duals=None, verbose=False):
try:
for f in myG.inner_facelist:
f.even_nodes = {}
f.odd_node = {}
except:
pass
if not duals:
duals = myG.stacked_duals()
depth = 1
result = {}
myG.S1_nodes()
result[depth] = [f for f in myG.inner_facelist if f.odd_node[depth]]
if verbose:
# print("Graph S{} has {} parcels".format(depth, len(result[depth])))
pass
depth += 1
if verbose:
test_interior_is_inner(myG)
while depth < len(duals):
duals, depth, result = myG.formClass(duals, depth, result)
if verbose:
# md = max(result.keys())
# print("Graph S{} has {} parcels".format(md, len(result[md])))
# print("current depth {} just finished".format(depth))
# test_interior_is_inner(myG)
pass
return result, depth
######################
# DEALING WITH PATHS
#######################
def ptup_to_mypath(myG, ptup):
mypath = []
for i in range(1, len(ptup)):
pedge = myG.G[ptup[i-1]][ptup[i]]['myedge']
mypath.append(pedge)
return mypath
def path_length(path):
"""finds the geometric path length for a path that consists of a list of
MyNodes. """
length = 0
for i in range(1, len(path)):
length += distance(path[i-1], path[i])
return length
# def path_length_npy(path):
# xy = np.array([n.x,n.y for n in path])
# return np.linalg.norm(xy[1:] - xy[:-1],2,1).sum()
def shorten_path(ptup):
""" all the paths found in my pathfinding algorithm start at the fake
road side, and go towards the interior of the parcel. This method drops
nodes beginning at the fake road node, until the first and only the
first node is on a road. This gets rid of paths that travel along a
curb before ending."""
while ptup[1].road is True and len(ptup) > 2:
ptup.pop(0)
return ptup
def segment_near_path(myG, segment, pathlist, threshold):
"""returns True if the segment is within (geometric) distance threshold
of all the segments contained in path is stored as a list of nodes that
strung together make up a path.
"""
# assert isinstance(segment, mg.MyEdge)
# pathlist = ptup_to_mypath(path)
for p in pathlist:
sq_distance = segment_distance_sq(p, segment)
if sq_distance < threshold**2:
return True
return False
def _fake_edge(myA, centroid, mynode):
newedge = mg.MyEdge((centroid, mynode))
newedge.length = 0
myA.add_edge(newedge)
def __add_fake_edges(myA, p, roads_only=False):
if roads_only:
[_fake_edge(myA, p.centroid, n) for n in p.nodes if n.road]
else:
[_fake_edge(myA, p.centroid, n) for n in p.nodes]
def shortest_path_setup(myA, p, roads_only=False):
""" sets up graph to be ready to find the shortest path from a
parcel to the road. if roads_only is True, only put fake edges for the
interior parcel to nodes that are already connected to a road. """
fake_interior = p.centroid
__add_fake_edges(myA, p)
fake_road_origin = mg.MyNode((305620, 8022470))
for i in myA.road_nodes:
if len(myA.G.neighbors(i)) > 2:
_fake_edge(myA, fake_road_origin, i)
return fake_interior, fake_road_origin
def shortest_path_p2p(myA, p1, p2):
"""finds the shortest path along fencelines from a given interior parcel
p1 to another parcel p2"""
__add_fake_edges(myA, p1, roads_only=True)
__add_fake_edges(myA, p2, roads_only=True)
path = nx.shortest_path(myA.G, p1.centroid, p2.centroid, "weight")
length = nx.shortest_path_length(myA.G, p1.centroid, p2.centroid, "weight")
myA.G.remove_node(p1.centroid)
myA.G.remove_node(p2.centroid)
return path[1:-1], length
def find_short_paths(myA, parcel, barriers=True, shortest_only=False):
""" finds short paths from an interior parcel,
returns them and stores in parcel.paths """
rb = [n for n in parcel.nodes+parcel.edges if n.road]
if len(rb) > 0:
raise AssertionError("parcel %s is on a road") % (str(parcel))
if barriers:
barrier_edges = [e for e in myA.myedges() if e.barrier]
if len(barrier_edges) > 0:
myA.remove_myedges_from(barrier_edges)
else:
print("no barriers found. Did you expect them?")
# myA.plot_roads(title = "myA no barriers")
interior, road = shortest_path_setup(myA, parcel)
shortest_path = nx.shortest_path(myA.G, road, interior, "weight")
if shortest_only is False:
shortest_path_segments = len(shortest_path)
shortest_path_distance = path_length(shortest_path[1:-1])
all_simple = [shorten_path(p[1:-1]) for p in nx.all_simple_paths(myA.G,
road, interior, cutoff=shortest_path_segments + 2)]
paths = dict((tuple(p), path_length(p)) for p in all_simple
if path_length(p) < shortest_path_distance*2)
if shortest_only is True:
p = shorten_path(shortest_path[1:-1])
paths = {tuple(p): path_length(p)}
myA.G.remove_node(road)
myA.G.remove_node(interior)
if barriers:
for e in barrier_edges:
myA.add_edge(e)
parcel.paths = paths
return paths
def find_short_paths_all_parcels(myA, flist=None, full_path=None,
barriers=True, quiet=False,
shortest_only=False):
""" finds the short paths for all parcels, stored in parcel.paths
default assumes we are calculating from the outside in. If we submit an
flist, find the parcels only for those faces, and (for now) recaluclate
paths for all of those faces.
"""
all_paths = {}
counter = 0
if flist is None:
flist = myA.interior_parcels
for parcel in flist:
# if paths have already been defined for this parcel
# (full path should exist too)
if parcel.paths:
if full_path is None:
raise AssertionError("comparison path is None "
"but parcel has paths")
rb = [n for n in parcel.nodes+parcel.edges if n.road]
if len(rb) > 0:
raise AssertionError("parcel %s is on a road" % (parcel))
needs_update = False
for pathitem in parcel.paths.items():
path = pathitem[0]
mypath = ptup_to_mypath(myA, path)
path_length = pathitem[1]
for e in full_path:
if segment_near_path(myA, e, mypath, path_length):
needs_update = True
# this code would be faster if I could break to
# next parcel if update turned true.
break
if needs_update is True:
paths = find_short_paths(myA, parcel, barriers=barriers,
shortest_only=shortest_only)
counter += 1
all_paths.update(paths)
elif needs_update is False:
paths = parcel.paths
all_paths.update(paths)
# if paths have not been defined for this parcel
else:
paths = find_short_paths(myA, parcel, barriers=barriers,
shortest_only=shortest_only)
counter += 1
all_paths.update(paths)
if quiet is False:
pass
# print("Shortest paths found for {} parcels".format(counter))
return all_paths
def build_path(myG, start, finish):
ptup = nx.shortest_path(myG.G, start, finish, weight="weight")
ptup = shorten_path(ptup)
ptup.reverse()
ptup = shorten_path(ptup)
mypath = ptup_to_mypath(myG, ptup)
for e in mypath:
myG.add_road_segment(e)
return ptup, mypath
#############################################
# PATH SELECTION AND CONSTRUCTION
#############################################
def choose_path(myG, paths, alpha, strict_greedy=False):
""" chooses the path segment, choosing paths of shorter
length more frequently """
if strict_greedy is False:
inv_weight = dict((k, 1.0/(paths[k]**alpha)) for k in paths)
target_path = WeightedPick(inv_weight)
if strict_greedy is True:
target_path = min(paths, key=paths.get)
mypath = ptup_to_mypath(myG, target_path)
return target_path, mypath
# if outsidein:
# result, depth = form_equivalence_classes(myG)
# while len(flist) < 1:
# md = max(result.keys())
# flist = flist + result.pop(md)
# elif outsidein == False:
# flist = myG.interior_parcels
# ## alternate option:
# # result, depth = form_equivalence_classes(myG)
# # flist = result[3]
def build_all_roads(myG, master=None, alpha=8, plot_intermediate=False,
wholepath=True, original_roads=None, plot_original=False,
bisect=False, plot_result=False, barriers=False,
quiet=True, vquiet=True, strict_greedy=False,
outsidein=False):
"""builds roads using the probablistic greedy alg, until all
interior parcels are connected, and returns the total length of
road built. """
if vquiet is True:
quiet = True
if plot_original:
myG.plot_roads(original_roads, update=False,
parcel_labels=False, new_road_color="blue")
shortest_only = False
if strict_greedy is True:
shortest_only = True
added_road_length = 0
# plotnum = 0
if plot_intermediate is True and master is None:
master = myG.copy()
myG.define_interior_parcels()
target_mypath = None
if vquiet is False:
print("Begin w {} Int Parcels".format(len(myG.interior_parcels)))
# before the max depth (md) is calculated, just assume it's very large in
# in order ensure we find the equivalence classes at least once.
md = 100
while myG.interior_parcels:
result, depth = form_equivalence_classes(myG)
# flist from result!
flist = []
if md == 3:
flist = myG.interior_parcels
elif md > 3:
if outsidein is False:
result, depth = form_equivalence_classes(myG)
while len(flist) < 1:
md = max(result.keys())
flist = flist + result.pop(md)
elif outsidein is True:
result, depth = form_equivalence_classes(myG)
md = max(result.keys())
if len(result[md]) == 0:
md = md - 2
flist = list(set(result[3]) - set(result.get(5, [])))
if quiet is False:
pass
# potential segments from parcels in flist
all_paths = find_short_paths_all_parcels(myG, flist, target_mypath,
barriers, quiet=quiet,
shortest_only=shortest_only)
# choose and build one
target_ptup, target_mypath = choose_path(myG, all_paths, alpha,
strict_greedy=strict_greedy)
if wholepath is False:
added_road_length += target_mypath[0].length
myG.add_road_segment(target_mypath[0])
if wholepath is True:
for e in target_mypath:
added_road_length += e.length
myG.add_road_segment(e)
myG.define_interior_parcels()
if plot_intermediate:
myG.plot_roads(master, update=False)
# plt.savefig("Int_Step"+str(plotnum)+".pdf", format='pdf')
remain = len(myG.interior_parcels)
if quiet is False:
print("\n{} interior parcels left".format(remain))
if vquiet is False:
if remain > 300 or remain in [50, 100, 150, 200, 225, 250, 275]:
print ("{} interior parcels left".format(remain))
# update the properties of nodes & edges to reflect new geometry.
myG.added_roads = added_road_length
return added_road_length
def bisecting_road(myG):
# once done getting all interior parcels connected, have option to bisect
bisecting_roads = 0
start, finish = bisecting_path_endpoints(myG)
ptup, myedges = build_path(myG, start, finish)
bisecting_roads = path_length(ptup)
myG.added_roads = myG.added_roads + bisecting_roads
return bisecting_roads
############################
# connectivity optimization
############################
def __road_connections_through_culdesac(myG, threshold=5):
"""connects all nodes on a road that are within threshold = 5 meters of
each other. This means that paths can cross a culdesac instead of needing
to go around. """
etup_drop = []
nlist = [i for i in myG.G.nodes() if i.road is True]
for i, j in itertools.combinations(nlist, 2):
if j in myG.G and i in myG.G:
if distance(i, j) < threshold:
newE = mg.MyEdge((i, j))
newE.road = True
myG.add_edge(newE)
etup_drop.append((i, j))
return etup_drop
def shortest_path_p2p_matrix(myG, full=False, travelcost=False):
"""option if full is false, removes all interior edges, so that travel
occurs only along a road. If full is true, keeps interior edges. If
travel cost is true, increases weight of non-road edges by a factor of ten.
Base case is defaults of false and false."""
copy = myG.copy()
etup_drop = copy.find_interior_edges()
if full is False:
copy.G.remove_edges_from(etup_drop)
# print("dropping {} edges".format(len(etup_drop)))
__road_connections_through_culdesac(copy)
path_mat = []
path_len_mat = []
edges = copy.myedges()
if travelcost is True:
for e in edges:
if e.road is False:
copy.G[e.nodes[0]][e.nodes[1]]['weight'] = e.length*10
for p0 in copy.inner_facelist:
path_vec = []
path_len_vec = []
__add_fake_edges(copy, p0)
for p1 in copy.inner_facelist:
if p0.centroid == p1.centroid:
length = 0
path = p0.centroid
else:
__add_fake_edges(copy, p1)
try:
path = nx.shortest_path(copy.G, p0.centroid, p1.centroid,
"weight")
length = path_length(path[1:-1])
except:
path = []
length = np.nan
copy.G.remove_node(p1.centroid)
path_vec.append(path)
path_len_vec.append(length)
copy.G.remove_node(p0.centroid)
path_mat.append(path_vec)
path_len_mat.append(path_len_vec)
n = len(path_len_mat)
meantravel = (sum([sum(i) for i in path_len_mat])/(n*(n-1)))
return path_len_mat, meantravel
def difference_roads_to_fences(myG, travelcost=False):
fullpath_len, tc = shortest_path_p2p_matrix(myG, full=True)
path_len, tc = shortest_path_p2p_matrix(myG, full=False)
diff = [[path_len[j][i] - fullpath_len[j][i]
for i in range(0, len(fullpath_len[j]))]
for j in range(0, len(fullpath_len))]
dmax = max([max(i) for i in diff])
# print dmax
for j in range(0, len(path_len)):
for i in range(0, len(path_len[j])):
if np.isnan(path_len[j][i]):
diff[j][i] = dmax + 150
# diff[j][i] = np.nan
n = len(path_len)
meantravel = sum([sum(i) for i in path_len])/(n*(n-1))
return diff, fullpath_len, path_len, meantravel
def bisecting_path_endpoints(myG):
roads_only = myG.copy()
etup_drop = roads_only.find_interior_edges()
roads_only.G.remove_edges_from(etup_drop)
__road_connections_through_culdesac(roads_only)
# nodes_drop = [n for n in roads_only.G.nodes() if not n.road]
# roads_only.G.remove_nodes_from(nodes_drop)
distdict = {}
for i, j in itertools.combinations(myG.road_nodes, 2):
geodist_sq = distance_squared(i, j)
onroad_dist = nx.shortest_path_length(roads_only.G, i, j,
weight='weight')
dist_diff = onroad_dist**2/geodist_sq
distdict[(i, j)] = dist_diff
(i, j) = max(distdict.iteritems(), key=operator.itemgetter(1))[0]
return i, j
################
# GRAPH INSTANTIATION
###################
def graphFromMyEdges(elist, name=None):
myG = mg.MyGraph(name=name)
for e in elist:
myG.add_edge(e)
return myG
def graphFromMyFaces(flist, name=None):
myG = mg.MyGraph(name=name)
for f in flist:
for e in f.edges:
myG.add_edge(e)
return myG
def graphFromShapes(shapes, name, rezero=np.array([0, 0])):
nodedict = dict()
plist = []
for s in shapes:
nodes = []
for k in s.points:
k = k - rezero
myN = mg.MyNode(k)
if myN not in nodedict:
nodes.append(myN)
nodedict[myN] = myN
else:
nodes.append(nodedict[myN])
edges = [(nodes[i], nodes[i+1]) for i in range(0, len(nodes)-1)]
plist.append(mg.MyFace(edges))
myG = mg.MyGraph(name=name)
for p in plist:
for e in p.edges:
myG.add_edge(mg.MyEdge(e.nodes))
return myG
def is_roadnode(node, graph):
"""defines a node as a road node if any connected edges are road edges.
returns true or false and updates the properties of the node. """
graph.G[node].keys()
node.road = False
for k in graph.G[node].keys():
edge = graph.G[node][k]['myedge']
if edge.road is True:
node.road = True
return node.road
return node.road
def is_interiornode(node, graph):
"""defines a node as an interior node if any connected edges are interior
edges. returns true or false and updates the properties of the node. """
graph.G[node].keys()
node.interior = False
for k in graph.G[node].keys():
edge = graph.G[node][k]['myedge']
if edge.interior is True:
node.interior = True
return node.interior
return node.interior
def is_barriernode(node, graph):
"""defines a node as a road node if any connected edges are barrier edges.
returns true or false and updates the properties of the node. """
graph.G[node].keys()
node.barrier = False
for k in graph.G[node].keys():
edge = graph.G[node][k]['myedge']
if edge.barrier is True:
node.barrier = True
return node.barrier
return node.barrier
def graphFromJSON(jsonobj):
"""returns a new mygraph from a json object. calculates interior node
and graph properties from the properties of the edges.
"""
edgelist = []
# read all the edges from json
for feature in jsonobj['features']:
# check that there are exactly 2 nodes
numnodes = len(feature['geometry']['coordinates'])
if numnodes != 2:
raise AssertionError("JSON line feature has {} "
"coordinates instead of 2".format(numnodes))
c0 = feature['geometry']['coordinates'][0]
c1 = feature['geometry']['coordinates'][1]
isinterior = feature['properties']['interior']
isroad = feature['properties']['road']
isbarrier = feature['properties']['barrier']
n0 = mg.MyNode(c0)
n1 = mg.MyNode(c1)
edge = mg.MyEdge((n0, n1))
edge.road = json.loads(isroad)
edge.interior = json.loads(isinterior)
edge.barrier = json.loads(isbarrier)
edgelist.append(edge)
# create a new graph from the edge list, and calculate
# necessary graph properties from the road
new = graphFromMyEdges(edgelist)
new.road_edges = [e for e in new.myedges() if e.road]
new.road_nodes = [n for n in new.G.nodes() if is_roadnode(n, new)]
new.interior_nodes = [n for n in new.G.nodes() if is_interiornode(n, new)]
new.barrier_nodes = [n for n in new.G.nodes() if is_barriernode(n, new)]
# defines all the faces in the graph
new.inner_facelist
# defines all the faces with no road nodes in the graph as interior parcels
new.define_interior_parcels()
return new, edgelist
####################
# PLOTTING FUNCTIONS
####################
# ==============================================================================
# def plot_cluster_mat(clustering_data, plotting_data, title, dmax,
# plot_dendro=True):
# """from http://nbviewer.ipython.org/github/OxanaSachenkova/
# hclust-python/blob/master/hclust.ipynb First input matrix is used to
# define clustering order, second is the data that is plotted."""
#
# fig = plt.figure(figsize=(8, 8))
# # x ywidth height
#
# ax1 = fig.add_axes([0.05, 0.1, 0.2, 0.6])
# Y = linkage(clustering_data, method='single')
# Z1 = dendrogram(Y, orientation='right') # adding/removing the axes
# ax1.set_xticks([])
# # ax1.set_yticks([])
#
# # Compute and plot second dendrogram.
# ax2 = fig.add_axes([0.3, 0.75, 0.6, 0.1])
# Z2 = dendrogram(Y)
# # ax2.set_xticks([])
# ax2.set_yticks([])
#
# # set up custom color map
# c = mcolors.ColorConverter().to_rgb
# seq = [c('navy'), c('mediumblue'), .1, c('mediumblue'),
# c('darkcyan'), .2, c('darkcyan'), c('darkgreen'), .3,
# c('darkgreen'), c('lawngreen'), .4,c('lawngreen'),c('yellow'),.5,
# c('yellow'), c('orange'), .7, c('orange'), c('red')]
# custommap = make_colormap(seq)
#
# # Compute and plot the heatmap
# axmatrix = fig.add_axes([0.3, 0.1, 0.6, 0.6])
#
# if not plot_dendro:
# fig = plt.figure(figsize=(8, 8))
# axmatrix = fig.add_axes([0.05, 0.1, 0.85, 0.8])
#
# idx1 = Z1['leaves']
# D = mat_reorder(plotting_data, idx1)
# im = axmatrix.matshow(D, aspect='auto', origin='lower', cmap=custommap,
# vmin=0, vmax=dmax)
# axmatrix.set_xticks([])
# axmatrix.set_yticks([])
#
# # Plot colorbar.
# h = 0.6
# if not plot_dendro:
# h = 0.8
# axcolor = fig.add_axes([0.91, 0.1, 0.02, h])
# plt.colorbar(im, cax=axcolor)
# ax2.set_title(title)
# if not plot_dendro:
# axmatrix.set_title(title)
#
#
# def make_colormap(seq):
# """Return a LinearSegmentedColormap
# seq: a sequence of floats and RGB-tuples. The floats should be increasing
# and in the interval (0,1).
# """
# seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
# cdict = {'red': [], 'green': [], 'blue': []}
# for i, item in enumerate(seq):
# if isinstance(item, float):
# r1, g1, b1 = seq[i - 1]
# r2, g2, b2 = seq[i + 1]
# cdict['red'].append([item, r1, r2])
# cdict['green'].append([item, g1, g2])
# cdict['blue'].append([item, b1, b2])
# return mcolors.LinearSegmentedColormap('CustomMap', cdict)
# ==============================================================================
# ==============================================================================
# def plotly_traces(myG):
# """myGraph to plotly trace """
#
# # add the edges as disconnected lines in a trace
# edge_trace = Scatter(x=[], y=[], mode='lines',
# name='Parcel Boundaries',
# line=Line(color='grey', width=0.5))
# road_trace = Scatter(x=[], y=[], mode='lines',
# name='Road Boundaries',
# line=Line(color='black', width=2))
# interior_trace = Scatter(x=[], y=[], mode='lines',
# name='Interior Parcels',
# line=Line(color='red', width=2.5))
# barrier_trace = Scatter(x=[], y=[], mode='lines',
# name='Barriers',
# line=Line(color='green', width=0.75))
#
# for i in myG.connected_components():
# for edge in i.myedges():
# x0, y0 = edge.nodes[0].loc
# x1, y1 = edge.nodes[1].loc
# edge_trace['x'] += [x0, x1, None]
# edge_trace['y'] += [y0, y1, None]
# if edge.road:
# road_trace['x'] += [x0, x1, None]
# road_trace['y'] += [y0, y1, None]
# if edge.interior:
# interior_trace['x'] += [x0, x1, None]
# interior_trace['y'] += [y0, y1, None]
# if edge.barrier:
# barrier_trace['x'] += [x0, x1, None]
# barrier_trace['y'] += [y0, y1, None]
#
# return [edge_trace, road_trace, interior_trace, barrier_trace]
#
#
# def plotly_graph(traces, filename=None, title=None):
#
# """ use ply.iplot(fig,filename) after this function in ipython notebok to
# show the resulting plotly figure inline, or url=ply.plot(fig,filename) to
# just get url of resulting fig and not plot inline. """
#
# if filename is None:
# filename = "plotly_graph"
# fig = Figure(data=Data(traces),
# layout=Layout(title=title, plot_bgcolor="rgb(217,217,217)",
# showlegend=True,
# xaxis=XAxis(showgrid=False, zeroline=False,
# showticklabels=False),
# yaxis=YAxis(showgrid=False, zeroline=False,
# showticklabels=False)))
#
# # ply.iplot(fig, filename=filename)
# # py.iplot(fig, filename=filename)
#
# return fig, filename
#
# ==============================================================================
######################
# IMPORT & Running FUNCTIONS #
#####################
def import_and_setup(filename, threshold=1, component=None,