-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmycelium.py
1756 lines (1653 loc) · 73.1 KB
/
mycelium.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
"""Simulation library for reversible proximity ligation of DNA probes."""
from collections import defaultdict
from itertools import cycle
from random import sample
from multiprocessing import Pool, cpu_count
from string import letters, lowercase, digits
from time import time
import networkx
from networkx.drawing.nx_agraph import write_dot
import numpy as np
from scipy.spatial.distance import euclidean
from math import (sin,
cos,
ceil,
pi,
log10,
atan2,
)
from shapely import geometry
import matplotlib
import matplotlib.pyplot as plt
def epoch_to_hash(epoch,
resolution=100,
hashchars='alphanumeric',
):
"""
Generate an alphanumeric hash from a Unix epoch. Unix epoch is
rounded to the nearest second before hashing.
Arguments:
epoch: Unix epoch time. Must be positive.
Returns:
Alphanumeric hash of the Unix epoch time.
Cribbed & modified from Scott W Harden's website
http://www.swharden.com/blog/2014-04-19-epoch-timestamp-hashing/
"""
if epoch <= 0:
raise ValueError("epoch must be positive.")
epoch = round(epoch * resolution)
if hashchars == 'original':
hashchars = digits + lowercase
elif hashchars == 'binary':
hashchars = '01'
elif hashchars == 'alphanumeric':
hashchars = letters + digits
else:
raise ValueError("Invalid hashchars option.")
epoch_hash = ''
while epoch > 0:
epoch_hash = hashchars[int(epoch % len(hashchars))] + epoch_hash
epoch = int(epoch / len(hashchars))
return epoch_hash
def hash_to_epoch(epoch_hash,
resolution=100,
hashchars='alphanumeric',
):
"""
Invert hashing function _epoch_to_hash.
Arguments:
epoch_hash: Alphanumeric hash of Unix epoch time as returned by
_epoch_to_hash.
Returns:
epoch: Unix epoch time corresponding to epoch_hash.
Cribbed & modified from Scott W Harden's website
http://www.swharden.com/blog/2014-04-19-epoch-timestamp-hashing/
"""
if hashchars == 'original':
hashchars = digits + lowercase
elif hashchars == 'binary':
hashchars = '01'
elif hashchars == 'alphanumeric':
hashchars = letters + digits
else:
raise ValueError("Invalid hashchars option.")
#reverse character order
epoch_hash = epoch_hash[::-1]
epoch = 0
for i, c in enumerate(epoch_hash):
if c not in hashchars:
raise ValueError("epoch_hash contains unrecognized character(s).")
epoch += hashchars.find(c)*(len(hashchars)**i)
return float(epoch) / resolution
def generate_epoch_hash(silent=True):
epoch_hash = epoch_to_hash(time())
if not silent:
print("Generated hash: " + str(epoch_hash))
return epoch_hash
def square_poisson(size,
lam,
):
mean_num_points = lam * size**2
num_points = np.random.poisson(lam=mean_num_points)
x_coordinates = np.random.uniform(low=0.0,
high=size,
size=num_points,
)
y_coordinates = np.random.uniform(low=0.0,
high=size,
size=num_points,
)
coordinates = np.stack([x_coordinates, y_coordinates], axis=-1)
coordinates_list = coordinates.tolist()
polarities = np.random.choice([3, 5], size=num_points)
polarities_list = polarities.tolist()
probes_tuple = tuple([(x, y, polarity)
for (x, y), polarity in zip(coordinates_list, polarities_list)])
return probes_tuple
def shift_probes(probe_coordinates,
x_shift,
y_shift,
):
return tuple([(x + x_shift, y + y_shift, p) for (x, y, p) in probe_coordinates])
def poisson_squares(square_lattice,
size,
lam,
):
probe_coordinates = []
for x, y in square_lattice:
square = square_poisson(size=size,
lam=lam,
)
square = shift_probes(square, x * size, y * size)
probe_coordinates += list(square)
return tuple(probe_coordinates)
def letter_poisson(letter,
size,
lam,
):
if letter == 'L':
square_1 = square_poisson(size=size,
lam=lam,
)
square_2 = square_poisson(size=size,
lam=lam,
)
square_2 = shift_probes(square_2, size, 0)
square_3 = square_poisson(size=size,
lam=lam,
)
square_3 = shift_probes(square_3, 2 * size, 0)
square_4 = square_poisson(size=size,
lam=lam,
)
square_4 = shift_probes(square_3, 0, size)
probe_coordinates = sum([square_1, square_2, square_3, square_4], ())
elif letter == 'H':
square_1 = square_poisson(size=size,
lam=lam,
)
square_2 = square_poisson(size=size,
lam=lam,
)
square_2 = shift_probes(square_2, size, 0)
square_3 = square_poisson(size=size,
lam=lam,
)
square_3 = shift_probes(square_3, 2 * size, 0)
square_4 = square_poisson(size=size,
lam=lam,
)
square_4 = shift_probes(square_4, size, size)
square_5 = square_poisson(size=size,
lam=lam,
)
square_5 = shift_probes(square_5, 0, 2 * size)
square_6 = square_poisson(size=size,
lam=lam,
)
square_6 = shift_probes(square_6, size, 2 * size)
square_7 = square_poisson(size=size,
lam=lam,
)
square_7 = shift_probes(square_7, 2 * size, 2 * size)
probe_coordinates = sum([square_1,
square_2,
square_3,
square_4,
square_5,
square_6,
square_7,
], ())
elif letter == 'E':
letter_lattice = ((0, 0),
(1, 0),
(2, 0),
(3, 0),
(4, 0), #This and above are backbone
(0, 1),
(0, 2), #These two are bottom wing
(4, 1),
(4, 2), #These two are top wing
(2, 1), #This is middle wing
)
probe_coordinates = poisson_squares(square_lattice=letter_lattice,
size=size,
lam=lam,
)
elif letter == 'D':
letter_lattice = ((0, 0),
(1, 0),
(2, 0),
(3, 0),
(4, 0),
(0, 1),
(0, 2),
(4, 1),
(4, 2),
(1, 2),
(1, 3),
(3, 2),
(3, 3),
(2, 3),
)
probe_coordinates = poisson_squares(square_lattice=letter_lattice,
size=size,
lam=lam,
)
elif letter == 'W':
letter_lattice = ((2, 0),
(1, 0),
(0, 0),
(2, 1),
(3, 1),
(3, 2),
(3, 3),
(2, 3),
(1, 3),
(3, 4),
(3, 5),
(2, 5),
(2, 6),
(1, 6),
(0, 6),
)
probe_coordinates = poisson_squares(square_lattice=letter_lattice,
size=size,
lam=lam,
)
elif letter == 'R':
letter_lattice = ((0, 0),
(1, 0),
(2, 0),
(0, 1),
(0, 2),
(1, 2),
(2, 1),
(2, 2),
(3, 0),
(4, 0),
(3, 2),
(3, 3),
(4, 3),
)
probe_coordinates = poisson_squares(square_lattice=letter_lattice,
size=size,
lam=lam,
)
elif letter == 'O':
letter_lattice = ((0, 0),
(1, 0),
(2, 0),
(0, 1),
(0, 2),
(1, 2),
(2, 1),
(2, 2),
)
probe_coordinates = poisson_squares(square_lattice=letter_lattice,
size=size,
lam=lam,
)
else:
raise NotImplementedError("Letter not available.")
return probe_coordinates
def ligate_graph(probe_graph,
max_ligation_distance=1,
):
raise DeprecationWarning("Use rapid_ligate_graph.")
for (x1, y1, p1) in probe_graph:
for (x2, y2, p2) in probe_graph:
if p1 == p2:
continue
probe_distance = euclidean((x1, y1), (x2, y2))
if probe_distance <= max_ligation_distance:
probe_graph.add_edge((x1, y1, p1), (x2, y2, p2))
def add_line(array,
ix1, iy1, ix2, iy2,
color=[0, 0, 255],
):
if ix1 == ix2:
stepdir = 1 if iy1 < iy2 else -1
for y in range(iy1 + 1, iy2, stepdir):
array[ix1, y] = color
elif iy1 == iy2:
stepdir = 1 if ix1 < ix2 else -1
for x in range(ix1 + 1, ix2, stepdir):
array[x, iy1] = color
else:
slope = float(iy2 - iy1) / (ix2 - ix1)
stepdir = 1 if ix1 < ix2 else -1
for x in range(ix1 + 1, ix2, stepdir):
y = int(round(slope * (x - ix1) + iy1))
if not min(iy1, iy2) <= y <= max(iy1, iy2):
continue
array[x, y] = color
slope = float(ix2 - ix1) / (iy2 - iy1)
stepdir = 1 if iy1 < iy2 else -1
for y in range(iy1 + 1, iy2, stepdir):
x = int(round(slope * (y - iy1) + ix1))
if not min(ix1, ix2) <= x <= max(ix1, ix2):
continue
array[x, y] = color
def squares_tesselate(min_x, max_x,
min_y, max_y,
size,
):
if min_x > max_x:
raise ValueError("min_x = " + str(min_x) + " > max_x = " + str(max_x))
if min_y > max_y:
raise ValueError("min_y = " + str(min_y) + " > max_y = " + str(max_y))
if size <= 0:
raise ValueError("size = " + str(size) + " <= 0")
squares = []
#make offset squares
start_x, start_y = min_x - size / 2.0, min_y - size / 2.0
end_x, end_y = max_x + size / 2.0, max_y + size / 2.0
num_x = int(ceil(float(end_x - start_x) / size))
num_y = int(ceil(float(end_y - start_y) / size))
for i in range(num_x):
for j in range(num_y):
square_start_x = start_x + i * size
square_start_y = start_y + j * size
square_end_x = start_x + (i + 1) * size
square_end_y = start_y + (j + 1) * size
squares.append((square_start_x,
square_start_y,
square_end_x,
square_end_y,
))
#broadest square coverage
start_x, start_y = min_x - size, min_y - size
end_x, end_y = max_x + size, max_y + size
num_x = int(ceil(float(end_x - start_x) / size))
num_y = int(ceil(float(end_y - start_y) / size))
for i in range(num_x):
for j in range(num_y):
square_start_x = start_x + i * size
square_start_y = start_y + j * size
square_end_x = start_x + (i + 1) * size
square_end_y = start_y + (j + 1) * size
squares.append((square_start_x,
square_start_y,
square_end_x,
square_end_y,
))
return tuple(squares)
def rapid_ligate_graph(probe_graph,
max_ligation_distance=1,
remove_isolates=True,
):
graph_x_coords = [x for (x, y, p) in probe_graph]
graph_y_coords = [y for (x, y, p) in probe_graph]
min_x, max_x = min(graph_x_coords), max(graph_x_coords)
min_y, max_y = min(graph_y_coords), max(graph_y_coords)
squares = squares_tesselate(min_x, max_x,
min_y, max_y,
max_ligation_distance * 2,
)
per_square_nodes = defaultdict(list)
all_nodes_check_1, all_nodes_check_2 = set(), set()
for (x, y, p) in probe_graph:
all_nodes_check_1.add((x, y, p))
for square in squares:
sq_start_x, sq_start_y, sq_stop_x, sq_stop_y = square
if sq_start_x <= x <= sq_stop_x and sq_start_y <= y <= sq_stop_y:
per_square_nodes[square].append((x, y, p))
all_nodes_check_2.add((x, y, p))
assert all_nodes_check_1 == all_nodes_check_2
for square, nodes in per_square_nodes.iteritems():
for node1 in nodes:
x1, y1, p1 = node1
for node2 in nodes:
x2, y2, p2 = node2
if p1 == p2:
continue
#p1 == p2 implies this check:
#if node1 == node2:
# continue
probe_distance = euclidean((x1, y1), (x2, y2))
if probe_distance <= max_ligation_distance:
probe_graph.add_edge((x1, y1, p1), (x2, y2, p2))
if remove_isolates:
subgraphs = networkx.connected_component_subgraphs(probe_graph)
largest_subgraph = max(subgraphs,
key=networkx.number_of_nodes,
)
probe_graph = largest_subgraph
return probe_graph
def plot_probes(probe_graph,
five_prime_color=[255, 0, 0],
three_prime_color=[255, 255, 0],
connection_color=[0, 0, 255],
highlight_color=[255, 255, 0],
expansion=10,
figsize=15,
include_nodes=None,
highlight_edges=None,
):
if include_nodes is not None:
include_nodes = set(include_nodes)
if highlight_edges is not None:
highlight_edges = set(highlight_edges)
all_x_coordinates = [x for (x, y, polarity) in probe_graph]
min_x, max_x = min(all_x_coordinates), max(all_x_coordinates)
all_y_coordinates = [y for (x, y, polarity) in probe_graph]
min_y, max_y = min(all_y_coordinates), max(all_y_coordinates)
x_plot_shift = -min_x if min_x < 0 else 0
y_plot_shift = -min_y if min_y < 0 else 0
plot_size_x = int(ceil(expansion * (max_x - min_x + 2)))
plot_size_y = int(ceil(expansion * (max_y - min_y + 2)))
display_array = np.zeros((plot_size_x, plot_size_y, 3), dtype=np.uint8)
for (x1, y1, p1), (x2, y2, p2) in probe_graph.edges():
if include_nodes is not None and ((x1, y1, p1) not in include_nodes
or (x2, y2, p2) not in include_nodes):
continue
ix1 = int(round((x1 + x_plot_shift) * expansion))
iy1 = int(round((y1 + y_plot_shift) * expansion))
ix2 = int(round((x2 + x_plot_shift) * expansion))
iy2 = int(round((y2 + y_plot_shift) * expansion))
if highlight_edges is not None and (((x1, y1, p1), (x2, y2, p2)) in highlight_edges
or ((x2, y2, p2), (x1, y1, p1)) in highlight_edges
):
line_color = highlight_color
else:
line_color = connection_color
add_line(display_array,
ix1, iy1, ix2, iy2,
line_color,
)
for (x, y, p) in probe_graph.nodes():
if include_nodes is not None and (x, y, p) not in include_nodes:
continue
ix = int(round((x + x_plot_shift) * expansion))
iy = int(round((y + y_plot_shift) * expansion))
node_color = five_prime_color if p == 5 else three_prime_color
display_array[ix, iy] = node_color
fig = plt.figure(figsize=(figsize, figsize))
plt.imshow(display_array)
def polsby_popper(area, perimeter):
return 4.0 * pi * area / perimeter**2
def graph_polsby_popper(graph):
points = geometry.MultiPoint([(x, y) for (x, y, p) in graph.nodes()])
convex_hull = points.convex_hull
area = convex_hull.area
perimeter = convex_hull.length
pp = polsby_popper(area, perimeter)
return pp
def compare_positions(probe_graph,
central_node,
radius,
neato_map,
):
"""neato_map is {node = (x, y, p): (neato_x, neato_y)}"""
subgraph = networkx.ego_graph(G=probe_graph,
n=central_node,
radius=radius,
center=True,
)
central_x, central_y, central_p = central_node
probe_distances = {(x, y, p): euclidean((x, y), (central_x, central_y))
for (x, y, p) in subgraph.nodes()
if (x, y, p) != central_node}
#use nearest probe for theta
nearest_node = min(probe_distances, key=probe_distances.get)
if nearest_node == central_node:
raise RuntimeError("Nearest node is central node.")
elif probe_distances[nearest_node] == 0:
raise RuntimeError("Nearest node on top of central node.")
nearest_x, nearest_y, nearest_p = nearest_node
theta = atan2(nearest_y - central_y, nearest_x - central_x)
central_neato_x, central_neato_y = neato_map[central_node]
nearest_neato_x, nearest_neato_y = neato_map[nearest_node]
neato_theta = atan2(nearest_neato_y - central_neato_y,
nearest_neato_x - central_neato_x,
)
discrepancy_ledger = {}
for node in subgraph.nodes():
if node == central_node:
continue
neato_x, neato_y = neato_map[node]
neato_distance = euclidean((central_neato_x, central_neato_y), (neato_x, neato_y))
node_neato_theta = atan2(neato_y - central_neato_y, neato_x - central_neato_x)
node_neato_theta_diff = atan2(sin(node_neato_theta - neato_theta),
cos(node_neato_theta - neato_theta),
)
x, y, p = node
node_theta = atan2(y - central_y, x - central_x)
node_theta_diff = atan2(sin(node_theta - theta), cos(node_theta - theta))
node_distance = probe_distances[node]
assert node not in discrepancy_ledger
discrepancy_ledger[node] = (node_distance,
node_theta_diff,
neato_distance,
node_neato_theta_diff,
)
return discrepancy_ledger
def node_angle(central_node,
node_1,
node_2,
):
central_x, central_y = central_node[:2]
x1, y1 = node_1[:2]
x2, y2 = node_2[:2]
theta_1 = atan2(y1 - central_y, x1 - central_x)
theta_2 = atan2(y2 - central_y, x2 - central_x)
return atan2(sin(theta_1 - theta_2), cos(theta_1 - theta_2))
def ld_1(s, t):
if not s: return len(t)
if not t: return len(s)
if s[0] == t[0]: return ld(s[1:], t[1:])
l1 = ld(s, t[1:])
l2 = ld(s[1:], t)
l3 = ld(s[1:], t[1:])
return 1 + min(l1, l2, l3)
def ld_2(s1, s2):
if len(s1) < len(s2):
return levenshtein(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and
#current_row are one character longer
deletions = current_row[j] + 1 # than s2
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
def ld_3(s, t):
''' From Wikipedia article; Iterative with two matrix rows. '''
if s == t: return 0
elif len(s) == 0: return len(t)
elif len(t) == 0: return len(s)
v0 = [None] * (len(t) + 1)
v1 = [None] * (len(t) + 1)
for i in range(len(v0)):
v0[i] = i
for i in range(len(s)):
v1[0] = i + 1
for j in range(len(t)):
cost = 0 if s[i] == t[j] else 1
v1[j + 1] = min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost)
for j in range(len(v0)):
v0[j] = v1[j]
return v1[len(t)]
def levenshtein_comparison(probe_graph,
central_node,
radius,
neato_map,
ld_algorithm=3,
normalize=False,
bidirectional=False,
):
subgraph = networkx.ego_graph(G=probe_graph,
n=central_node,
radius=radius,
center=False,
)
central_x, central_y, central_p = central_node
probe_distances = {(x, y, p): euclidean((x, y), (central_x, central_y))
for (x, y, p) in subgraph.nodes()
if (x, y, p) != central_node}
#use nearest probe for baseline
nearest_node = min(probe_distances, key=probe_distances.get)
if nearest_node == central_node:
raise RuntimeError("Nearest node is central node.")
elif probe_distances[nearest_node] == 0:
raise RuntimeError("Nearest node on top of central node.")
node_angles = []
neato_angles = []
for node in subgraph:
angle = node_angle(central_node=central_node,
node_1=nearest_node,
node_2=node,
)
node_angles.append(angle)
neato_angle = node_angle(central_node=neato_map[central_node],
node_1=neato_map[nearest_node],
node_2=neato_map[node]
)
neato_angles.append(neato_angle)
sorted_node_angles = sorted(enumerate(node_angles), key=lambda x:x[1])
sorted_node_indexes = [i for i, a in sorted_node_angles]
sorted_neato_angles = sorted(enumerate(neato_angles), key=lambda x:x[1])
sorted_neato_indexes = [i for i, a in sorted_neato_angles]
assert len(sorted_node_indexes) == len(sorted_neato_indexes)
if ld_algorithm == 1:
ld = ld_1
elif ld_algorithm == 2:
ld = ld_2
elif ld_algorithm == 3:
ld = ld_3
else:
raise ValueError("Invalid ld_algorithm.")
distance = ld(sorted_node_indexes, sorted_neato_indexes)
if bidirectional:
sorted_neato_indexes.reverse()
r_distance = ld(sorted_node_indexes, sorted_neato_indexes)
distance = min(distance, r_distance)
if normalize:
distance /= float(len(sorted_node_indexes))
return distance
def kendalltau_comparison(probe_graph,
central_node,
radius,
neato_map,
absolute=False,
):
subgraph = networkx.ego_graph(G=probe_graph,
n=central_node,
radius=radius,
center=False,
)
central_x, central_y, central_p = central_node
probe_distances = {(x, y, p): euclidean((x, y), (central_x, central_y))
for (x, y, p) in subgraph.nodes()
if (x, y, p) != central_node}
#use nearest probe for baseline
nearest_node = min(probe_distances, key=probe_distances.get)
if nearest_node == central_node:
raise RuntimeError("Nearest node is central node.")
elif probe_distances[nearest_node] == 0:
raise RuntimeError("Nearest node on top of central node.")
node_angles = []
neato_angles = []
for node in subgraph:
angle = node_angle(central_node=central_node,
node_1=nearest_node,
node_2=node,
)
node_angles.append(angle)
neato_angle = node_angle(central_node=neato_map[central_node],
node_1=neato_map[nearest_node],
node_2=neato_map[node]
)
neato_angles.append(neato_angle)
distance = kendalltau(node_angles, neato_angles).correlation
if absolute:
distance = abs(distance)
return distance
def rgb_to_hex(R, G, B,
multiplier=255,
):
R = int(round(R * multiplier))
G = int(round(G * multiplier))
B = int(round(B * multiplier))
return '#%02x%02x%02x' % (R, G, B)
def displacement_distances(probe_graph,
central_node,
radius,
neato_map,
):
subgraph = networkx.ego_graph(G=probe_graph,
n=central_node,
radius=radius,
center=True,
)
central_x, central_y, central_p = central_node
probe_distances = {(x, y, p): euclidean((x, y), (central_x, central_y))
for (x, y, p) in subgraph.nodes()
if (x, y, p) != central_node}
#use nearest probe for theta
nearest_node = min(probe_distances, key=probe_distances.get)
if nearest_node == central_node:
raise RuntimeError("Nearest node is central node.")
elif probe_distances[nearest_node] == 0:
raise RuntimeError("Nearest node on top of central node.")
nearest_x, nearest_y, nearest_p = nearest_node
theta = atan2(nearest_y - central_y, nearest_x - central_x)
central_neato_x, central_neato_y = neato_map[central_node]
nearest_neato_x, nearest_neato_y = neato_map[nearest_node]
neato_theta = atan2(nearest_neato_y - central_neato_y,
nearest_neato_x - central_neato_x,
)
reset_rotation = theta - neato_theta
r_sin, r_cos = sin(reset_rotation), cos(reset_rotation)
displacement_ledger = {}
for node in subgraph:
if node == central_node:
displacement_ledger[node] = 0
continue
x, y, p = node
x, y = x - central_x, y - central_y
neato_x, neato_y = neato_map[node]
neato_x, neato_y = neato_x - central_neato_x, neato_y - central_neato_y
r_neato_x = neato_x * r_cos - neato_y * r_sin
r_neato_y = neato_x * r_sin + neato_y * r_cos
displacement = euclidean((x, y), (r_neato_x, r_neato_y))
assert node not in displacement_ledger
displacement_ledger[node] = displacement
return displacement_ledger
def pairwise_node_distortion(probe_graph,
central_node,
radius,
neato_map,
):
subgraph = networkx.ego_graph(G=probe_graph,
n=central_node,
radius=radius,
center=True,
)
pairwise_ledger = {}
for node_1, node_2 in MCsimlib._pairwise(subgraph.nodes()):
x1, y1, p1 = node_1
x2, y2, p2 = node_2
edge_length = euclidean((x1, y1), (x2, y2))
neato_x1, neato_y1 = neato_map[node_1]
neato_x2, neato_y2 = neato_map[node_2]
neato_edge_length = euclidean((neato_x1, neato_y1), (neato_x2, neato_y2))
assert (node_1, node_2) not in pairwise_ledger
pairwise_ledger[(node_1, node_2)] = (edge_length, neato_edge_length)
return pairwise_ledger
def compare_edge_lengths(probe_graph,
central_node,
radius,
neato_map,
):
subgraph = networkx.ego_graph(G=probe_graph,
n=central_node,
radius=radius,
center=True,
)
length_ledger = {}
for (node_1, node_2) in subgraph.edges():
x1, y1, p1 = node_1
x2, y2, p2 = node_2
edge_length = euclidean((x1, y1), (x2, y2))
neato_x1, neato_y1 = neato_map[node_1]
neato_x2, neato_y2 = neato_map[node_2]
neato_edge_length = euclidean((neato_x1, neato_y1), (neato_x2, neato_y2))
assert (node_1, node_2) not in length_ledger
length_ledger[(node_1, node_2)] = (edge_length, neato_edge_length)
return length_ledger
def pp_ratio(probe_graph,
central_node,
radius,
neato_map,
):
subgraph = networkx.ego_graph(G=probe_graph,
n=central_node,
radius=radius,
center=True,
)
original_pp = graph_polsby_popper(subgraph)
subgraph_neato = [neato_map[node] for node in subgraph]
subgraph_neato_hull = geometry.MultiPoint(subgraph_neato).convex_hull
neato_area, neato_perimeter = subgraph_neato_hull.area, subgraph_neato_hull.length
neato_pp = polsby_popper(neato_area, neato_perimeter)
return float(neato_pp) / float(original_pp)
def area_scaling(probe_graph,
central_node,
radius,
neato_map,
):
subgraph = networkx.ego_graph(G=probe_graph,
n=central_node,
radius=radius,
center=True,
)
subgraph_hull = geometry.MultiPoint([(x, y) for (x, y, p) in subgraph]).convex_hull
subgraph_neato = [neato_map[node] for node in subgraph]
subgraph_neato_hull = geometry.MultiPoint(subgraph_neato).convex_hull
original_area = subgraph_hull.area
neato_area = subgraph_neato_hull.area
return float(original_area) / neato_area
def write_heatmap_dot(input_dot_filename,
output_dot_filename,
node_values,
minimum_value=None,
maximum_value=None,
heatmap='viridis',
per_node_signifier="height",
nan_color=(1, 1, 1),
blank_nodes=None,
blank_color=(1, 1, 1),
):
if minimum_value is None:
minimum_value = min(node_values.values())
if maximum_value is None:
maximum_value = max(node_values.values())
output_line_cache = []
with open(input_dot_filename) as input_dotfile:
for line in input_dotfile:
if per_node_signifier not in line:
output_line_cache.append(line)
continue
x_str, y_str, p_str, height_str = line.split(' ')
x = float(x_str[3:-1])
y = float(y_str[:-1])
p = int(p_str[:-3])
node = x, y, p
node_value = node_values[node]
node_value = max(min(node_value, maximum_value), minimum_value)
heatmap_position = (float(node_value - minimum_value)
/ (maximum_value - minimum_value)
)
if np.isnan(heatmap_position):
R, G, B = nan_color
elif heatmap == 'viridis':
R, G, B, alpha = matplotlib.cm.viridis(heatmap_position)
else:
ValueError("Invalid heatmap.")
if blank_nodes is not None and node in blank_nodes:
R, G, B = blank_color
colorhex = rgb_to_hex(R, G, B)
fillcolor_str = ('\t\t'
+ "fillcolor=\""
+ str(colorhex)
+ "\"" + ","
+ '\n'
)
filled_str = "\t\tstyle=filled,\n"
output_line_cache.append(line)
output_line_cache.append(filled_str)
output_line_cache.append(fillcolor_str)
with open(output_dot_filename, 'w') as output_dotfile:
output_dotfile.writelines(output_line_cache)
def neato_node_densities(neato_map,
radius,
):
"""radius is Euclidean in neato space."""
pairwise_distances = {}
for (node_1, (x1, y1)), (node_2, (x2, y2)) in combinations(neato_map.iteritems(), 2):
if abs(x1 - x2) > radius or abs(y1 - y2) > radius:
continue
node_pair = frozenset((node_1, node_2))
distance = euclidean((x1, y1), (x2, y2))
pairwise_distances[node_pair] = distance
#account for each node itself within its local density
densities = defaultdict(lambda:1)
for node_pair, distance in pairwise_distances.iteritems():
node_1, node_2 = tuple(node_pair)
if distance <= radius:
densities[node_1] += 1
densities[node_2] += 1
return densities
def ligate_additional_nodes(probe_graph,
sprinkled_nodes,
max_ligation_distance,
remove_isolates=True,
self_long=False,
):
augmented_probe_graph = probe_graph.copy()
for node in augmented_probe_graph.nodes():
x, y, p = node
for sprinkled_node in sprinkled_nodes:
sx, sy, sp = sprinkled_node
if p == sp:
continue
if abs(sx - x) > max_ligation_distance or abs(sy - y) > max_ligation_distance:
continue
probe_distance = euclidean((x, y), (sx, sy))
if probe_distance <= max_ligation_distance:
augmented_probe_graph.add_edge(node, sprinkled_node, len=max_ligation_distance)
if self_long:
self_long_distance = 2 * (max_ligation_distance - 1)
for (node_1, node_2) in combinations(augmented_probe_graph.nodes(), 2):
x1, y1, p1 = node_1
x2, y2, p2 = node_2
if p1 == p2:
continue
if abs(x1 - x2) > self_long_distance or abs(y1 - y2) > self_long_distance:
continue
probe_distance = euclidean((x1, y1), (x2, y2))
if probe_distance <= self_long_distance:
augmented_probe_graph.add_edge(node_1, node_2, len=self_long_distance)
if remove_isolates:
subgraphs = networkx.connected_component_subgraphs(augmented_probe_graph)
largest_subgraph = max(subgraphs,
key=networkx.number_of_nodes,
)
augmented_probe_graph = largest_subgraph
return augmented_probe_graph
def make_heatmap_colorbar(node_values,
minimum_value=None,
maximum_value=None,
silent=False,
):
min_value, max_value = min(node_values.values()), max(node_values.values())
if minimum_value is not None:
min_value = minimum_value
if maximum_value is not None:
max_value = maximum_value
mean_value = np.mean(node_values.values())
median_value = np.median(node_values.values())
data = np.zeros((2, 2))
data[0, 0] = min_value
data[1, 1] = max_value
data[0, 1] = mean_value
data[1, 0] = median_value
if not silent:
print("make_heatmap_colorbar: "
+ "(min_value, mean_value, median_value, max_value) = "
+ str((min_value, mean_value, median_value, max_value))
)
heatmap = plt.pcolor(data)
plt.colorbar(heatmap)
plt.show()
def neighbor_angle_sequence(probe_graph,
central_node,
radius,
neato_coordinates,
):
subgraph = networkx.ego_graph(G=probe_graph,
n=central_node,
radius=radius,
center=False,
)
n_central_x, n_central_y = neato_coordinates[central_node]
neato_distances = {node: euclidean((n_central_x, n_central_y), neato_coordinates[node])
for node in subgraph.nodes()}
#use nearest probe for baseline
nearest_node = min(neato_distances, key=neato_distances.get)
if nearest_node == central_node:
raise RuntimeError("Nearest node is central node.")
elif neato_distances[nearest_node] == 0:
raise RuntimeError("Nearest node on top of central node.")
neato_angles = {}
for node in subgraph:
neato_angle = node_angle(central_node=neato_coordinates[central_node],
node_1=neato_coordinates[nearest_node],
node_2=neato_coordinates[node]
)
neato_angles[node] = neato_angle
return neato_angles
def read_probe_graph_plain(neato_plain_filename):
neato_coordinates, graph_scale, graph_width, graph_height = {}, 0, 0, 0
with open(neato_plain_filename) as neato_plain_file:
for L, line in enumerate(neato_plain_file, start=1):
split_line = line.split(' ')
line_type = split_line[0]
if line_type == 'graph':
type_string, graph_scale_str, graph_width_str, graph_height_str = split_line
graph_scale = float(graph_scale_str)
graph_width = float(graph_width_str)
graph_height = float(graph_height_str)
elif line_type == 'node':