-
Notifications
You must be signed in to change notification settings - Fork 34
/
dyngraph.py
1496 lines (1219 loc) · 43.7 KB
/
dyngraph.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
"""Base class for undirected dynamic graphs.
The DynGraph class allows any hashable object as a node.
Of each interaction needs be specified the set of timestamps of its presence.
Self-loops are allowed.
"""
from typing import List, Any
import networkx as nx
from collections import defaultdict
from dynetx.utils import not_implemented
from copy import deepcopy
from itertools import combinations
__author__ = 'Giulio Rossetti'
__license__ = "BSD-Clause-2"
__email__ = "giulio.rossetti@gmail.com"
class DynGraph(nx.Graph):
"""
Base class for undirected dynamic graphs.
A DynGraph stores nodes and timestamped interaction.
DynGraph hold undirected interaction. Self loops are allowed.
Nodes can be arbitrary (hashable) Python objects with optional
key/value attributes.
Parameters
----------
data : input graph
Data to initialize graph. If data=None (default) an empty
graph is created. The data can be an interaction list, or any
NetworkX graph object.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to graph as key=value pairs.
edge_removal : bool, optional (default=True)
Specify if the dynamic graph instance should allows edge removal or not.
See Also
--------
DynDiGraph
Examples
--------
Create an empty graph structure (a "null graph") with no nodes and
no interactions.
>>> import dynetx as dn
>>> G = dn.DynGraph()
G can be grown in several ways.
**Nodes:**
Add one node at a time:
>>> G.add_node(1)
Add the nodes from any container (a list, dict, set or
even the lines from a file or the nodes from another graph).
>>> G.add_nodes_from([2,3])
>>> G.add_nodes_from(range(100,110))
>>> H=dn.DynGraph()
>>> H.add_path([0,1,2,3,4,5,6,7,8,9], t=0)
>>> G.add_nodes_from(H)
In addition to strings and integers any hashable Python object
(except None) can represent a node.
>>> G.add_node(H)
**Edges:**
G can also be grown by adding interaction and specifying their timestamp.
Add one interaction,
>>> G.add_interaction(1, 2, t=0)
a list of interaction
>>> G.add_interactions_from([(3, 2), (1,3)], t=1)
If some interaction connect nodes not yet in the graph, the nodes
are added automatically.
To traverse all interactions of a graph a time t use the interactions(t) method.
>>> G.interactions(t=1)
[(3, 2), (1, 3)]
"""
def __init__(self, data=None, edge_removal=True, **attr):
"""Initialize a graph with interaction, name, graph attributes.
Parameters
----------
data : input graph
Data to initialize graph. If data=None (default) an empty
graph is created. The data can be an interaction list, or any
NetworkX/DyNetx graph object. If the corresponding optional Python
packages are installed the data can also be a NumPy matrix
or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph.
edge_removal : bool, optional (default=True)
Specify if the dynamic graph instance should allows edge removal or not.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to graph as key=value pairs.
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G1 = dn.DynGraph(edge_removal=True)
"""
super(self.__class__, self).__init__(data, **attr)
self.time_to_edge = defaultdict(int)
self.snapshots = {}
self.edge_removal = edge_removal
self.directed = False
def nodes_iter(self, t=None, data=False):
"""Return an iterator over the nodes with respect to a given temporal snapshot.
Parameters
----------
t : snapshot id (default=None).
If None the iterator returns all the nodes of the flattened graph.
data: node data(default=False)
Returns
-------
niter : iterator
An iterator over nodes. If data=True the iterator gives
two-tuples containing (node, node data, dictionary)
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2], 0)
>>> [n for n, d in G.nodes_iter(t=0)]
[0, 1, 2]
"""
if t is not None:
if not data:
return [n for n, d in self.degree(t=t).items() if d > 0]
else:
return {n: self._node[n] for n, d in self.degree(t=t).items() if d > 0}
if not data:
return iter(self._node)
else:
return self._node
def nodes(self, t=None, data=False):
"""Return a list of the nodes in the graph at a given snapshot.
Parameters
----------
t : snapshot id (default=None)
If None the the method returns all the nodes of the flattened graph.
data : boolean, optional (default=False)
If False return a list of nodes. If True return a
two-tuple of node and node data dictionary
Returns
-------
nlist : list
A list of nodes. If data=True a list of two-tuples containing
(node, node data dictionary).
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2], 0)
>>> G.nodes(t=0)
[0, 1, 2]
>>> G.add_edge(1, 4, t=1)
>>> G.nodes(t=0)
[0, 1, 2]
"""
if data:
return [(k, v) for k, v in self.nodes_iter(t=t, data=data).items()]
else:
return [k for k in self.nodes_iter(t=t, data=data)]
def interactions(self, nbunch=None, t=None):
"""Return the list of interaction present in a given snapshot.
Edges are returned as tuples
in the order (node, neighbor).
Parameters
----------
nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated
through once.
t : snapshot id (default=None)
If None the the method returns all the edges of the flattened graph.
Returns
--------
interaction_list: list of interaction tuples
Interactions that are adjacent to any node in nbunch, or a list
of all interactions if nbunch is not specified.
See Also
--------
edges_iter : return an iterator over the interactions
Notes
-----
Nodes in nbunch that are not in the graph will be (quietly) ignored.
For directed graphs this returns the out-interaction.
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2], t=0)
>>> G.add_edge(2,3, t=1)
>>> G.interactions(t=0)
[(0, 1), (1, 2)]
>>> G.interactions()
[(0, 1), (1, 2), (2, 3)]
>>> G.interactions([0,3], t=0)
[(0, 1)]
"""
return list(self.interactions_iter(nbunch, t))
def __presence_test(self, u, v, t):
spans = self._adj[u][v]['t']
if self.edge_removal:
if spans[0][0] <= t <= spans[-1][1]:
for s in spans:
if t in range(s[0], s[1] + 1):
return True
else:
if spans[0][0] <= t <= max(self.temporal_snapshots_ids()):
return True
return False
def interactions_iter(self, nbunch=None, t=None):
"""Return an iterator over the interaction present in a given snapshot.
Edges are returned as tuples
in the order (node, neighbor).
Parameters
----------
nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated
through once.
t : snapshot id (default=None)
If None the the method returns an iterator over the edges of the flattened graph.
Returns
-------
edge_iter : iterator
An iterator of (u,v) tuples of interaction.
See Also
--------
interaction : return a list of interaction
Notes
-----
Nodes in nbunch that are not in the graph will be (quietly) ignored.
For directed graphs this returns the out-interaction.
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2], 0)
>>> G.add_interaction(2,3,1)
>>> [e for e in G.interactions_iter(t=0)]
[(0, 1), (1, 2)]
>>> list(G.interactions_iter())
[(0, 1), (1, 2), (2, 3)]
"""
seen = {} # helper dict to keep track of multiply stored interactions
if nbunch is None:
nodes_nbrs = self._adj.items()
else:
nodes_nbrs = ((n, self._adj[n]) for n in self.nbunch_iter(nbunch))
for n, nbrs in nodes_nbrs:
for nbr in nbrs:
if t is not None:
if nbr not in seen and self.__presence_test(n, nbr, t):
yield n, nbr, {"t": [t]}
else:
if nbr not in seen:
yield n, nbr, self._adj[n][nbr]
seen[n] = 1
del seen
def add_interaction(self, u, v, t=None, e=None):
"""Add an interaction between u and v at time t vanishing (optional) at time e.
The nodes u and v will be automatically added if they are
not already in the graph.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : appearance snapshot id, mandatory
e : vanishing snapshot id, optional (default=None)
See Also
--------
add_edges_from : add a collection of interaction at time t
Notes
-----
Adding an interaction that already exists but with different snapshot id updates the interaction data.
Examples
--------
The following all add the interaction e=(1,2, 0) to graph G:
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_interaction(1, 2, 0) # explicit two-node form
>>> G.add_interaction( [(1,2)], t=0 ) # add interaction from iterable container
Specify the vanishing of the interaction
>>>> G.add_interaction(1, 3, t=1, e=10)
will produce an interaction present in snapshots [0, 9]
"""
if t is None:
raise nx.NetworkXError(
"The t argument must be specified.")
if u not in self._node:
self._adj[u] = self.adjlist_inner_dict_factory()
self._node[u] = {}
if v not in self._node:
self._adj[v] = self.adjlist_inner_dict_factory()
self._node[v] = {}
if not isinstance(t, list):
t = [t, t]
for idt in [t[0]]:
if self.has_edge(u, v) and not self.edge_removal:
continue
else:
if idt not in self.time_to_edge:
self.time_to_edge[idt] = {(u, v, "+"): None}
else:
if (u, v, "+") not in self.time_to_edge[idt]:
self.time_to_edge[idt][(u, v, "+")] = None
if e is not None and self.edge_removal:
t[1] = e - 1
if e not in self.time_to_edge:
self.time_to_edge[e] = {(u, v, "-"): None}
else:
self.time_to_edge[e][(u, v, "-")] = None
# add the interaction
datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
if 't' in datadict:
app = datadict['t']
max_end = app[-1][1]
if max_end == app[-1][0] and t[0] == app[-1][0] + 1:
app[-1] = [app[-1][0], t[1]]
if app[-1][0] + 1 in self.time_to_edge and (u, v, "+") in self.time_to_edge[app[-1][0] + 1]:
del self.time_to_edge[app[-1][0] + 1][(u, v, "+")]
else:
if t[0] < app[-1][0]:
raise ValueError("The specified interaction extension is broader than "
"the ones already present for the given nodes.")
if t[0] <= max_end < t[1]:
app[-1][1] = t[1]
if max_end + 1 in self.time_to_edge:
if self.edge_removal:
del self.time_to_edge[max_end + 1][(u, v, "-")]
del self.time_to_edge[t[0]][(u, v, "+")]
elif max_end == t[0] - 1:
if max_end + 1 in self.time_to_edge and (u, v, "+") in self.time_to_edge[max_end + 1]:
del self.time_to_edge[max_end + 1][(u, v, "+")]
if self.edge_removal:
if max_end + 1 in self.time_to_edge and (u, v, '-') in self.time_to_edge[max_end + 1]:
del self.time_to_edge[max_end + 1][(u, v, '-')]
if t[1] + 1 in self.time_to_edge:
self.time_to_edge[t[1] + 1][(u, v, "-")] = None
else:
self.time_to_edge[t[1] + 1] = {(u, v, "-"): None}
app[-1][1] = t[1]
else:
app.append(t)
else:
datadict['t'] = [t]
if e is not None:
span = range(t[0], t[1] + 1)
for idt in span:
if idt not in self.snapshots:
self.snapshots[idt] = 1
else:
self.snapshots[idt] += 1
else:
for idt in t:
if idt is not None:
if idt not in self.snapshots:
self.snapshots[idt] = 1
else:
self.snapshots[idt] += 1
self._adj[u][v] = datadict
self._adj[v][u] = datadict
def add_interactions_from(self, ebunch, t=None, e=None):
"""Add all the interaction in ebunch at time t.
Parameters
----------
ebunch : container of interaction
Each interaction given in the container will be added to the
graph. The interaction must be given as as 2-tuples (u,v) or
3-tuples (u,v,d) where d is a dictionary containing interaction
data.
t : appearance snapshot id, mandatory
e : vanishing snapshot id, optional
See Also
--------
add_edge : add a single interaction
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_edges_from([(0,1),(1,2)], t=0)
"""
# set up attribute dict
if t is None:
raise nx.NetworkXError(
"The t argument must be a specified.")
# process ebunch
for ed in ebunch:
self.add_interaction(ed[0], ed[1], t, e)
def number_of_interactions(self, u=None, v=None, t=None):
"""Return the number of interaction between two nodes at time t.
Parameters
----------
u, v : nodes, optional (default=all interaction)
If u and v are specified, return the number of interaction between
u and v. Otherwise return the total number of all interaction.
t : snapshot id (default=None)
If None will be returned the number of edges on the flattened graph.
Returns
-------
nedges : int
The number of interaction in the graph. If nodes u and v are specified
return the number of interaction between those nodes. If a single node is specified return None.
See Also
--------
size
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> G.number_of_interactions()
3
>>> G.number_of_interactions(0,1, t=0)
1
>>> G.add_edge(3, 4, t=1)
>>> G.number_of_interactions()
4
"""
if t is None:
if u is None:
return int(self.size())
elif u is not None and v is not None:
if v in self._adj[u]:
return 1
else:
return 0
else:
if u is None:
return int(self.size(t))
elif u is not None and v is not None:
if v in self._adj[u]:
if self.__presence_test(u, v, t):
return 1
else:
return 0
def has_interaction(self, u, v, t=None):
"""Return True if the interaction (u,v) is in the graph at time t.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id (default=None)
If None will be returned the presence of the interaction on the flattened graph.
Returns
-------
edge_ind : bool
True if interaction is in the graph, False otherwise.
Examples
--------
Can be called either using two nodes u,v or interaction tuple (u,v)
>>> import dynetx as dn
>>> G = nx.Graph()
>>> G.add_path([0,1,2,3], t=0)
>>> G.has_interaction(0,1, t=0)
True
>>> G.has_interaction(0,1, t=1)
False
"""
try:
if t is None:
return v in self._adj[u]
else:
return v in self._adj[u] and self.__presence_test(u, v, t)
except KeyError:
return False
def neighbors(self, n, t=None):
"""Return a list of the nodes connected to the node n at time t.
Parameters
----------
n : node
A node in the graph
t : snapshot id (default=None)
If None will be returned the neighbors of the node on the flattened graph.
Returns
-------
nlist : list
A list of nodes that are adjacent to n.
Raises
------
NetworkXError
If the node n is not in the graph.
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> G.neighbors(0, t=0)
[1]
>>> G.neighbors(0, t=1)
[]
"""
try:
if t is None:
return list(self._adj[n])
else:
if n in self._adj:
return [i for i in self._adj[n] if self.__presence_test(n, i, t)]
else:
return []
except KeyError:
raise nx.NetworkXError("The node %s is not in the graph." % (n,))
def neighbors_iter(self, n, t=None):
"""Return an iterator over all neighbors of node n at time t.
Parameters
----------
n : node
A node in the graph
t : snapshot id (default=None)
If None will be returned an iterator over the neighbors of the node on the flattened graph.
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> [n for n in G.neighbors_iter(0, t=0)]
[1]
"""
try:
if t is None:
return iter(self._adj[n])
else:
return iter([i for i in self._adj[n] if self.__presence_test(n, i, t)])
except KeyError:
raise nx.NetworkXError("The node %s is not in the graph." % (n,))
def degree(self, nbunch=None, t=None):
"""Return the degree of a node or nodes at time t.
The node degree is the number of interaction adjacent to that node in a given time frame.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated
through once.
t : snapshot id (default=None)
If None will be returned the degree of nodes on the flattened graph.
Returns
-------
nd : dictionary, or number
A dictionary with nodes as keys and degree as values or
a number if a single node is specified.
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> G.degree(0, t=0)
1
>>> G.degree([0,1], t=1)
{0: 0, 1: 0}
>>> list(G.degree([0,1], t=0).values())
[1, 2]
"""
if nbunch in self: # return a single node
return next(self.degree_iter(nbunch, t))[1]
else: # return a dict
return dict(self.degree_iter(nbunch, t))
def degree_iter(self, nbunch=None, t=None):
"""Return an iterator for (node, degree) at time t.
The node degree is the number of edges adjacent to the node in a given timeframe.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated
through once.
t : snapshot id (default=None)
If None will be returned an iterator over the degree of nodes on the flattened graph.
Returns
-------
nd_iter : an iterator
The iterator returns two-tuples of (node, degree).
See Also
--------
degree
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> list(G.degree_iter(0, t=0))
[(0, 1)]
>>> list(G.degree_iter([0,1], t=0))
[(0, 1), (1, 2)]
"""
if nbunch is None:
nodes_nbrs = self._adj.items()
else:
nodes_nbrs = ((n, self._adj[n]) for n in self.nbunch_iter(nbunch))
if t is None:
for n, nbrs in nodes_nbrs:
deg = len(self._adj[n])
yield n, deg
else:
for n, nbrs in nodes_nbrs:
edges_t = len([v for v in nbrs.keys() if self.__presence_test(n, v, t)])
if edges_t > 0:
yield n, edges_t
else:
yield n, 0
def size(self, t=None):
"""Return the number of edges at time t.
Parameters
----------
t : snapshot id (default=None)
If None will be returned the size of the flattened graph.
Returns
-------
nedges : int
The number of edges
See Also
--------
number_of_edges
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> G.size(t=0)
3
"""
s = sum(self.degree(t=t).values()) / 2
return int(s)
def number_of_nodes(self, t=None):
"""Return the number of nodes in the t snpashot of a dynamic graph.
Parameters
----------
t : snapshot id (default=None)
If None return the number of nodes in the flattened graph.
Returns
-------
nnodes : int
The number of nodes in the graph.
See Also
--------
order which is identical
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2], t=0)
>>> G.number_of_nodes(0)
3
"""
if t is None:
return len(self._node)
else:
nds = sum([1 for n in self.degree(t=t).values() if n > 0])
return nds
def avg_number_of_nodes(self):
"""Return the number of nodes in the t snpashot of a dynamic graph.
Returns
-------
nnodes : int
The average number of nodes in the dynamic graph.
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2], t=0)
>>> G.add_path([0,1], t=1)
>>> G.avg_number_of_nodes()
2.5
"""
nds = sum([self.number_of_nodes(t) for t in self.temporal_snapshots_ids()])
return nds / len(self.snapshots)
def order(self, t=None):
"""Return the number of nodes in the t snpashot of a dynamic graph.
Parameters
----------
t : snapshot id (default=None)
If None return the number of nodes in the flattened graph.
Returns
-------
nnodes : int
The number of nodes in the graph.
See Also
--------
number_of_nodes which is identical
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2], t=0)
>>> G.order(0)
3
"""
return self.number_of_nodes(t)
def has_node(self, n, t=None):
"""Return True if the graph, at time t, contains the node n.
Parameters
----------
n : node
t : snapshot id (default None)
If None return the presence of the node in the flattened graph.
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2], t=0)
>>> G.has_node(0, t=0)
True
It is more readable and simpler to use
>>> 0 in G
True
"""
if t is None:
try:
return n in self._node
except TypeError:
return False
else:
deg = list(self.degree([n], t).values())
if len(deg) > 0:
return deg[0] > 0
else:
return False
def add_star(self, nodes, t=None):
"""Add a star at time t.
The first node in nodes is the middle of the star. It is connected
to all other nodes.
Parameters
----------
nodes : iterable container
A container of nodes.
t : snapshot id (default=None)
See Also
--------
add_path, add_cycle
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_star([0,1,2,3], t=0)
"""
nlist = list(nodes)
v = nlist[0]
interaction = ((v, n) for n in nlist[1:])
self.add_interactions_from(interaction, t)
def add_path(self, nodes, t=None):
"""Add a path at time t.
Parameters
----------
nodes : iterable container
A container of nodes.
t : snapshot id (default=None)
See Also
--------
add_path, add_cycle
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
"""
nlist = list(nodes)
interaction = zip(nlist[:-1], nlist[1:])
self.add_interactions_from(interaction, t)
def add_cycle(self, nodes, t=None):
"""Add a cycle at time t.
Parameters
----------
nodes : iterable container
A container of nodes.
t : snapshot id (default=None)
See Also
--------
add_path, add_cycle
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_cycle([0,1,2,3], t=0)
"""
nlist = list(nodes)
interaction = zip(nlist, nlist[1:] + [nlist[0]])
self.add_interactions_from(interaction, t)
def to_directed(self, **kwargs):
"""Return a directed representation of the graph.
Returns
-------
G : DynDiGraph
A dynamic directed graph with the same name, same nodes, and with
each edge (u,v,data) replaced by two directed edges
(u,v,data) and (v,u,data).
Notes
-----
This returns a "deepcopy" of the edge, node, and
graph attributes which attempts to completely copy
all of the data and references.
This is in contrast to the similar D=DynDiGraph(G) which returns a
shallow copy of the data.
See the Python copy module for more information on shallow
and deep copies, http://docs.python.org/library/copy.html.
Warning: If you have subclassed Graph to use dict-like objects in the
data structure, those changes do not transfer to the DynDiGraph
created by this method.
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph() # or MultiGraph, etc
>>> G.add_path([0,1])
>>> H = G.to_directed()
>>> H.edges()
[(0, 1), (1, 0)]
If already directed, return a (deep) copy
>>> G = dn.DynDiGraph() # or MultiDiGraph, etc
>>> G.add_path([0,1])
>>> H = G.to_directed()
>>> H.edges()
[(0, 1)]
"""
from .dyndigraph import DynDiGraph
G = DynDiGraph()
G.name = self.name
G.add_nodes_from(self)
for it in self.interactions_iter():
for t in it[2]['t']:
G.add_interaction(it[0], it[1], t=t[0], e=t[1])
G.graph = deepcopy(self.graph)
G._node = deepcopy(self._node)
return G
def stream_interactions(self):
"""Generate a temporal ordered stream of interactions.
Returns
-------
nd_iter : an iterator
The iterator returns a 4-tuples of (node, node, op, timestamp).
Examples
--------