/
nx_animation.py
633 lines (530 loc) · 18 KB
/
nx_animation.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
import matplotlib.pyplot as plt
import copy
import sys
import numpy as np
def _get_node_collection_object(G):
fig = plt.gcf()
axes = plt.gca()
no_of_nodes = G.number_of_nodes()
nodes_collection = axes.get_children()[no_of_nodes + 2]
return fig, axes, no_of_nodes, nodes_collection
def _get_values_from_kwargs(dic, string):
try:
node = dic['node']
except KeyError:
node = None
try:
value = dic['string']
except KeyError:
print(string + "argument required")
sys.exit(0)
return node, value
def set_node_position(G, **kwargs):
"""
Moves node to position along with its edges.
Parameters
----------
G : Graph whose nodes are to be moved
kwargs
------
node : The node to move if not specified moves all the nodes to the
corresponding position in position
position : The new position of the node. If node specified should be in
form (x,y) or [x,y]. If node not specified should be in form
[(x1,y1), (x2,y2), (x3,y3)]. It must have new position for
each node in the graph.
Example
-------
set_node_position(G, node=1, position=[0.5, 0.5])
set_node_position(G, node=1, position=(0.5, 0.5))
#Considering graph G has 3 nodes
set_node_position(G, position=[(0.1,0.1), (0.2, 0.2), (0.3, 0.3)]
"""
try:
node = kwargs['node']
except KeyError:
node = None
try:
position = kwargs['position']
except KeyError:
print("postion argument required")
sys.exit(0)
if node:
_set_single_node_position(G, node=node, position=position)
else:
for node_no in range(G.number_of_nodes()):
_set_single_node_position(G, node=G.nodes()[node_no],
position=position[node_no])
def _set_single_node_position(G, **kwargs):
"""
Moves a single node specified in node to the specified position.
"""
try:
node = kwargs['node']
except KeyError:
node = None
try:
position = kwargs['position']
except KeyError:
print("position argument required")
sys.exit(0)
fig = plt.gcf()
axes = plt.gca()
node_index = G.nodes().index(node)
no_of_nodes = G.number_of_nodes()
def compare(li1, li2):
for i, j in zip(li1, li2):
if i != j:
return False
return True
if node:
# move node
x, y = position
nodes_collection = axes.get_children()[no_of_nodes + 2]
prev_positions = nodes_collection.get_offsets()
prev_position = copy.deepcopy(prev_positions[node_index])
prev_positions[node_index] = [x, y]
# move edge
edges_collection = axes.get_children()[no_of_nodes + 3]
for edge in edges_collection.get_paths():
if compare(edge.vertices[0], prev_position):
edge.vertices[0] = position
elif compare(edge.vertices[1], prev_position):
edge.vertices[1] = position
# move label
label = axes.get_children()[node_index + 2]
label.set_position([x, y])
plt.draw()
def set_node_facecolor(G, **kwargs):
"""
Changes node's facecolor
Parameters
----------
G : Graph whose node's facecolor needs to be changed
kwargs
------
node : The node whose facecolor needs to be changed. If node not specified
and only one color is specified changes all the nodes to that
facecolor. If node not specified and color is a list or tuple of
colors, each node will be changed to its corresponding color.
color : Can be a single value of a list of colors.
The following color abbreviations are supported:
========== ========
character color
========== ========
'b' blue
'g' green
'r' red
'c' cyan
'm' magenta
'y' yellow
'k' black
'w' white
========== ========
Examples:
set_node_facecolor(G, node=1, color='b')
set_node_facecolor(G, node=1, color=['b'])
set_node_facecolor(G, color=['r', 'b', 'g', 'y', 'm', 'k', 'c'])
set_node_facecolor(G, color='b')
set_node_facecolor(G, color=('b'))
"""
try:
node = kwargs['node']
except KeyError:
node = None
try:
color = kwargs['color']
except KeyError:
print("color argument required")
sys.exit(0)
if (isinstance(color, list) or isinstance(color, tuple)) and \
len(color) == 1:
color = color[0]
same_colors = {'blue': 'b',
'green': 'g',
'red': 'r',
'cyan': 'c',
'magenta': 'm',
'yellow': 'y',
'black': 'k',
'white': 'w'}
if isinstance(color, str) and len(color) != 1:
color = same_colors[color]
colors_dict = {'b': (0., 0., 1., 1.),
'g': (0., 0.5, 0., 1.),
'r': (1., 0., 0., 1.),
'c': (0., 0.75, 0.75, 1.),
'm': (0.75, 0., 0.75, 1.),
'y': (0.75, 0.75, 0., 1.),
'k': (0., 0., 0., 1.),
'w': (1., 1., 1., 1.)}
fig = plt.gcf()
axes = plt.gca()
no_of_nodes = G.number_of_nodes()
nodes_collection = axes.get_children()[no_of_nodes + 2]
# if node is specified manually changing the facecolor array
# so that the colors for other nodes are retained
if node:
node_index = G.nodes().index(node)
facecolor_array = nodes_collection.get_facecolor().tolist()
facecolor_array = [tuple(x) for x in facecolor_array]
if len(facecolor_array) == 1:
facecolor_array = [copy.deepcopy(facecolor_array[0])
for i in range(no_of_nodes)]
facecolor_array[node_index] = colors_dict[color]
nodes_collection.set_facecolor(facecolor_array)
# if node not specified call the matplotlib's set_facecolor function
else:
nodes_collection.set_facecolor(color)
plt.draw()
def set_node_edgecolor(G, **kwargs):
"""
Changes node edgecolors
Parameters
----------
G : Graph whose node's edgecolor needs to be changed
kwargs
------
node : The node whose edgecolor needs to be changed. If node not specified
and only one color is specified changes all the nodes to that
color. If node not specified and color is a list or tuple of
colors, each node will be changed to its corresponding color.
color : Can be a single value of a list of colors.
The following color abbreviations are supported:
========== ========
character color
========== ========
'b' blue
'g' green
'r' red
'c' cyan
'm' magenta
'y' yellow
'k' black
'w' white
========== ========
Examples:
set_node_edgecolor(G, node=1, color='b')
set_node_edgecolor(G, node=1, color=['b'])
set_node_edgecolor(G, color=['r', 'b', 'g', 'y', 'm', 'k', 'c'])
set_node_edgecolor(G, color='b')
set_node_edgecolor(G, color=('b'))
"""
try:
node = kwargs['node']
except KeyError:
node = None
try:
color = kwargs['color']
except KeyError:
print("color argument required")
sys.exit(0)
if (isinstance(color, list) or isinstance(color, tuple)) and \
len(color) == 1:
color = color[0]
same_colors = {'blue': 'b',
'green': 'g',
'red': 'r',
'cyan': 'c',
'magenta': 'm',
'yellow': 'y',
'black': 'k',
'white': 'w'}
if isinstance(color, str) and len(color) != 1:
color = same_colors[color]
colors_dict = {'b': (0., 0., 1., 1.),
'g': (0., 0.5, 0., 1.),
'r': (1., 0., 0., 1.),
'c': (0., 0.75, 0.75, 1.),
'm': (0.75, 0., 0.75, 1.),
'y': (0.75, 0.75, 0., 1.),
'k': (0., 0., 0., 1.),
'w': (1., 1., 1., 1.)}
fig = plt.gcf()
axes = plt.gca()
no_of_nodes = G.number_of_nodes()
nodes_collection = axes.get_children()[no_of_nodes + 2]
# if node is specified manually changing the edgecolor array
# so that the colors for other nodes are retained
if node:
node_index = G.nodes().index(node)
edgecolor_array = nodes_collection.get_edgecolor().tolist()
edgecolor_array = [tuple(x) for x in edgecolor_array]
if len(edgecolor_array) == 1:
edgecolor_array = [copy.deepcopy(edgecolor_array[0])
for i in range(no_of_nodes)]
edgecolor_array[node_index] = colors_dict[color]
nodes_collection.set_edgecolor(edgecolor_array)
# if node not specified call the matplotlib's set_edgecolor function
else:
nodes_collection.set_edgecolor(color)
plt.draw()
def set_node_color(G, **kwargs):
"""
Changes node colors
Parameters
----------
G : Graph whose node's color needs to be changed
kwargs
------
node : The node whose color needs to be changed. If node not specified
and only one color is specified changes all the nodes to that
color. If node not specified and color is a list or tuple of
colors, each node will be changed to its corresponding color.
color : Can be a single value of a list of colors.
The following color abbreviations are supported:
========== ========
character color
========== ========
'b' blue
'g' green
'r' red
'c' cyan
'm' magenta
'y' yellow
'k' black
'w' white
========== ========
Examples:
set_node_color(G, node=1, color='b')
set_node_color(G, node=1, color=['b'])
set_node_color(G, color=['r', 'b', 'g', 'y', 'm', 'k', 'c'])
set_node_color(G, color='b')
set_node_color(G, color=('b'))
"""
try:
node = kwargs['node']
except KeyError:
node = None
try:
color = kwargs['color']
except KeyError:
print("color argument required")
sys.exit(0)
if (isinstance(color, list) or isinstance(color, tuple)) and \
len(color) == 1:
color = color[0]
same_colors = {'blue': 'b',
'green': 'g',
'red': 'r',
'cyan': 'c',
'magenta': 'm',
'yellow': 'y',
'black': 'k',
'white': 'w'}
if isinstance(color, str) and len(color) != 1:
color = same_colors[color]
fig = plt.gcf()
axes = plt.gca()
no_of_nodes = G.number_of_nodes()
nodes_collection = axes.get_children()[no_of_nodes + 2]
if node:
set_node_facecolor(G, **kwargs)
set_node_edgecolor(G, **kwargs)
else:
nodes_collection.set_color(color)
plt.draw()
def set_node_size(G, **kwargs):
"""
Change node size
Parameters
----------
G : The graph whose nodes are to be resized
kwargs
------
node : The node whose size is to be changed. If node not specified size
of all the nodes will be changed.
size : If size is an int and node specified, that node's size would be
changed. If size is a list of tuple and no node specified each
node will be changed to it's corresponding size. If node not
specified and size is int all the nodes will be changed to that
value.
Examples
--------
set_node_size(G, node=1, size=10)
set_node_size(G, size=5)
set_node_size(G, size=[1,2,3,4,5,6,7])
"""
try:
node = kwargs['node']
except KeyError:
node = None
try:
size = kwargs['size']
except KeyError:
print("size argument required")
sys.exit(0)
fig = plt.gcf()
axes = plt.gca()
no_of_nodes = G.number_of_nodes()
nodes_collection = axes.get_children()[no_of_nodes + 2]
if node:
node_index = G.nodes().index(node)
line_width_arr = nodes_collection.get_linewidth()
if len(line_width_arr) == 1:
element = line_width_arr[0]
line_width_arr = [copy.deepcopy(element)
for i in range(no_of_nodes)]
line_width_arr[node_index] = size
nodes_collection.set_linewidth(line_width_arr)
else:
nodes_collection.set_linewidth(size)
plt.draw()
def set_node_style(G, **kwargs):
try:
node = kwargs['node']
except KeyError:
node = None
try:
style = kwargs['position']
except KeyError:
print("style argument required")
sys.exit(0)
fig = plt.gcf()
axes = plt.gca()
no_of_nodes = G.number_of_nodes()
nodes_collection = axes.get_children()[no_of_nodes + 2]
linestyle_dict = {'solid': (None, None),
'dotted': (0, (1.0, 3.0)),
'dashdot': (0, (3.0, 5.0, 1.0, 5.0))}
# TODO: Still incomplete Check what does the tuple values do
def set_node_alpha(G, alpha):
fig = plt.gcf()
axes = plt.gca()
no_of_nodes = G.number_of_nodes()
nodes_collection = axes.get_children()[no_of_nodes + 2]
nodes_collection.set_alpha(alpha)
plt.draw()
# TODO set_edge_style
def set_edge_color(G, **kwargs):
"""
Change the color of the edges
Parameters
----------
G : The graph whose edges color are to be changed.
kwargs
------
edge : The edge whose color is to be changed. If edge
not specified and a single color value is given
all the edges are changed to the specified color.
If edge not given and color list is given the
color of the corresponding edge is changed. The
order of the edges can be seen from G.edges()
color: Color value. Either a list of a single value
Examples
--------
set_edge_color(G, edge=(1,2), color='g')
set_edge_color(G, color='b')
"""
try:
edge = kwargs['edge']
except KeyError:
edge = None
try:
color = kwargs['color']
except KeyError:
print("color argument required")
sys.exit(0)
if (isinstance(color, list) or isinstance(color, tuple)) and \
len(color) == 1:
color = color[0]
same_colors = {'blue': 'b',
'green': 'g',
'red': 'r',
'cyan': 'c',
'magenta': 'm',
'yellow': 'y',
'black': 'k',
'white': 'w'}
if isinstance(color, str) and len(color) != 1:
color = same_colors[color]
colors_dict = {'b': (0., 0., 1., 1.),
'g': (0., 0.5, 0., 1.),
'r': (1., 0., 0., 1.),
'c': (0., 0.75, 0.75, 1.),
'm': (0.75, 0., 0.75, 1.),
'y': (0.75, 0.75, 0., 1.),
'k': (0., 0., 0., 1.),
'w': (1., 1., 1., 1.)}
fig = plt.gcf()
axes = plt.gca()
no_of_nodes = G.number_of_nodes()
no_of_edges = G.number_of_edges()
edges_collection = axes.get_children()[no_of_nodes + 3]
edges = G.edges()
if edge:
edge_index = edges.indexof(edge)
edgecolor_array = edges_collection.get_color().tolist()
edgecolor_array = [tuple(x) for x in edgecolor_array]
if len(edgecolor_array) == 1:
edgecolor_array = [copy.deepcopy(edgecolor_array[0])
for i in range(no_of_edges)]
edgecolor_array[edge_index] = colors_dict[color]
edges_collection.set_facecolor(edgecolor_array)
else:
edges_collection.set_color(color)
plt.draw()
def set_edge_linewidth(G, **kwargs):
"""
Change the linewidth of the edges.
parameters
----------
G : The graph whose edge widths are to be changed.
kwargs
------
edge : The edge whose width is to be changed. If edge
not specified and a single width value is given
all the edges are changed to the specified width.
If edge not given and edge list is given the
width of the corresponding edge is changed. The
order of the edges can be seen from G.edges()
width: Width value. Either a list of a single value
Example
-------
set_edge_linewidth(G, edge=(1,2), width=4)
set_edge_linewidth(G, width=(1, 2, 3, 4, 5, 6))
"""
try:
edge = kwargs['edge']
except KeyError:
edge = None
try:
linewidth = kwargs['width']
except KeyError:
print("width argument required")
fig = plt.gcf()
axes = plt.gca()
no_of_nodes = G.number_of_nodes()
no_of_edges = G.number_of_edges()
edges_collection = axes.get_children()[no_of_nodes + 3]
edges = G.edges()
if edge:
current_linewidth = edges_collection.get_linewidth()
edge_index = edges.indexof(edge)
if len(current_linewidth) == 1:
current_linewidth = [copy.deepcopy(current_linewidth[0])
for i in range(no_of_edges)]
current_linewidth[edge_index] = linewidth
else:
edges_collection.set_linewidth(linewidth)
plt.draw()
def set_edge_alpha(G, **kwargs):
"""
Example
-------
set_edge_alpha(G, alpha=0)
"""
try:
edge = kwargs['edge']
except KeyError:
edge = None
try:
alpha = kwargs['alpha']
except KeyError:
print("alpha argument required")
fig = plt.gcf()
axes = plt.gca()
no_of_nodes = G.number_of_nodes()
edges_collection = axes.get_children()[no_of_nodes + 3]
edges_collection.set_linewidth(alpha)
plt.draw()