-
Notifications
You must be signed in to change notification settings - Fork 266
Expand file tree
/
Copy path__init__.py
More file actions
1286 lines (1135 loc) · 40.9 KB
/
__init__.py
File metadata and controls
1286 lines (1135 loc) · 40.9 KB
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
"""
igraph library.
"""
__license__ = """
Copyright (C) 2006- The igraph development team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
"""
from igraph._igraph import (
ADJ_DIRECTED,
ADJ_LOWER,
ADJ_MAX,
ADJ_MIN,
ADJ_PLUS,
ADJ_UNDIRECTED,
ADJ_UPPER,
ALL,
ARPACKOptions,
BFSIter,
BLISS_F,
BLISS_FL,
BLISS_FLM,
BLISS_FM,
BLISS_FS,
BLISS_FSM,
DFSIter,
Edge,
GET_ADJACENCY_BOTH,
GET_ADJACENCY_LOWER,
GET_ADJACENCY_UPPER,
GraphBase,
IN,
InternalError,
OUT,
STAR_IN,
STAR_MUTUAL,
STAR_OUT,
STAR_UNDIRECTED,
STRONG,
TRANSITIVITY_NAN,
TRANSITIVITY_ZERO,
TREE_IN,
TREE_OUT,
TREE_UNDIRECTED,
Vertex,
WEAK,
arpack_options as default_arpack_options,
community_to_membership,
convex_hull,
is_bigraphical,
is_degree_sequence,
is_graphical,
is_graphical_degree_sequence,
set_progress_handler,
set_random_number_generator,
set_status_handler,
umap_compute_weights,
__igraph_version__,
)
from igraph.adjacency import (
_get_adjacency,
_get_adjacency_sparse,
_get_adjlist,
_get_biadjacency,
_get_inclist,
)
from igraph.automorphisms import (
_count_automorphisms_vf2,
_get_automorphisms_vf2,
)
from igraph.basic import (
_add_edge,
_add_edges,
_add_vertex,
_add_vertices,
_delete_edges,
_clear,
_as_directed,
_as_undirected,
)
from igraph.bipartite import (
_maximum_bipartite_matching,
_bipartite_projection,
_bipartite_projection_size,
)
from igraph.community import (
_community_fastgreedy,
_community_infomap,
_community_leading_eigenvector,
_community_label_propagation,
_community_multilevel,
_community_optimal_modularity,
_community_edge_betweenness,
_community_fluid_communities,
_community_spinglass,
_community_voronoi,
_community_walktrap,
_k_core,
_community_leiden,
_modularity,
)
from igraph.clustering import (
Clustering,
VertexClustering,
Dendrogram,
VertexDendrogram,
Cover,
VertexCover,
CohesiveBlocks,
compare_communities,
split_join_distance,
_biconnected_components,
_cohesive_blocks,
_connected_components,
_clusters,
)
from igraph.cut import (
Cut,
Flow,
_all_st_cuts,
_all_st_mincuts,
_gomory_hu_tree,
_maxflow,
_mincut,
_st_mincut,
)
from igraph.configuration import Configuration, init as init_configuration
from igraph.drawing import (
BoundingBox,
CairoGraphDrawer,
DefaultGraphDrawer,
MatplotlibGraphDrawer,
Plot,
Point,
Rectangle,
plot,
)
from igraph.drawing.colors import (
Palette,
GradientPalette,
AdvancedGradientPalette,
RainbowPalette,
PrecalculatedPalette,
ClusterColoringPalette,
color_name_to_rgb,
color_name_to_rgba,
hsv_to_rgb,
hsva_to_rgba,
hsl_to_rgb,
hsla_to_rgba,
rgb_to_hsv,
rgba_to_hsva,
rgb_to_hsl,
rgba_to_hsla,
palettes,
known_colors,
)
from igraph.drawing.graph import __plot__ as _graph_plot
from igraph.drawing.utils import autocurve
from igraph.datatypes import Matrix, DyadCensus, TriadCensus, UniqueIdGenerator
from igraph.formula import construct_graph_from_formula
from igraph.io import _format_mapping
from igraph.io.files import (
_construct_graph_from_graphmlz_file,
_construct_graph_from_dimacs_file,
_construct_graph_from_pickle_file,
_construct_graph_from_picklez_file,
_construct_graph_from_adjacency_file,
_construct_graph_from_file,
_write_graph_to_adjacency_file,
_write_graph_to_dimacs_file,
_write_graph_to_graphmlz_file,
_write_graph_to_pickle_file,
_write_graph_to_picklez_file,
_write_graph_to_file,
)
from igraph.io.objects import (
_construct_graph_from_dict_list,
_export_graph_to_dict_list,
_construct_graph_from_tuple_list,
_export_graph_to_tuple_list,
_construct_graph_from_list_dict,
_export_graph_to_list_dict,
_construct_graph_from_dict_dict,
_export_graph_to_dict_dict,
_construct_graph_from_dataframe,
_export_vertex_dataframe,
_export_edge_dataframe,
)
from igraph.io.adjacency import (
_construct_graph_from_adjacency,
_construct_graph_from_weighted_adjacency,
)
from igraph.io.libraries import (
_construct_graph_from_networkx,
_export_graph_to_networkx,
_construct_graph_from_graph_tool,
_export_graph_to_graph_tool,
)
from igraph.io.random import (
_construct_random_geometric_graph,
)
from igraph.io.bipartite import (
_construct_bipartite_graph,
_construct_bipartite_graph_from_adjacency,
_construct_full_bipartite_graph,
_construct_random_bipartite_graph,
)
from igraph.io.images import _write_graph_to_svg
from igraph.layout import (
Layout,
align_layout,
_layout,
_layout_auto,
_layout_sugiyama,
_layout_method_wrapper,
_3d_version_for,
_layout_mapping,
)
from igraph.matching import Matching
from igraph.operators import (
disjoint_union,
union,
intersection,
operator_method_registry as _operator_method_registry,
)
from igraph.rewiring import _rewire
from igraph.seq import EdgeSeq, VertexSeq, _add_proxy_methods
from igraph.statistics import (
FittedPowerLaw,
Histogram,
RunningMean,
mean,
median,
percentile,
quantile,
power_law_fit,
)
from igraph.structural import (
_indegree,
_outdegree,
_degree_distribution,
_pagerank,
_shortest_paths,
)
from igraph.summary import GraphSummary, summary
from igraph.utils import (
deprecated,
numpy_to_contiguous_memoryview,
rescale,
)
from igraph.version import __version__, __version_info__
import os
import sys
class Graph(GraphBase):
"""Generic graph.
This class is built on top of L{GraphBase}, so the order of the
methods in the generated API documentation is a little bit obscure:
inherited methods come after the ones implemented directly in the
subclass. L{Graph} provides many functions that L{GraphBase} does not,
mostly because these functions are not speed critical and they were
easier to implement in Python than in pure C. An example is the
attribute handling in the constructor: the constructor of L{Graph}
accepts three dictionaries corresponding to the graph, vertex and edge
attributes while the constructor of L{GraphBase} does not. This extension
was needed to make L{Graph} serializable through the C{pickle} module.
L{Graph} also overrides some functions from L{GraphBase} to provide a
more convenient interface; e.g., layout functions return a L{Layout}
instance from L{Graph} instead of a list of coordinate pairs.
Graphs can also be indexed by strings or pairs of vertex indices or vertex
names. When a graph is indexed by a string, the operation translates to
the retrieval, creation, modification or deletion of a graph attribute:
>>> g = Graph.Full(3)
>>> g["name"] = "Triangle graph"
>>> g["name"]
'Triangle graph'
>>> del g["name"]
When a graph is indexed by a pair of vertex indices or names, the graph
itself is treated as an adjacency matrix and the corresponding cell of
the matrix is returned:
>>> g = Graph.Full(3)
>>> g.vs["name"] = ["A", "B", "C"]
>>> g[1, 2]
1
>>> g["A", "B"]
1
>>> g["A", "B"] = 0
>>> g.ecount()
2
Assigning values different from zero or one to the adjacency matrix will
be translated to one, unless the graph is weighted, in which case the
numbers will be treated as weights:
>>> g.is_weighted()
False
>>> g["A", "B"] = 2
>>> g["A", "B"]
1
>>> g.es["weight"] = 1.0
>>> g.is_weighted()
True
>>> g["A", "B"] = 2
>>> g["A", "B"]
2
>>> g.es["weight"]
[1.0, 1.0, 2]
"""
# Some useful aliases
omega = GraphBase.clique_number
alpha = GraphBase.independence_number
shell_index = GraphBase.coreness
cut_vertices = GraphBase.articulation_points
blocks = GraphBase.biconnected_components
evcent = GraphBase.eigenvector_centrality
vertex_disjoint_paths = GraphBase.vertex_connectivity
edge_disjoint_paths = GraphBase.edge_connectivity
cohesion = GraphBase.vertex_connectivity
adhesion = GraphBase.edge_connectivity
# Compatibility aliases
shortest_paths = _shortest_paths
shortest_paths_dijkstra = shortest_paths
subgraph = GraphBase.induced_subgraph
def __init__(self, *args, **kwds):
"""__init__(n=0, edges=None, directed=False, graph_attrs=None,
vertex_attrs=None, edge_attrs=None)
Constructs a graph from scratch.
@keyword n: the number of vertices. Can be omitted, the default is
zero. Note that if the edge list contains vertices with indexes
larger than or equal to M{n}, then the number of vertices will
be adjusted accordingly.
@keyword edges: the edge list where every list item is a pair of
integers. If any of the integers is larger than M{n-1}, the number
of vertices is adjusted accordingly. C{None} means no edges.
@keyword directed: whether the graph should be directed
@keyword graph_attrs: the attributes of the graph as a dictionary.
@keyword vertex_attrs: the attributes of the vertices as a dictionary.
The keys of the dictionary must be the names of the attributes; the
values must be iterables with exactly M{n} items where M{n} is the
number of vertices.
@keyword edge_attrs: the attributes of the edges as a dictionary. The
keys of the dictionary must be the names of the attributes; the values
must be iterables with exactly M{m} items where M{m} is the number of
edges.
"""
# Pop the special __ptr keyword argument
ptr = kwds.pop("__ptr", None)
# Set up default values for the parameters. This should match the order
# in *args
kwd_order = (
"n",
"edges",
"directed",
"graph_attrs",
"vertex_attrs",
"edge_attrs",
)
params = [0, [], False, {}, {}, {}]
# Is there any keyword argument in kwds that we don't know? If so,
# freak out.
unknown_kwds = set(kwds.keys())
unknown_kwds.difference_update(kwd_order)
if unknown_kwds:
raise TypeError(
"{0}.__init__ got an unexpected keyword argument {1!r}".format(
self.__class__.__name__, unknown_kwds.pop()
)
)
# If the first argument is a list or any other iterable, assume that
# the number of vertices were omitted
args = list(args)
if len(args) > 0 and hasattr(args[0], "__iter__"):
args.insert(0, params[0])
# Override default parameters from args
params[: len(args)] = args
# Override default parameters from keywords
for idx, k in enumerate(kwd_order):
if k in kwds:
params[idx] = kwds[k]
# Now, translate the params list to argument names
nverts, edges, directed, graph_attrs, vertex_attrs, edge_attrs = params
# When the number of vertices is None, assume that the user meant zero
if nverts is None:
nverts = 0
# When 'edges' is None, assume that the user meant an empty list
if edges is None:
edges = []
# When 'edges' is a NumPy array or matrix, convert it into a memoryview
# as the lower-level C API works with memoryviews only
try:
from numpy import ndarray, matrix
if isinstance(edges, (ndarray, matrix)):
edges = numpy_to_contiguous_memoryview(edges)
except ImportError:
pass
# Initialize the graph
if ptr:
super().__init__(__ptr=ptr)
else:
super().__init__(nverts, edges, directed)
# Set the graph attributes
for key, value in graph_attrs.items():
if isinstance(key, int):
key = str(key)
self[key] = value
# Set the vertex attributes
for key, value in vertex_attrs.items():
if isinstance(key, int):
key = str(key)
self.vs[key] = value
# Set the edge attributes
for key, value in edge_attrs.items():
if isinstance(key, int):
key = str(key)
self.es[key] = value
#############################################
# Auxiliary I/O functions
# Graph libraries
from_networkx = classmethod(_construct_graph_from_networkx)
to_networkx = _export_graph_to_networkx
from_graph_tool = classmethod(_construct_graph_from_graph_tool)
to_graph_tool = _export_graph_to_graph_tool
# Files
Read_DIMACS = classmethod(_construct_graph_from_dimacs_file)
write_dimacs = _write_graph_to_dimacs_file
Read_GraphMLz = classmethod(_construct_graph_from_graphmlz_file)
write_graphmlz = _write_graph_to_graphmlz_file
Read_Pickle = classmethod(_construct_graph_from_pickle_file)
write_pickle = _write_graph_to_pickle_file
Read_Picklez = classmethod(_construct_graph_from_picklez_file)
write_picklez = _write_graph_to_picklez_file
Read_Adjacency = classmethod(_construct_graph_from_adjacency_file)
write_adjacency = _write_graph_to_adjacency_file
write_svg = _write_graph_to_svg
Read = classmethod(_construct_graph_from_file)
Load = Read
write = _write_graph_to_file
save = write
# Various objects
# list of dict representation of graphs
DictList = classmethod(_construct_graph_from_dict_list)
to_dict_list = _export_graph_to_dict_list
# tuple-like representation of graphs
TupleList = classmethod(_construct_graph_from_tuple_list)
to_tuple_list = _export_graph_to_tuple_list
# dict of sequence representation of graphs
ListDict = classmethod(_construct_graph_from_list_dict)
to_list_dict = _export_graph_to_list_dict
# dict of dicts representation of graphs
DictDict = classmethod(_construct_graph_from_dict_dict)
to_dict_dict = _export_graph_to_dict_dict
# adjacency matrix
Adjacency = classmethod(_construct_graph_from_adjacency)
Weighted_Adjacency = classmethod(_construct_graph_from_weighted_adjacency)
# pandas dataframe(s)
DataFrame = classmethod(_construct_graph_from_dataframe)
get_vertex_dataframe = _export_vertex_dataframe
get_edge_dataframe = _export_edge_dataframe
# Bipartite graphs
Bipartite = classmethod(_construct_bipartite_graph)
Biadjacency = classmethod(_construct_bipartite_graph_from_adjacency)
Full_Bipartite = classmethod(_construct_full_bipartite_graph)
Random_Bipartite = classmethod(_construct_random_bipartite_graph)
# Other constructors
GRG = classmethod(_construct_random_geometric_graph)
# Graph formulae
Formula = classmethod(construct_graph_from_formula)
#############################################
# Summary/string representation
def __str__(self):
"""Returns a string representation of the graph.
Behind the scenes, this method constructs a L{GraphSummary}
instance and invokes its C{__str__} method with a verbosity of 1
and attribute printing turned off.
See the documentation of L{GraphSummary} for more details about the
output.
"""
params = {
"verbosity": 1,
"width": 78,
"print_graph_attributes": False,
"print_vertex_attributes": False,
"print_edge_attributes": False,
}
return self.summary(**params)
def summary(self, verbosity=0, width=None, *args, **kwds):
"""Returns the summary of the graph.
The output of this method is similar to the output of the
C{__str__} method. If I{verbosity} is zero, only the header line
is returned (see C{__str__} for more details), otherwise the
header line and the edge list is printed.
Behind the scenes, this method constructs a L{GraphSummary}
object and invokes its C{__str__} method.
@param verbosity: if zero, only the header line is returned
(see C{__str__} for more details), otherwise the header line
and the full edge list is printed.
@param width: the number of characters to use in one line.
If C{None}, no limit will be enforced on the line lengths.
@return: the summary of the graph.
"""
return str(GraphSummary(self, verbosity, width, *args, **kwds))
#############################################
# Commonly used attributes
def is_named(self):
"""Returns whether the graph is named.
A graph is named if and only if it has a C{"name"} vertex attribute.
"""
return "name" in self.vertex_attributes()
def is_weighted(self):
"""Returns whether the graph is weighted.
A graph is weighted if and only if it has a C{"weight"} edge attribute.
"""
return "weight" in self.edge_attributes()
#############################################
# Neighbors
def predecessors(self, vertex, loops=True, multiple=True):
"""Returns the predecessors of a given vertex.
Equivalent to calling the L{Graph.neighbors()} method with mode=C{\"in\"}.
"""
return self.neighbors(vertex, mode="in", loops=loops, multiple=multiple)
def successors(self, vertex, loops=True, multiple=True):
"""Returns the successors of a given vertex.
Equivalent to calling the L{Graph.neighbors()} method with mode=C{\"out\"}.
"""
return self.neighbors(vertex, mode="out", loops=loops, multiple=multiple)
#############################################
# Vertex and edge sequence
@property
def vs(self):
"""The vertex sequence of the graph"""
return VertexSeq(self)
@property
def es(self):
"""The edge sequence of the graph"""
return EdgeSeq(self)
#############################################
# Basic operations
add_edge = _add_edge
add_edges = _add_edges
add_vertex = _add_vertex
add_vertices = _add_vertices
delete_edges = _delete_edges
clear = _clear
as_directed = _as_directed
as_undirected = _as_undirected
###################
# Graph operators
__iadd__ = _operator_method_registry["__iadd__"]
__add__ = _operator_method_registry["__add__"]
__and__ = _operator_method_registry["__and__"]
__isub__ = _operator_method_registry["__isub__"]
__sub__ = _operator_method_registry["__sub__"]
__mul__ = _operator_method_registry["__mul__"]
__or__ = _operator_method_registry["__or__"]
disjoint_union = _operator_method_registry["disjoint_union"]
union = _operator_method_registry["union"]
intersection = _operator_method_registry["intersection"]
rewire = _rewire
#############################################
# Adjacency/incidence
get_adjacency = _get_adjacency
get_adjacency_sparse = _get_adjacency_sparse
get_adjlist = _get_adjlist
get_biadjacency = _get_biadjacency
get_inclist = _get_inclist
#############################################
# Structural properties
indegree = _indegree
outdegree = _outdegree
degree_distribution = _degree_distribution
pagerank = _pagerank
#############################################
# Flow
all_st_cuts = _all_st_cuts
all_st_mincuts = _all_st_mincuts
gomory_hu_tree = _gomory_hu_tree
maxflow = _maxflow
mincut = _mincut
st_mincut = _st_mincut
#############################################
# Connected components
biconnected_components = _biconnected_components
clusters = _clusters
cohesive_blocks = _cohesive_blocks
connected_components = _connected_components
blocks = _biconnected_components
components = _connected_components
#############################################
# Community detection/clustering
community_fastgreedy = _community_fastgreedy
community_infomap = _community_infomap
community_leading_eigenvector = _community_leading_eigenvector
community_label_propagation = _community_label_propagation
community_multilevel = _community_multilevel
community_optimal_modularity = _community_optimal_modularity
community_edge_betweenness = _community_edge_betweenness
community_fluid_communities = _community_fluid_communities
community_spinglass = _community_spinglass
community_voronoi = _community_voronoi
community_walktrap = _community_walktrap
k_core = _k_core
community_leiden = _community_leiden
modularity = _modularity
#############################################
# Layout
layout = _layout
layout_auto = _layout_auto
layout_sugiyama = _layout_sugiyama
#############################################
# Plotting
__plot__ = _graph_plot
#############################################
# Bipartite
maximum_bipartite_matching = _maximum_bipartite_matching
bipartite_projection = _bipartite_projection
bipartite_projection_size = _bipartite_projection_size
#############################################
# Automorphisms
count_automorphisms_vf2 = _count_automorphisms_vf2
get_automorphisms_vf2 = _get_automorphisms_vf2
###########################
# Paths/traversals
def get_all_simple_paths(self, v, to=None, minlen=0, maxlen=-1, mode="out", max_results=None):
"""Calculates all the simple paths from a given node to some other nodes
(or all of them) in a graph.
A path is simple if its vertices are unique, i.e. no vertex is visited
more than once.
Note that potentially there are exponentially many paths between two
vertices of a graph, especially if your graph is lattice-like. In this
case, you may run out of memory when using this function.
@param v: the source for the calculated paths
@param to: a vertex selector describing the destination for the calculated
paths. This can be a single vertex ID, a list of vertex IDs, a single
vertex name, a list of vertex names or a L{VertexSeq} object. C{None}
means all the vertices.
@param minlen: minimum length of path that is considered.
@param maxlen: maximum length of path that is considered. If negative,
paths of all lengths are considered.
@param mode: the directionality of the paths. C{\"in\"} means to calculate
incoming paths, C{\"out\"} means to calculate outgoing paths, C{\"all\"} means
to calculate both ones.
@param max_results: the maximum number of results to return. C{None} means
no limit on the number of results.
@return: all of the simple paths from the given node to every other
reachable node in the graph in a list. Note that in case of mode=C{\"in\"},
the vertices in a path are returned in reversed order!
"""
return self._get_all_simple_paths(v, to, minlen, maxlen, mode, max_results)
def path_length_hist(self, directed=True):
"""Returns the path length histogram of the graph
@param directed: whether to consider directed paths. Ignored for
undirected graphs.
@return: a L{Histogram} object. The object will also have an
C{unconnected} attribute that stores the number of unconnected
vertex pairs (where the second vertex can not be reached from
the first one). The latter one will be of type long (and not
a simple integer), since this can be I{very} large.
"""
data, unconn = GraphBase.path_length_hist(self, directed)
hist = Histogram(bin_width=1)
for i, length in enumerate(data):
hist.add(i + 1, length)
hist.unconnected = int(unconn)
return hist
# DFS (C version will come soon)
def dfs(self, vid, mode=OUT):
"""Conducts a depth first search (DFS) on the graph.
@param vid: the root vertex ID
@param mode: either C{\"in\"} or C{\"out\"} or C{\"all\"}, ignored
for undirected graphs.
@return: a tuple with the following items:
- The vertex IDs visited (in order)
- The parent of every vertex in the DFS
"""
nv = self.vcount()
added = [False for v in range(nv)]
stack = []
# prepare output
vids = []
parents = []
# ok start from vid
stack.append((vid, self.neighbors(vid, mode=mode)))
vids.append(vid)
parents.append(-1)
added[vid] = True
# go down the rabbit hole
while stack:
vid, neighbors = stack[-1]
if neighbors:
# Get next neighbor to visit
neighbor = neighbors.pop()
if not added[neighbor]:
# Add hanging subtree neighbor
stack.append((neighbor, self.neighbors(neighbor, mode=mode)))
vids.append(neighbor)
parents.append(vid)
added[neighbor] = True
else:
# No neighbor found, end of subtree
stack.pop()
return (vids, parents)
def spanning_tree(self, weights=None, return_tree=True, method="auto"):
"""Calculates a minimum spanning tree for a graph.
B{Reference}: Prim, R.C. Shortest connection networks and some
generalizations. I{Bell System Technical Journal} 36:1389-1401, 1957.
@param weights: a vector containing weights for every edge in
the graph. C{None} means that the graph is unweighted.
@param return_tree: whether to return the minimum spanning tree (when
C{return_tree} is C{True}) or to return the IDs of the edges in
the minimum spanning tree instead (when C{return_tree} is C{False}).
The default is C{True} for historical reasons as this argument was
introduced in igraph 0.6.
@param method: the algorithm to use. C{"auto"} means that the algorithm
is selected automatically. C{"prim"} means that Prim's algorithm is
used. C{"kruskal"} means that Kruskal's algorithm is used.
C{"unweighted"} assumes that the graph is unweighted even if weights
are provided.
@return: the spanning tree as a L{Graph} object if C{return_tree}
is C{True} or the IDs of the edges that constitute the spanning
tree if C{return_tree} is C{False}.
"""
result = GraphBase._spanning_tree(self, weights, method)
if return_tree:
return self.subgraph_edges(result, delete_vertices=False)
return result
###########################
# Dyad/triad census
def dyad_census(self, *args, **kwds):
"""Calculates the dyad census of the graph.
Dyad census means classifying each pair of vertices of a directed
graph into three categories: mutual (there is an edge from I{a} to
I{b} and also from I{b} to I{a}), asymmetric (there is an edge
from I{a} to I{b} or from I{b} to I{a} but not the other way round)
and null (there is no connection between I{a} and I{b}).
B{Reference}: Holland, P.W. and Leinhardt, S. A Method for Detecting
Structure in Sociometric Data. I{American Journal of Sociology}, 70,
492-513, 1970.
@return: a L{DyadCensus} object.
"""
return DyadCensus(GraphBase.dyad_census(self, *args, **kwds))
def triad_census(self, *args, **kwds):
"""Calculates the triad census of the graph.
B{Reference}: Davis, J.A. and Leinhardt, S. The Structure of
Positive Interpersonal Relations in Small Groups. In:
J. Berger (Ed.), Sociological Theories in Progress, Volume 2,
218-251. Boston: Houghton Mifflin (1972).
@return: a L{TriadCensus} object.
"""
return TriadCensus(GraphBase.triad_census(self, *args, **kwds))
###########################
# Other functions
def transitivity_avglocal_undirected(self, mode="nan", weights=None):
"""Calculates the average of the vertex transitivities of the graph.
In the unweighted case, the transitivity measures the probability that
two neighbors of a vertex are connected. In case of the average local
transitivity, this probability is calculated for each vertex and then
the average is taken. Vertices with less than two neighbors require
special treatment, they will either be left out from the calculation
or they will be considered as having zero transitivity, depending on
the I{mode} parameter. The calculation is slightly more involved for
weighted graphs; in this case, weights are taken into account according
to the formula of Barrat et al (see the references).
Note that this measure is different from the global transitivity
measure (see L{transitivity_undirected()}) as it simply takes the
average local transitivity across the whole network.
B{References}
- Watts DJ and Strogatz S: Collective dynamics of small-world
networks. I{Nature} 393(6884):440-442, 1998.
- Barrat A, Barthelemy M, Pastor-Satorras R and Vespignani A:
The architecture of complex weighted networks. I{PNAS} 101, 3747
(2004). U{https://arxiv.org/abs/cond-mat/0311416}.
@param mode: defines how to treat vertices with degree less than two.
If C{TRANSITIVITY_ZERO} or C{"zero"}, these vertices will have zero
transitivity. If C{TRANSITIVITY_NAN} or C{"nan"}, these vertices
will be excluded from the average.
@param weights: edge weights to be used. Can be a sequence or iterable
or even an edge attribute name.
@see: L{transitivity_undirected()}, L{transitivity_local_undirected()}
"""
if weights is None:
return GraphBase.transitivity_avglocal_undirected(self, mode)
xs = self.transitivity_local_undirected(mode=mode, weights=weights)
return sum(xs) / float(len(xs))
###########################
# ctypes support
@property
def _as_parameter_(self):
return self._raw_pointer()
# Other type functions
def __bool__(self):
"""Returns True if the graph has at least one vertex, False otherwise."""
return self.vcount() > 0
def __coerce__(self, other):
"""Coercion rules.
This method is needed to allow the graph to react to additions
with lists, tuples, integers, strings, vertices, edges and so on.
"""
if isinstance(other, (int, tuple, list, str)):
return self, other
if isinstance(other, Vertex):
return self, other
if isinstance(other, VertexSeq):
return self, other
if isinstance(other, Edge):
return self, other
if isinstance(other, EdgeSeq):
return self, other
return NotImplemented
@classmethod
def _reconstruct(cls, attrs, *args, **kwds):
"""Reconstructs a Graph object from Python's pickled format.
This method is for internal use only, it should not be called
directly."""
result = cls(*args, **kwds)
result.__dict__.update(attrs)
return result
def __reduce__(self):
"""Support for pickling."""
constructor = self.__class__
gattrs, vattrs, eattrs = {}, {}, {}
for attr in self.attributes():
gattrs[attr] = self[attr]
for attr in self.vs.attribute_names():
vattrs[attr] = self.vs[attr]
for attr in self.es.attribute_names():
eattrs[attr] = self.es[attr]
parameters = (
self.vcount(),
self.get_edgelist(),
self.is_directed(),
gattrs,
vattrs,
eattrs,
)
return (constructor, parameters, self.__dict__)
__iter__ = None # needed for PyPy
__hash__ = None # needed for PyPy
###########################
# Deprecated functions
@classmethod
def Incidence(cls, *args, **kwds):
"""Deprecated alias to L{Graph.Biadjacency()}."""
deprecated("Graph.Incidence() is deprecated; use Graph.Biadjacency() instead")
return cls.Biadjacency(*args, **kwds)
def are_connected(self, *args, **kwds):
"""Deprecated alias to L{Graph.are_adjacent()}."""
deprecated(
"Graph.are_connected() is deprecated; use Graph.are_adjacent() " "instead"
)
return self.are_adjacent(*args, **kwds)
def get_incidence(self, *args, **kwds):
"""Deprecated alias to L{Graph.get_biadjacency()}."""
deprecated(
"Graph.get_incidence() is deprecated; use Graph.get_biadjacency() "
"instead"
)
return self.get_biadjacency(*args, **kwds)
##############################################################
# I/O format mapping
Graph._format_mapping = _format_mapping
##############################################################
# Additional methods of VertexSeq and EdgeSeq that call Graph methods
_add_proxy_methods()
##############################################################
# Layout mapping