python-igraph API reference

List of all classes, functions and methods in python-igraph

class documentation

class GraphBase:

Known subclasses: igraph.Graph

View In Hierarchy

Low-level representation of a graph.

Don't use it directly, use igraph.Graph instead.

Unknown Field: deffield
refReference
Method __new__ Create and return a new object. See help(type) for accurate signature.
Method add_edges Adds edges to the graph.
Method add_vertices Adds vertices to the graph.
Method Adjacency Generates a graph from its adjacency matrix.
Method all_minimal_st_separators Returns a list containing all the minimal s-t separators of a graph.
Method all_st_cuts Returns all the cuts between the source and target vertices in a directed graph.
Method all_st_mincuts Returns all minimum cuts between the source and target vertices in a directed graph.
Method are_connected Decides whether two given vertices are directly connected.
Method articulation_points Returns the list of articulation points in the graph.
Method assortativity Returns the assortativity of the graph based on numeric properties of the vertices.
Method assortativity_degree Returns the assortativity of a graph based on vertex degrees.
Method assortativity_nominal Returns the assortativity of the graph based on vertex categories.
Method Asymmetric_Preference Generates a graph based on asymmetric vertex types and connection probabilities.
Method Atlas Generates a graph from the Graph Atlas.
Method attributes No summary
Method authority_score Calculates Kleinberg's authority score for the vertices of the graph
Method average_path_length Calculates the average path length in a graph.
Method Barabasi Generates a graph based on the Barabasi-Albert model.
Method betweenness Calculates or estimates the betweenness of vertices in a graph.
Method bfs Conducts a breadth first search (BFS) on the graph.
Method bfsiter Constructs a breadth first search (BFS) iterator of the graph.
Method bibcoupling Calculates bibliographic coupling scores for given vertices in a graph.
Method biconnected_components Calculates the biconnected components of the graph.
Method bipartite_projection Internal function, undocumented.
Method bipartite_projection_size Internal function, undocumented.
Method bridges Returns the list of bridges in the graph.
Method canonical_permutation Calculates the canonical permutation of a graph using the BLISS isomorphism algorithm.
Method chordal_completion chordal_complation(alpha=None, alpham1=None) --
Method clique_number Returns the clique number of the graph.
Method cliques Returns some or all cliques of the graph as a list of tuples.
Method closeness Calculates the closeness centralities of given vertices in a graph.
Method clusters Calculates the (strong or weak) clusters for a given graph.
Method cocitation Calculates cocitation scores for given vertices in a graph.
Method cohesive_blocks Calculates the cohesive block structure of the graph.
Method community_edge_betweenness Community structure detection based on the betweenness of the edges in the network. This algorithm was invented by M Girvan and MEJ Newman, see: M Girvan and MEJ Newman: Community structure in social and biological networks, Proc...
Method community_fastgreedy Finds the community structure of the graph according to the algorithm of Clauset et al based on the greedy optimization of modularity.
Method community_infomap Finds the community structure of the network according to the Infomap method of Martin Rosvall and Carl T. Bergstrom.
Method community_label_propagation Finds the community structure of the graph according to the label propagation method of Raghavan et al.
Method community_leading_eigenvector A proper implementation of Newman's eigenvector community structure detection. Each split is done by maximizing the modularity regarding the original network. See the reference for details.
Method community_leiden Finds the community structure of the graph using the Leiden algorithm of Traag, van Eck & Waltman.
Method community_multilevel Finds the community structure of the graph according to the multilevel algorithm of Blondel et al. This is a bottom-up algorithm: initially every vertex belongs to a separate community, and vertices are moved between communities iteratively in a way that maximizes the vertices' local contribution to the overall modularity score...
Method community_optimal_modularity Calculates the optimal modularity score of the graph and the corresponding community structure.
Method community_spinglass Finds the community structure of the graph according to the spinglass community detection method of Reichardt & Bornholdt.
Method community_walktrap Finds the community structure of the graph according to the random walk method of Latapy & Pons.
Method complementer Returns the complementer of the graph
Method compose Returns the composition of two graphs.
Method constraint Calculates Burt's constraint scores for given vertices in a graph.
Method contract_vertices Contracts some vertices in the graph, i.e. replaces groups of vertices with single vertices. Edges are not affected.
Method convergence_degree Undocumented (yet).
Method convergence_field_size Undocumented (yet).
Method copy Creates a copy of the graph.
Method coreness Finds the coreness (shell index) of the vertices of the network.
Method count_isomorphisms_vf2 Determines the number of isomorphisms between the graph and another one
Method count_multiple Counts the multiplicities of the given edges.
Method count_subisomorphisms_vf2 Determines the number of subisomorphisms between the graph and another one
Method De_Bruijn Generates a de Bruijn graph with parameters (m, n)
Method decompose Decomposes the graph into subgraphs.
Method degree Returns some vertex degrees from the graph.
Method Degree_Sequence Generates a graph with a given degree sequence.
Method delete_edges Removes edges from the graph.
Method delete_vertices Deletes vertices and all its edges from the graph.
Method density Calculates the density of the graph.
Method dfsiter Constructs a depth first search (DFS) iterator of the graph.
Method diameter Calculates the diameter of the graph.
Method difference Subtracts the given graph from the original
Method diversity Calculates the structural diversity index of the vertices.
Method dominator Returns the dominator tree from the given root node
Method dyad_census Dyad census, as defined by Holland and Leinhardt
Method eccentricity Calculates the eccentricities of given vertices in a graph.
Method ecount Counts the number of edges.
Method edge_attributes No summary
Method edge_betweenness Calculates or estimates the edge betweennesses in a graph.
Method edge_connectivity Calculates the edge connectivity of the graph or between some vertices.
Method eigen_adjacency Undocumented
Method eigenvector_centrality Calculates the eigenvector centralities of the vertices in a graph.
Method Erdos_Renyi Generates a graph based on the Erdos-Renyi model.
Method Establishment Generates a graph based on a simple growing model with vertex types.
Method Famous Generates a famous graph based on its name.
Method farthest_points Returns two vertex IDs whose distance equals the actual diameter of the graph.
Method feedback_arc_set Calculates an approximately or exactly minimal feedback arc set.
Method Forest_Fire Generates a graph based on the forest fire model
Method Full Generates a full graph (directed or undirected, with or without loops).
Method Full_Citation Generates a full citation graph
Method get_adjacency Returns the adjacency matrix of a graph.
Method get_all_shortest_paths Calculates all of the shortest paths from/to a given node in a graph.
Method get_diameter Returns a path with the actual diameter of the graph.
Method get_edgelist Returns the edge list of a graph.
Method get_eid Returns the edge ID of an arbitrary edge between vertices v1 and v2
Method get_eids Returns the edge IDs of some edges between some vertices.
Method get_incidence Internal function, undocumented.
Method get_isomorphisms_vf2 Returns all isomorphisms between the graph and another one
Method get_shortest_paths Calculates the shortest paths from/to a given node in a graph.
Method get_subisomorphisms_lad Returns all subisomorphisms between the graph and another one using the LAD algorithm.
Method get_subisomorphisms_vf2 Returns all subisomorphisms between the graph and another one
Method girth Returns the girth of the graph.
Method gomory_hu_tree Internal function, undocumented.
Method Growing_Random Generates a growing random graph.
Method harmonic_centrality Calculates the harmonic centralities of given vertices in a graph.
Method has_multiple Checks whether the graph has multiple edges.
Method hub_score Calculates Kleinberg's hub score for the vertices of the graph
Method incident Returns the edges a given vertex is incident on.
Method independence_number Returns the independence number of the graph.
Method independent_vertex_sets Returns some or all independent vertex sets of the graph as a list of tuples.
Method induced_subgraph Returns a subgraph spanned by the given vertices.
Method is_bipartite Decides whether the graph is bipartite or not.
Method is_chordal Returns whether the graph is chordal or not.
Method is_connected Decides whether the graph is connected.
Method is_dag Checks whether the graph is a DAG (directed acyclic graph).
Method is_directed Checks whether the graph is directed.
Method is_loop Checks whether a specific set of edges contain loop edges
Method is_minimal_separator Decides whether the given vertex set is a minimal separator.
Method is_multiple Checks whether an edge is a multiple edge.
Method is_mutual Checks whether an edge has an opposite pair.
Method is_separator Decides whether the removal of the given vertices disconnects the graph.
Method is_simple Checks whether the graph is simple (no loop or multiple edges).
Method is_tree Checks whether the graph is a (directed or undirected) tree graph.
Method Isoclass Generates a graph with a given isomorphism class.
Method isoclass Returns the isomorphism class of the graph or its subgraph.
Method isomorphic Checks whether the graph is isomorphic to another graph.
Method isomorphic_bliss Checks whether the graph is isomorphic to another graph, using the BLISS isomorphism algorithm.
Method isomorphic_vf2 Checks whether the graph is isomorphic to another graph, using the VF2 isomorphism algorithm.
Method K_Regular Generates a k-regular random graph
Method Kautz Generates a Kautz graph with parameters (m, n)
Method knn Calculates the average degree of the neighbors for each vertex, and the same quantity as the function of vertex degree.
Method laplacian Returns the Laplacian matrix of a graph.
Method largest_cliques Returns the largest cliques of the graph as a list of tuples.
Method largest_independent_vertex_sets Returns the largest independent vertex sets of the graph as a list of tuples.
Method Lattice Generates a regular lattice.
Method layout_bipartite Place the vertices of a bipartite graph in two layers.
Method layout_circle Places the vertices of the graph uniformly on a circle or a sphere.
Method layout_davidson_harel Places the vertices on a 2D plane according to the Davidson-Harel layout algorithm.
Method layout_drl Places the vertices on a 2D plane or in the 3D space ccording to the DrL layout algorithm.
Method layout_fruchterman_reingold Places the vertices on a 2D plane according to the Fruchterman-Reingold algorithm.
Method layout_graphopt This is a port of the graphopt layout algorithm by Michael Schmuhl. graphopt version 0.4.1 was rewritten in C and the support for layers was removed.
Method layout_grid Places the vertices of a graph in a 2D or 3D grid.
Method layout_kamada_kawai Places the vertices on a plane according to the Kamada-Kawai algorithm.
Method layout_lgl Places the vertices on a 2D plane according to the Large Graph Layout.
Method layout_mds Places the vertices in an Euclidean space with the given number of dimensions using multidimensional scaling.
Method layout_random Places the vertices of the graph randomly.
Method layout_reingold_tilford Places the vertices on a 2D plane according to the Reingold-Tilford layout algorithm.
Method layout_reingold_tilford_circular Circular Reingold-Tilford layout for trees.
Method layout_star Calculates a star-like layout for the graph.
Method LCF Generates a graph from LCF notation.
Method linegraph Returns the line graph of the graph.
Method maxdegree Returns the maximum degree of a vertex set in the graph.
Method maxflow Returns the maximum flow between the source and target vertices.
Method maxflow_value Returns the value of the maximum flow between the source and target vertices.
Method maximal_cliques Returns the maximal cliques of the graph as a list of tuples.
Method maximal_independent_vertex_sets Returns the maximal independent vertex sets of the graph as a list of tuples.
Method maximum_cardinality_search Conducts a maximum cardinality search on the graph. The function computes a rank alpha for each vertex such that visiting vertices in decreasing rank order corresponds to always choosing the vertex with the most already visited neighbors as the next one to visit.
Method mincut Calculates the minimum cut between the source and target vertices or within the whole graph.
Method mincut_value Returns the minimum cut between the source and target vertices or within the whole graph.
Method minimum_size_separators Returns a list containing all separator vertex sets of minimum size.
Method modularity Calculates the modularity of the graph with respect to some vertex types.
Method motifs_randesu Counts the number of motifs in the graph
Method motifs_randesu_estimate Counts the total number of motifs in the graph
Method motifs_randesu_no Counts the total number of motifs in the graph
Method neighborhood For each vertex specified by vertices, returns the vertices reachable from that vertex in at most order steps. If mindist is larger than zero, vertices that are reachable in less than mindist steps are excluded.
Method neighborhood_size For each vertex specified by vertices, returns the number of vertices reachable from that vertex in at most order steps. If mindist is larger than zero, vertices that are reachable in less than mindist...
Method neighbors Returns adjacent vertices to a given vertex.
Method path_length_hist Calculates the path length histogram of the graph
Method permute_vertices Permutes the vertices of the graph according to the given permutation and returns the new graph.
Method personalized_pagerank Calculates the personalized PageRank values of a graph.
Method predecessors Returns the predecessors of a given vertex.
Method Preference Generates a graph based on vertex types and connection probabilities.
Method radius Calculates the radius of the graph.
Method random_walk Performs a random walk of a given length from a given node.
Method Read_DIMACS Reads a graph from a file conforming to the DIMACS minimum-cost flow file format.
Method Read_DL Reads an UCINET DL file and creates a graph based on it.
Method Read_Edgelist Reads an edge list from a file and creates a graph based on it.
Method Read_GML Reads a GML file and creates a graph based on it.
Method Read_GraphDB Reads a GraphDB format file and creates a graph based on it.
Method Read_GraphML Reads a GraphML format file and creates a graph based on it.
Method Read_Lgl Reads an .lgl file used by LGL.
Method Read_Ncol Reads an .ncol file used by LGL.
Method Read_Pajek Reads a Pajek format file and creates a graph based on it.
Method Realize_Degree_Sequence Generates a graph from a degree sequence.
Method Recent_Degree Generates a graph based on a stochastic model where the probability of an edge gaining a new node is proportional to the edges gained in a given time window.
Method reciprocity Reciprocity defines the proportion of mutual connections in a directed graph. It is most commonly defined as the probability that the opposite counterpart of a directed edge is also included in the graph...
Method rewire Randomly rewires the graph while preserving the degree distribution.
Method rewire_edges Rewires the edges of a graph with constant probability.
Method Ring Generates a ring graph.
Method SBM Generates a graph based on a stochastic blockmodel.
Method shortest_paths Calculates shortest path lengths for given vertices in a graph.
Method similarity_dice Dice similarity coefficient of vertices.
Method similarity_inverse_log_weighted Inverse log-weighted similarity coefficient of vertices.
Method similarity_jaccard Jaccard similarity coefficient of vertices.
Method simplify Simplifies a graph by removing self-loops and/or multiple edges.
Method st_mincut Calculates the minimum cut between the source and target vertices in a graph.
Method Star Generates a star graph.
Method Static_Fitness Generates a non-growing graph with edge probabilities proportional to node fitnesses.
Method Static_Power_Law Generates a non-growing graph with prescribed power-law degree distributions.
Method strength Returns the strength (weighted degree) of some vertices from the graph
Method subcomponent Determines the indices of vertices which are in the same component as a given vertex.
Method subgraph_edges Returns a subgraph spanned by the given edges.
Method subisomorphic_lad Checks whether a subgraph of the graph is isomorphic to another graph.
Method subisomorphic_vf2 Checks whether a subgraph of the graph is isomorphic to another graph.
Method successors Returns the successors of a given vertex.
Method to_directed Converts an undirected graph to directed.
Method to_prufer Converts a tree graph into a Prufer sequence.
Method to_undirected Converts a directed graph to undirected.
Method topological_sorting Calculates a possible topological sorting of the graph.
Method transitivity_avglocal_undirected Calculates the average of the vertex transitivities of the graph.
Method transitivity_local_undirected Calculates the local transitivity (clustering coefficient) of the given vertices in the graph.
Method transitivity_undirected Calculates the global transitivity (clustering coefficient) of the graph.
Method Tree Generates a tree in which almost all vertices have the same number of children.
Method Tree_Game Generates a random tree by sampling uniformly from the set of labelled trees with a given number of nodes.
Method triad_census Triad census, as defined by Davis and Leinhardt
Method unfold_tree Unfolds the graph using a BFS to a tree by duplicating vertices as necessary.
Method vcount Counts the number of vertices.
Method vertex_attributes No summary
Method vertex_connectivity Calculates the vertex connectivity of the graph or between some vertices.
Method Watts_Strogatz No summary
Method Weighted_Adjacency Generates a graph from its adjacency matrix.
Method write_dimacs Writes the graph in DIMACS format to the given file.
Method write_dot Writes the graph in DOT format to the given file.
Method write_edgelist Writes the edge list of a graph to a file.
Method write_gml Writes the graph in GML format to the given file.
Method write_graphml Writes the graph to a GraphML file.
Method write_leda Writes the graph to a file in LEDA native format.
Method write_lgl Writes the edge list of a graph to a file in .lgl format.
Method write_ncol Writes the edge list of a graph to a file in .ncol format.
Method write_pajek Writes the graph in Pajek format to the given file.
Method __graph_as_capsule __graph_as_capsule()
Method __register_destructor Registers a destructor to be called when the object is freed by Python. This function should not be used directly by igraph users.
Method _Bipartite Internal function, undocumented.
Method _Full_Bipartite Internal function, undocumented.
Method _get_all_simple_paths Internal function, undocumented.
Method _GRG Internal function, undocumented.
Method _Incidence Internal function, undocumented.
Method _is_matching Internal function, undocumented.
Method _is_maximal_matching Internal function, undocumented.
Method _layout_sugiyama Internal function, undocumented.
Method _maximum_bipartite_matching Internal function, undocumented.
Method _Random_Bipartite Internal function, undocumented.
Method _raw_pointer Returns the memory address of the igraph graph encapsulated by the Python object as an ordinary Python integer.
Method _spanning_tree Internal function, undocumented.
def __new__(*args, **kwargs):

Create and return a new object. See help(type) for accurate signature.

def add_edges(es):
overridden in igraph.Graph

Adds edges to the graph.

Parameters
esthe list of edges to be added. Every edge is represented with a tuple, containing the vertex IDs of the two endpoints. Vertices are enumerated from zero.
def add_vertices(n):
overridden in igraph.Graph

Adds vertices to the graph.

Parameters
nthe number of vertices to be added
def Adjacency(matrix, mode='directed'):
overridden in igraph.Graph

Generates a graph from its adjacency matrix.

Parameters
matrixthe adjacency matrix
mode

the mode to be used. Possible values are:

  • "directed" - the graph will be directed and a matrix element gives the number of edges between two vertices.
  • "undirected" - alias to "max" for convenience.
  • "max" - undirected graph will be created and the number of edges between vertex i and j is max(A(i, j), A(j, i))
  • "min" - like "max", but with min(A(i, j), A(j, i))
  • "plus" - like "max", but with A(i, j) + A(j, i)
  • "upper" - undirected graph with the upper right triangle of the matrix (including the diagonal)
  • "lower" - undirected graph with the lower left triangle of the matrix (including the diagonal)
def all_minimal_st_separators():

Returns a list containing all the minimal s-t separators of a graph.

A minimal separator is a set of vertices whose removal disconnects the graph, while the removal of any subset of the set keeps the graph connected.

Returns
a list where each item lists the vertex indices of a given minimal s-t separator.
Unknown Field: newfield
refReference
Unknown Field: ref
Anne Berry, Jean-Paul Bordat and Olivier Cogis: Generating all the minimal separators of a graph. In: Peter Widmayer, Gabriele Neyer and Stephan Eidenbenz (eds.): Graph-theoretic concepts in computer science, 1665, 167--172, 1999. Springer.
def all_st_cuts(source, target):
overridden in igraph.Graph

Returns all the cuts between the source and target vertices in a directed graph.

This function lists all edge-cuts between a source and a target vertex. Every cut is listed exactly once.

Parameters
sourcethe source vertex ID
targetthe target vertex ID
Returns
a tuple where the first element is a list of lists of edge IDs representing a cut and the second element is a list of lists of vertex IDs representing the sets of vertices that were separated by the cuts.
Unknown Field: attention
this function has a more convenient interface in class Graph which wraps the result in a list of Cut objects. It is advised to use that.
def all_st_mincuts(source, target):
overridden in igraph.Graph

Returns all minimum cuts between the source and target vertices in a directed graph.

Parameters
sourcethe source vertex ID
targetthe target vertex ID
Unknown Field: attention
this function has a more convenient interface in class Graph which wraps the result in a list of Cut objects. It is advised to use that.
def are_connected(v1, v2):

Decides whether two given vertices are directly connected.

Parameters
v1the ID or name of the first vertex
v2the ID or name of the second vertex
Returns
True if there exists an edge from v1 to v2, False otherwise.
def articulation_points():

Returns the list of articulation points in the graph.

A vertex is an articulation point if its removal increases the number of connected components in the graph.

def assortativity(types1, types2=None, directed=True):

Returns the assortativity of the graph based on numeric properties of the vertices.

This coefficient is basically the correlation between the actual connectivity patterns of the vertices and the pattern expected from the disribution of the vertex types.

See equation (21) in Newman MEJ: Mixing patterns in networks, Phys Rev E 67:026126 (2003) for the proper definition. The actual calculation is performed using equation (26) in the same paper for directed graphs, and equation (4) in Newman MEJ: Assortative mixing in networks, Phys Rev Lett 89:208701 (2002) for undirected graphs.

Parameters
types1vertex types in a list or the name of a vertex attribute holding vertex types. Types are ideally denoted by numeric values.
types2in directed assortativity calculations, each vertex can have an out-type and an in-type. In this case, types1 contains the out-types and this parameter contains the in-types in a list or the name of a vertex attribute. If None, it is assumed to be equal to types1.
directedwhether to consider edge directions or not.
Returns
the assortativity coefficient
See Also
assortativity_degree() when the types are the vertex degrees
Unknown Field: newfield
refReference
Unknown Field: ref
Newman MEJ: Mixing patterns in networks, Phys Rev E 67:026126, 2003.

Newman MEJ: Assortative mixing in networks, Phys Rev Lett 89:208701,

def assortativity_degree(directed=True):

Returns the assortativity of a graph based on vertex degrees.

See assortativity() for the details. assortativity_degree() simply calls assortativity() with the vertex degrees as types.

Parameters
directedwhether to consider edge directions for directed graphs or not. This argument is ignored for undirected graphs.
Returns
the assortativity coefficient
See Also
assortativity()
def assortativity_nominal(types, directed=True):

Returns the assortativity of the graph based on vertex categories.

Assuming that the vertices belong to different categories, this function calculates the assortativity coefficient, which specifies the extent to which the connections stay within categories. The assortativity coefficient is one if all the connections stay within categories and minus one if all the connections join vertices of different categories. For a randomly connected network, it is asymptotically zero.

See equation (2) in Newman MEJ: Mixing patterns in networks, Phys Rev E 67:026126 (2003) for the proper definition.

Parameters
typesvertex types in a list or the name of a vertex attribute holding vertex types. Types should be denoted by numeric values.
directedwhether to consider edge directions or not.
Returns
the assortativity coefficient
Unknown Field: newfield
refReference
Unknown Field: ref
Newman MEJ: Mixing patterns in networks, Phys Rev E 67:026126, 2003.
def Asymmetric_Preference(n, type_dist_matrix, pref_matrix, attribute=None, loops=False):

Generates a graph based on asymmetric vertex types and connection probabilities.

This is the asymmetric variant of Preference(). A given number of vertices are generated. Every vertex is assigned to an "incoming" and an "outgoing" vertex type according to the given joint type probabilities. Finally, every vertex pair is evaluated and a directed edge is created between them with a probability depending on the "outgoing" type of the source vertex and the "incoming" type of the target vertex.

Parameters
nthe number of vertices in the graph
type_dist_matrixmatrix giving the joint distribution of vertex types
pref_matrixmatrix giving the connection probabilities for different vertex types.
attributethe vertex attribute name used to store the vertex types. If None, vertex types are not stored.
loopswhether loop edges are allowed.
def Atlas(idx):

Generates a graph from the Graph Atlas.

Parameters
idx

The index of the graph to be generated. Indices start from zero, graphs are listed:

  1. in increasing order of number of vertices;
  2. for a fixed number of vertices, in increasing order of the number of edges;
  3. for fixed numbers of vertices and edges, in increasing order of the degree sequence, for example 111223 < 112222;
  4. for fixed degree sequence, in increasing number of automorphisms.
Unknown Field: newfield
refReference
Unknown Field: ref
An Atlas of Graphs by Ronald C. Read and Robin J. Wilson, Oxford University Press, 1998.
def attributes():
Returns
the attribute name list of the graph
def authority_score(weights=None, scale=True, arpack_options=None, return_eigenvalue=False):

Calculates Kleinberg's authority score for the vertices of the graph

Parameters
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
scalewhether to normalize the scores so that the largest one is 1.
arpack_optionsan ARPACKOptions object used to fine-tune the ARPACK eigenvector calculation. If omitted, the module-level variable called arpack_options is used.
return_eigenvaluewhether to return the largest eigenvalue
Returns
the authority scores in a list and optionally the largest eigenvalue as a second member of a tuple
See Also
hub_score()
def average_path_length(directed=True, unconn=True):

Calculates the average path length in a graph.

Parameters
directedwhether to consider directed paths in case of a directed graph. Ignored for undirected graphs.
unconnwhat to do when the graph is unconnected. If True, the average of the geodesic lengths in the components is calculated. Otherwise for all unconnected vertex pairs, a path length equal to the number of vertices is used.
Returns
the average path length in the graph
def Barabasi(n, m, outpref=False, directed=False, power=1, zero_appeal=1, implementation='psumtree', start_from=None):

Generates a graph based on the Barabasi-Albert model.

Parameters
nthe number of vertices
meither the number of outgoing edges generated for each vertex or a list containing the number of outgoing edges for each vertex explicitly.
outprefTrue if the out-degree of a given vertex should also increase its citation probability (as well as its in-degree), but it defaults to False.
directedTrue if the generated graph should be directed (default: False).
powerthe power constant of the nonlinear model. It can be omitted, and in this case the usual linear model will be used.
zero_appealthe attractivity of vertices with degree zero.
implementation

the algorithm to use to generate the network. Possible values are:

  • "bag": the algorithm that was the default in igraph before 0.6. It works by putting the ids of the vertices into a bag (multiset) exactly as many times as their in-degree, plus once more. The required number of cited vertices are then drawn from the bag with replacement. It works only for power=1 and zero_appeal=1.
  • "psumtree": this algorithm uses a partial prefix-sum tree to generate the graph. It does not generate multiple edges and it works for any values of power and zero_appeal.
  • "psumtree_multiple": similar to "psumtree", but it will generate multiple edges as well. igraph before 0.6 used this algorithm for powers other than 1.
start_fromif given and not None, this must be another GraphBase object. igraph will use this graph as a starting point for the preferential attachment model.
Unknown Field: newfield
refReference
Unknown Field: ref
Barabasi, A-L and Albert, R. 1999. Emergence of scaling in random networks. Science, 286 509-512.
def betweenness(vertices=None, directed=True, cutoff=None, weights=None):

Calculates or estimates the betweenness of vertices in a graph.

Keyword arguments:

Parameters
verticesthe vertices for which the betweennesses must be returned. If None, assumes all of the vertices in the graph.
directedwhether to consider directed paths.
cutoffif it is an integer, only paths less than or equal to this length are considered, effectively resulting in an estimation of the betweenness for the given vertices. If None, the exact betweenness is returned.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
Returns
the (possibly estimated) betweenness of the given vertices in a list
def bfs(vid, mode='out'):

Conducts a breadth first search (BFS) on the graph.

Parameters
vidthe root vertex ID
modeeither "in" or "out" or "all", ignored for undirected graphs.
Returns

a tuple with the following items:

  • The vertex IDs visited (in order)
  • The start indices of the layers in the vertex list
  • The parent of every vertex in the BFS
def bfsiter(vid, mode='out', advanced=False):

Constructs a breadth first search (BFS) iterator of the graph.

Parameters
vidthe root vertex ID
modeeither "in" or "out" or "all".
advancedif False, the iterator returns the next vertex in BFS order in every step. If True, the iterator returns the distance of the vertex from the root and the parent of the vertex in the BFS tree as well.
Returns
the BFS iterator as an igraph.BFSIter object.
def bibcoupling(vertices=None):

Calculates bibliographic coupling scores for given vertices in a graph.

Parameters
verticesthe vertices to be analysed. If None, all vertices will be considered.
Returns
bibliographic coupling scores for all given vertices in a matrix.
def biconnected_components(return_articulation_points=True):
overridden in igraph.Graph

Calculates the biconnected components of the graph.

Components containing a single vertex only are not considered as being biconnected.

Parameters
return_articulation_pointswhether to return the articulation points as well
Returns
a list of lists containing edge indices making up spanning trees of the biconnected components (one spanning tree for each component) and optionally the list of articulation points
def bipartite_projection(types, multiplicity=True, probe1=-1, which=-1):
overridden in igraph.Graph

Internal function, undocumented.

See Also
Graph.bipartite_projection()
def bipartite_projection_size(types):
overridden in igraph.Graph

Internal function, undocumented.

See Also
Graph.bipartite_projection_size()
def bridges():

Returns the list of bridges in the graph.

An edge is a bridge if its removal increases the number of (weakly) connected components in the graph.

def canonical_permutation(sh='fl', color=None):

Calculates the canonical permutation of a graph using the BLISS isomorphism algorithm.

Passing the permutation returned here to permute_vertices() will transform the graph into its canonical form.

See http://www.tcs.hut.fi/Software/bliss/index.html for more information about the BLISS algorithm and canonical permutations.

Parameters
sh

splitting heuristics for graph as a case-insensitive string, with the following possible values:

  • "f": first non-singleton cell
  • "fl": first largest non-singleton cell
  • "fs": first smallest non-singleton cell
  • "fm": first maximally non-trivially connected non-singleton cell
  • "flm": largest maximally non-trivially connected non-singleton cell
  • "fsm": smallest maximally non-trivially connected non-singleton cell
coloroptional vector storing a coloring of the vertices with respect to which the isomorphism is computed.If None, all vertices have the same color.
Returns
a permutation vector containing vertex IDs. Vertex 0 in the original graph will be mapped to an ID contained in the first element of this vector; vertex 1 will be mapped to the second and so on.
def chordal_completion(...):

chordal_complation(alpha=None, alpham1=None) --

Returns the list of edges needed to be added to the graph to make it chordal.

A graph is chordal if each of its cycles of four or more nodes has a chord, i.e. an edge joining two nodes that are not adjacent in the cycle. An equivalent definition is that any chordless cycles have at most three nodes.

The chordal completion of a graph is the list of edges that needed to be added to the graph to make it chordal. It is an empty list if the graph is already chordal.

Note that at the moment igraph does not guarantee that the returned chordal completion is minimal; there may exist a subset of the returned chordal completion that is still a valid chordal completion.

Parameters
alphathe alpha vector from the result of calling maximum_cardinality_search() on the graph. Useful only if you already have the alpha vector; simply passing None here will make igraph calculate the alpha vector on its own.
alpham1the inverse alpha vector from the result of calling maximum_cardinality_search() on the graph. Useful only if you already have the inverse alpha vector; simply passing None here will make igraph calculate the inverse alpha vector on its own.
Returns
the list of edges to add to the graph; each item in the list is a source-target pair of vertex indices.
def clique_number():

Returns the clique number of the graph.

The clique number of the graph is the size of the largest clique.

See Also
largest_cliques() for the largest cliques.
def cliques(min=0, max=0):

Returns some or all cliques of the graph as a list of tuples.

A clique is a complete subgraph -- a set of vertices where an edge is present between any two of them (excluding loops)

Parameters
minthe minimum size of cliques to be returned. If zero or negative, no lower bound will be used.
maxthe maximum size of cliques to be returned. If zero or negative, no upper bound will be used.
def closeness(vertices=None, mode='all', cutoff=None, weights=None, normalized=True):

Calculates the closeness centralities of given vertices in a graph.

The closeness centerality of a vertex measures how easily other vertices can be reached from it (or the other way: how easily it can be reached from the other vertices). It is defined as the number of vertices minus one divided by the sum of the lengths of all geodesics from/to the given vertex.

If the graph is not connected, and there is no path between two vertices, the number of vertices is used instead the length of the geodesic. This is always longer than the longest possible geodesic.

Parameters
verticesthe vertices for which the closenesses must be returned. If None, uses all of the vertices in the graph.
modemust be one of "in", "out" and "all". "in" means that the length of the incoming paths, "out" means that the length of the outgoing paths must be calculated. "all" means that both of them must be calculated.
cutoffif it is an integer, only paths less than or equal to this length are considered, effectively resulting in an estimation of the closeness for the given vertices (which is always an underestimation of the real closeness, since some vertex pairs will appear as disconnected even though they are connected).. If None, the exact closeness is returned.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
normalizedWhether to normalize the raw closeness scores by multiplying by the number of vertices minus one.
Returns
the calculated closenesses in a list
def clusters(mode='strong'):
overridden in igraph.Graph

Calculates the (strong or weak) clusters for a given graph.

Parameters
modemust be either "strong" or "weak", depending on the clusters being sought. Optional, defaults to "strong".
Returns
the component index for every node in the graph.
Unknown Field: attention
this function has a more convenient interface in class Graph which wraps the result in a VertexClustering object. It is advised to use that.
def cocitation(vertices=None):

Calculates cocitation scores for given vertices in a graph.

Parameters
verticesthe vertices to be analysed. If None, all vertices will be considered.
Returns
cocitation scores for all given vertices in a matrix.
def cohesive_blocks():
overridden in igraph.Graph

Calculates the cohesive block structure of the graph.

Unknown Field: attention
this function has a more convenient interface in class Graph which wraps the result in a CohesiveBlocks object. It is advised to use that.
def community_edge_betweenness(directed=True, weights=None):
overridden in igraph.Graph

Community structure detection based on the betweenness of the edges in the network. This algorithm was invented by M Girvan and MEJ Newman, see: M Girvan and MEJ Newman: Community structure in social and biological networks, Proc. Nat. Acad. Sci. USA 99, 7821-7826 (2002).

The idea is that the betweenness of the edges connecting two communities is typically high. So we gradually remove the edge with the highest betweenness from the network and recalculate edge betweenness after every removal, as long as all edges are removed.

Parameters
directedwhether to take into account the directedness of the edges when we calculate the betweenness values.
weightsname of an edge attribute or a list containing edge weights.
Returns
a tuple with the merge matrix that describes the dendrogram and the modularity scores before each merge. The modularity scores use the weights if the original graph was weighted.
Unknown Field: attention
this function is wrapped in a more convenient syntax in the derived class Graph. It is advised to use that instead of this version.
def community_fastgreedy(weights=None):
overridden in igraph.Graph

Finds the community structure of the graph according to the algorithm of Clauset et al based on the greedy optimization of modularity.

This is a bottom-up algorithm: initially every vertex belongs to a separate community, and communities are merged one by one. In every step, the two communities being merged are the ones which result in the maximal increase in modularity.

Parameters
weightsname of an edge attribute or a list containing edge weights
Returns

a tuple with the following elements:

  1. The list of merges
  2. The modularity scores before each merge
See Also
modularity()
Unknown Field: attention
this function is wrapped in a more convenient syntax in the derived class Graph. It is advised to use that instead of this version.
Unknown Field: newfield
refReference
Unknown Field: ref
A. Clauset, M. E. J. Newman and C. Moore: Finding community structure in very large networks. Phys Rev E 70, 066111 (2004).
def community_infomap(edge_weights=None, vertex_weights=None, trials=10):
overridden in igraph.Graph

Finds the community structure of the network according to the Infomap method of Martin Rosvall and Carl T. Bergstrom.

See http://www.mapequation.org for a visualization of the algorithm or one of the references provided below.

Parameters
edge_weightsname of an edge attribute or a list containing edge weights.
vertex_weightsname of an vertex attribute or a list containing vertex weights.
trialsthe number of attempts to partition the network.
Returns
the calculated membership vector and the corresponding codelength in a tuple.
Unknown Field: newfield
refReference
Unknown Field: ref
M. Rosvall and C. T. Bergstrom: Maps of information flow reveal community structure in complex networks. PNAS 105, 1118 (2008). http://arxiv.org/abs/0707.0609
M. Rosvall, D. Axelsson and C. T. Bergstrom: The map equation. Eur Phys J Special Topics 178, 13 (2009). http://arxiv.org/abs/0906.1405
def community_label_propagation(weights=None, initial=None, fixed=None):
overridden in igraph.Graph

Finds the community structure of the graph according to the label propagation method of Raghavan et al.

Initially, each vertex is assigned a different label. After that, each vertex chooses the dominant label in its neighbourhood in each iteration. Ties are broken randomly and the order in which the vertices are updated is randomized before every iteration. The algorithm ends when vertices reach a consensus.

Note that since ties are broken randomly, there is no guarantee that the algorithm returns the same community structure after each run. In fact, they frequently differ. See the paper of Raghavan et al on how to come up with an aggregated community structure.

Parameters
weightsname of an edge attribute or a list containing edge weights
initialname of a vertex attribute or a list containing the initial vertex labels. Labels are identified by integers from zero to n − 1 where n is the number of vertices. Negative numbers may also be present in this vector, they represent unlabeled vertices.
fixeda list of booleans for each vertex. True corresponds to vertices whose labeling should not change during the algorithm. It only makes sense if initial labels are also given. Unlabeled vertices cannot be fixed. Note that vertex attribute names are not accepted here.
Returns
the resulting membership vector
Unknown Field: newfield
refReference
Unknown Field: ref
Raghavan, U.N. and Albert, R. and Kumara, S. Near linear time algorithm to detect community structures in large-scale networks. Phys Rev E 76:036106, 2007. http://arxiv.org/abs/0709.2938.
def community_leading_eigenvector(n=-1, arpack_options=None, weights=None):
overridden in igraph.Graph

A proper implementation of Newman's eigenvector community structure detection. Each split is done by maximizing the modularity regarding the original network. See the reference for details.

Parameters
nthe desired number of communities. If negative, the algorithm tries to do as many splits as possible. Note that the algorithm won't split a community further if the signs of the leading eigenvector are all the same.
arpack_optionsan ARPACKOptions object used to fine-tune the ARPACK eigenvector calculation. If omitted, the module-level variable called arpack_options is used.
weightsname of an edge attribute or a list containing edge weights
Returns
a tuple where the first element is the membership vector of the clustering and the second element is the merge matrix.
Unknown Field: attention
this function is wrapped in a more convenient syntax in the derived class Graph. It is advised to use that instead of this version.
Unknown Field: newfield
refReference
Unknown Field: ref
MEJ Newman: Finding community structure in networks using the eigenvectors of matrices, arXiv:physics/0605087
def community_leiden(edge_weights=None, node_weights=None, resolution_parameter=1.0, normalize_resolution=False, beta=0.01, initial_membership=None, n_iterations=2):
overridden in igraph.Graph

Finds the community structure of the graph using the Leiden algorithm of Traag, van Eck & Waltman.

Parameters
edge_weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
node_weightsthe node weights used in the Leiden algorithm.
resolution_parameterthe resolution parameter to use. Higher resolutions lead to more smaller communities, while lower resolutions lead to fewer larger communities.
normalize_resolutionif set to true, the resolution parameter will be divided by the sum of the node weights. If this is not supplied, it will default to the node degree, or weighted degree in case edge_weights are supplied.
betaparameter affecting the randomness in the Leiden algorithm. This affects only the refinement step of the algorithm.
initial_membershipif provided, the Leiden algorithm will try to improve this provided membership. If no argument is provided, the aglorithm simply starts from the singleton partition.
n_iterationsthe number of iterations to iterate the Leiden algorithm. Each iteration may improve the partition further.
Returns
the community membership vector.
def community_multilevel(weights=None, return_levels=True, resolution=1):
overridden in igraph.Graph

Finds the community structure of the graph according to the multilevel algorithm of Blondel et al. This is a bottom-up algorithm: initially every vertex belongs to a separate community, and vertices are moved between communities iteratively in a way that maximizes the vertices' local contribution to the overall modularity score. When a consensus is reached (i.e. no single move would increase the modularity score), every community in the original graph is shrank to a single vertex (while keeping the total weight of the incident edges) and the process continues on the next level. The algorithm stops when it is not possible to increase the modularity any more after shrinking the communities to vertices.

Parameters
weightsname of an edge attribute or a list containing edge weights
return_levelsif True, returns the multilevel result. If False, only the best level (corresponding to the best modularity) is returned.
resolutionthe resolution parameter to use in the modularity measure. Smaller values result in a smaller number of larger clusters, while higher values yield a large number of small clusters. The classical modularity measure assumes a resolution parameter of 1.
Returns
either a single list describing the community membership of each vertex (if return_levels is False), or a list of community membership vectors, one corresponding to each level and a list of corresponding modularities (if return_levels is True).
See Also
modularity()
Unknown Field: attention
this function is wrapped in a more convenient syntax in the derived class Graph. It is advised to use that instead of this version.
Unknown Field: newfield
refReference
Unknown Field: ref
VD Blondel, J-L Guillaume, R Lambiotte and E Lefebvre: Fast unfolding of community hierarchies in large networks. J Stat Mech P10008 (2008), http://arxiv.org/abs/0803.0476
def community_optimal_modularity(weights=None):
overridden in igraph.Graph

Calculates the optimal modularity score of the graph and the corresponding community structure.

This function uses the GNU Linear Programming Kit to solve a large integer optimization problem in order to find the optimal modularity score and the corresponding community structure, therefore it is unlikely to work for graphs larger than a few (less than a hundred) vertices. Consider using one of the heuristic approaches instead if you have such a large graph.

Parameters
weightsname of an edge attribute or a list containing edge weights.
Returns
the calculated membership vector and the corresponding modularity in a tuple.
def community_spinglass(weights=None, spins=25, parupdate=False, start_temp=1, stop_temp=0.01, cool_fact=0.99, update_rule='config', gamma=1, implementation='orig', lambda_=1):
overridden in igraph.Graph

Finds the community structure of the graph according to the spinglass community detection method of Reichardt & Bornholdt.

Parameters
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
spinsinteger, the number of spins to use. This is the upper limit for the number of communities. It is not a problem to supply a (reasonably) big number here, in which case some spin states will be unpopulated.
parupdatewhether to update the spins of the vertices in parallel (synchronously) or not
start_tempthe starting temperature
stop_tempthe stop temperature
cool_factcooling factor for the simulated annealing
update_rulespecifies the null model of the simulation. Possible values are "config" (a random graph with the same vertex degrees as the input graph) or "simple" (a random graph with the same number of edges)
gammathe gamma argument of the algorithm, specifying the balance between the importance of present and missing edges within a community. The default value of 1.0 assigns equal importance to both of them.
implementationcurrently igraph contains two implementations for the spinglass community detection algorithm. The faster original implementation is the default. The other implementation is able to take into account negative weights, this can be chosen by setting implementation to "neg".
lambda_the lambda argument of the algorithm, which specifies the balance between the importance of present and missing negatively weighted edges within a community. Smaller values of lambda lead to communities with less negative intra-connectivity. If the argument is zero, the algorithm reduces to a graph coloring algorithm, using the number of spins as colors. This argument is ignored if the original implementation is used.
Returns
the community membership vector.
def community_walktrap(weights=None, steps=None):
overridden in igraph.Graph

Finds the community structure of the graph according to the random walk method of Latapy & Pons.

The basic idea of the algorithm is that short random walks tend to stay in the same community. The method provides a dendrogram.

Parameters
weightsname of an edge attribute or a list containing edge weights
stepsUndocumented
Returns
a tuple with the list of merges and the modularity scores corresponding to each merge
See Also
modularity()
Unknown Field: attention
this function is wrapped in a more convenient syntax in the derived class Graph. It is advised to use that instead of this version.
Unknown Field: newfield
refReference
Unknown Field: ref
Pascal Pons, Matthieu Latapy: Computing communities in large networks using random walks, http://arxiv.org/abs/physics/0512106.
def complementer(loops=False):

Returns the complementer of the graph

Parameters
loopswhether to include loop edges in the complementer.
Returns
the complementer of the graph
def compose(other):

Returns the composition of two graphs.

def constraint(vertices=None, weights=None):

Calculates Burt's constraint scores for given vertices in a graph.

Burt's constraint is higher if ego has less, or mutually stronger related (i.e. more redundant) contacts. Burt's measure of constraint, C[i], of vertex i's ego network V[i], is defined for directed and valued graphs as follows:

C[i] = sum( sum( (p[i,q] p[q,j])^2, q in V[i], q != i,j ), j in V[], j != i)

for a graph of order (ie. number od vertices) N, where proportional tie strengths are defined as follows:

p[i,j]=(a[i,j]+a[j,i]) / sum(a[i,k]+a[k,i], k in V[i], k != i), a[i,j] are elements of A and the latter being the graph adjacency matrix.

For isolated vertices, constraint is undefined.

Parameters
verticesthe vertices to be analysed or None for all vertices.
weightsweights associated to the edges. Can be an attribute name as well. If None, every edge will have the same weight.
Returns
constraint scores for all given vertices in a matrix.
def contract_vertices(mapping, combine_attrs=None):

Contracts some vertices in the graph, i.e. replaces groups of vertices with single vertices. Edges are not affected.

Parameters
mappingnumeric vector which gives the mapping between old and new vertex IDs. Vertices having the same new vertex ID in this vector will be remapped into a single new vertex. It is safe to pass the membership vector of a VertexClustering object here.
combine_attrsspecifies how to combine the attributes of the vertices being collapsed into a single one. If it is None, all the attributes will be lost. If it is a function, the attributes of the vertices will be collected and passed on to that function which will return the new attribute value that has to be assigned to the single collapsed vertex. It can also be one of the following string constants which define built-in collapsing functions: sum, prod, mean, median, max, min, first, last, random. You can also specify different combination functions for different attributes by passing a dict here which maps attribute names to functions. See simplify() for more details.
Returns
None.
See Also
simplify()
def convergence_degree():

Undocumented (yet).

def convergence_field_size():

Undocumented (yet).

def copy():

Creates a copy of the graph.

Attributes are copied by reference; in other words, if you use mutable Python objects as attribute values, these objects will still be shared between the old and new graph. You can use `deepcopy()` from the `copy` module if you need a truly deep copy of the graph.

def coreness(mode='all'):

Finds the coreness (shell index) of the vertices of the network.

The k-core of a graph is a maximal subgraph in which each vertex has at least degree k. (Degree here means the degree in the subgraph of course). The coreness of a vertex is k if it is a member of the k-core but not a member of the k + 1-core.

Parameters
modewhether to compute the in-corenesses ("in"), the out-corenesses ("out") or the undirected corenesses ("all"). Ignored and assumed to be "all" for undirected graphs.
Returns
the corenesses for each vertex.
Unknown Field: newfield
refReference
Unknown Field: ref
Vladimir Batagelj, Matjaz Zaversnik: An O(m) Algorithm for Core Decomposition of Networks.
def count_isomorphisms_vf2(other=None, color1=None, color2=None, edge_color1=None, edge_color2=None, node_compat_fn=None, edge_compat_fn=None):

Determines the number of isomorphisms between the graph and another one

Vertex and edge colors may be used to restrict the isomorphisms, as only vertices and edges with the same color will be allowed to match each other.

Parameters
otherthe other graph. If None, the number of automorphisms will be returned.
color1optional vector storing the coloring of the vertices of the first graph. If None, all vertices have the same color.
color2optional vector storing the coloring of the vertices of the second graph. If None, all vertices have the same color.
edge_color1optional vector storing the coloring of the edges of the first graph. If None, all edges have the same color.
edge_color2optional vector storing the coloring of the edges of the second graph. If None, all edges have the same color.
node_compat_fna function that receives the two graphs and two node indices (one from the first graph, one from the second graph) and returns True if the nodes given by the two indices are compatible (i.e. they could be matched to each other) or False otherwise. This can be used to restrict the set of isomorphisms based on node-specific criteria that are too complicated to be represented by node color vectors (i.e. the color1 and color2 parameters). None means that every node is compatible with every other node.
edge_compat_fna function that receives the two graphs and two edge indices (one from the first graph, one from the second graph) and returns True if the edges given by the two indices are compatible (i.e. they could be matched to each other) or False otherwise. This can be used to restrict the set of isomorphisms based on edge-specific criteria that are too complicated to be represented by edge color vectors (i.e. the edge_color1 and edge_color2 parameters). None means that every edge is compatible with every other node.
Returns
the number of isomorphisms between the two given graphs (or the number of automorphisms if other is None.
def count_multiple(edges=None):

Counts the multiplicities of the given edges.

Parameters
edgesedge indices for which we want to count their multiplicity. If None, all edges are counted.
Returns
the multiplicities of the given edges as a list.
def count_subisomorphisms_vf2(other, color1=None, color2=None, edge_color1=None, edge_color2=None, node_compat_fn=None, edge_compat_fn=None):

Determines the number of subisomorphisms between the graph and another one

Vertex and edge colors may be used to restrict the isomorphisms, as only vertices and edges with the same color will be allowed to match each other.

Parameters
otherthe other graph.
color1optional vector storing the coloring of the vertices of the first graph. If None, all vertices have the same color.
color2optional vector storing the coloring of the vertices of the second graph. If None, all vertices have the same color.
edge_color1optional vector storing the coloring of the edges of the first graph. If None, all edges have the same color.
edge_color2optional vector storing the coloring of the edges of the second graph. If None, all edges have the same color.
node_compat_fna function that receives the two graphs and two node indices (one from the first graph, one from the second graph) and returns True if the nodes given by the two indices are compatible (i.e. they could be matched to each other) or False otherwise. This can be used to restrict the set of isomorphisms based on node-specific criteria that are too complicated to be represented by node color vectors (i.e. the color1 and color2 parameters). None means that every node is compatible with every other node.
edge_compat_fna function that receives the two graphs and two edge indices (one from the first graph, one from the second graph) and returns True if the edges given by the two indices are compatible (i.e. they could be matched to each other) or False otherwise. This can be used to restrict the set of isomorphisms based on edge-specific criteria that are too complicated to be represented by edge color vectors (i.e. the edge_color1 and edge_color2 parameters). None means that every edge is compatible with every other node.
Returns
the number of subisomorphisms between the two given graphs
def De_Bruijn(m, n):

Generates a de Bruijn graph with parameters (m, n)

A de Bruijn graph represents relationships between strings. An alphabet of m letters are used and strings of length n are considered. A vertex corresponds to every possible string and there is a directed edge from vertex v to vertex w if the string of v can be transformed into the string of w by removing its first letter and appending a letter to it.

Please note that the graph will have mn vertices and even more edges, so probably you don't want to supply too big numbers for m and n.

Parameters
mthe size of the alphabet
nthe length of the strings
def decompose(mode='strong', maxcompno=None, minelements=1):

Decomposes the graph into subgraphs.

Parameters
modemust be either "strong" or "weak", depending on the clusters being sought. Optional, defaults to "strong".
maxcompnomaximum number of components to return. None means all possible components.
minelementsminimum number of vertices in a component. By setting this to 2, isolated vertices are not returned as separate components.
Returns
a list of the subgraphs. Every returned subgraph is a copy of the original.
def degree(vertices, mode='all', loops=True):

Returns some vertex degrees from the graph.

This method accepts a single vertex ID or a list of vertex IDs as a parameter, and returns the degree of the given vertices (in the form of a single integer or a list, depending on the input parameter).

Parameters
verticesa single vertex ID or a list of vertex IDs
modethe type of degree to be returned ("out" for out-degrees, "in" for in-degrees or "all" for the sum of them).
loopswhether self-loops should be counted.
def Degree_Sequence(out, in_=None, method='simple'):

Generates a graph with a given degree sequence.

Parameters
outthe out-degree sequence for a directed graph. If the in-degree sequence is omitted, the generated graph will be undirected, so this will be the in-degree sequence as well
in_the in-degree sequence for a directed graph. If omitted, the generated graph will be undirected.
method

the generation method to be used. One of the following:

  • "simple" -- simple generator that sometimes generates loop edges and multiple edges. The generated graph is not guaranteed to be connected.
  • "no_multiple" -- similar to "simple" but avoids the generation of multiple and loop edges at the expense of increased time complexity. The method will re-start the generation every time it gets stuck in a configuration where it is not possible to insert any more edges without creating loops or multiple edges, and there is no upper bound on the number of iterations, but it will succeed eventually if the input degree sequence is graphical and throw an exception if the input degree sequence is not graphical.
  • "vl" -- a more sophisticated generator that can sample undirected, connected simple graphs uniformly. It uses Monte-Carlo methods to randomize the graphs. This generator should be favoured if undirected and connected graphs are to be generated and execution time is not a concern. igraph uses the original implementation of Fabien Viger; see the following URL and the paper cited on it for the details of the algorithm: https://www-complexnetworks.lip6.fr/~latapy/FV/generation.html.
def delete_edges(es):
overridden in igraph.Graph

Removes edges from the graph.

All vertices will be kept, even if they lose all their edges. Nonexistent edges will be silently ignored.

Parameters
esthe list of edges to be removed. Edges are identifed by edge IDs. EdgeSeq objects are also accepted here. No argument deletes all edges.
def delete_vertices(vs):

Deletes vertices and all its edges from the graph.

Parameters
vsa single vertex ID or the list of vertex IDs to be deleted. No argument deletes all vertices.
def density(loops=False):

Calculates the density of the graph.

Parameters
loopswhether to take loops into consideration. If True, the algorithm assumes that there might be some loops in the graph and calculates the density accordingly. If False, the algorithm assumes that there can't be any loops.
Returns
the density of the graph.
def dfsiter(vid, mode='out', advanced=False):

Constructs a depth first search (DFS) iterator of the graph.

Parameters
vidthe root vertex ID
modeeither "in" or "out" or "all".
advancedif False, the iterator returns the next vertex in DFS order in every step. If True, the iterator returns the distance of the vertex from the root and the parent of the vertex in the DFS tree as well.
Returns
the DFS iterator as an igraph.DFSIter object.
def diameter(directed=True, unconn=True, weights=None):

Calculates the diameter of the graph.

Parameters
directedwhether to consider directed paths.
unconnif True and the graph is unconnected, the longest geodesic within a component will be returned. If False and the graph is unconnected, the result is the number of vertices if there are no weights or infinity if there are weights.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
Returns
the diameter
def difference(other):

Subtracts the given graph from the original

def diversity(vertices=None, weights=None):

Calculates the structural diversity index of the vertices.

The structural diversity index of a vertex is simply the (normalized) Shannon entropy of the weights of the edges incident on the vertex.

The measure is defined for undirected graphs only; edge directions are ignored.

Parameters
verticesthe vertices for which the diversity indices must be returned. If None, uses all of the vertices in the graph.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
Returns
the calculated diversity indices in a list, or a single number if a single vertex was supplied.
Unknown Field: newfield
refReference
Unknown Field: ref
Eagle N, Macy M and Claxton R: Network diversity and economic development, Science 328, 1029--1031, 2010.
def dominator(vid, mode='out'):

Returns the dominator tree from the given root node

Parameters
vidthe root vertex ID
modeeither "in" or "out"
Returns
a list containing the dominator tree for the current graph.
def dyad_census():
overridden in igraph.Graph

Dyad census, as defined by Holland and Leinhardt

Dyad census means classifying each pair of vertices of a directed graph into three categories: mutual, there is an edge from a to b and also from b to a; asymmetric, there is an edge either from a to b or from b to a but not the other way and null, no edges between a and b.

Returns
the number of mutual, asymmetric and null connections in a 3-tuple.
Unknown Field: attention
this function has a more convenient interface in class Graph which wraps the result in a DyadCensus object. It is advised to use that.
def eccentricity(vertices=None, mode='all'):

Calculates the eccentricities of given vertices in a graph.

The eccentricity of a vertex is calculated by measuring the shortest distance from (or to) the vertex, to (or from) all other vertices in the graph, and taking the maximum.

Parameters
verticesthe vertices for which the eccentricity scores must be returned. If None, uses all of the vertices in the graph.
modemust be one of "in", "out" and "all". "in" means that edge directions are followed; "out" means that edge directions are followed the opposite direction; "all" means that directions are ignored. The argument has no effect for undirected graphs.
Returns
the calculated eccentricities in a list, or a single number if a single vertex was supplied.
def ecount():

Counts the number of edges.

Returns
integerthe number of edges in the graph.
def edge_attributes():
Returns
the attribute name list of the edges of the graph
def edge_betweenness(directed=True, cutoff=None, weights=None):

Calculates or estimates the edge betweennesses in a graph.

Parameters
directedwhether to consider directed paths.
cutoffif it is an integer, only paths less than or equal to this length are considered, effectively resulting in an estimation of the betweenness values. If None, the exact betweennesses are returned.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
Returns
a list with the (exact or estimated) edge betweennesses of all edges.
def edge_connectivity(source=-1, target=-1, checks=True):

Calculates the edge connectivity of the graph or between some vertices.

The edge connectivity between two given vertices is the number of edges that have to be removed in order to disconnect the two vertices into two separate components. This is also the number of edge disjoint directed paths between the vertices. The edge connectivity of the graph is the minimal edge connectivity over all vertex pairs.

This method calculates the edge connectivity of a given vertex pair if both the source and target vertices are given. If none of them is given (or they are both negative), the overall edge connectivity is returned.

Parameters
sourcethe source vertex involved in the calculation.
targetthe target vertex involved in the calculation.
checksif the whole graph connectivity is calculated and this is True, igraph performs some basic checks before calculation. If the graph is not strongly connected, then the connectivity is obviously zero. If the minimum degree is one, then the connectivity is also one. These simple checks are much faster than checking the entire graph, therefore it is advised to set this to True. The parameter is ignored if the connectivity between two given vertices is computed.
Returns
the edge connectivity
def eigen_adjacency(...):

Undocumented

def eigenvector_centrality(directed=True, scale=True, weights=None, return_eigenvalue=False, arpack_options=None):

Calculates the eigenvector centralities of the vertices in a graph.

Eigenvector centrality is a measure of the importance of a node in a network. It assigns relative scores to all nodes in the network based on the principle that connections from high-scoring nodes contribute more to the score of the node in question than equal connections from low-scoring nodes. In practice, the centralities are determined by calculating eigenvector corresponding to the largest positive eigenvalue of the adjacency matrix. In the undirected case, this function considers the diagonal entries of the adjacency matrix to be twice the number of self-loops on the corresponding vertex.

In the directed case, the left eigenvector of the adjacency matrix is calculated. In other words, the centrality of a vertex is proportional to the sum of centralities of vertices pointing to it.

Eigenvector centrality is meaningful only for connected graphs. Graphs that are not connected should be decomposed into connected components, and the eigenvector centrality calculated for each separately.

Parameters
directedwhether to consider edge directions in a directed graph. Ignored for undirected graphs.
scalewhether to normalize the centralities so the largest one will always be 1.
weightsedge weights given as a list or an edge attribute. If None, all edges have equal weight.
return_eigenvaluewhether to return the actual largest eigenvalue along with the centralities
arpack_optionsan ARPACKOptions object that can be used to fine-tune the calculation. If it is omitted, the module-level variable called arpack_options is used.
Returns
the eigenvector centralities in a list and optionally the largest eigenvalue (as a second member of a tuple)
def Erdos_Renyi(n, p, m, directed=False, loops=False):

Generates a graph based on the Erdos-Renyi model.

Parameters
nthe number of vertices.
pthe probability of edges. If given, m must be missing.
mthe number of edges. If given, p must be missing.
directedwhether to generate a directed graph.
loopswhether self-loops are allowed.
def Establishment(n, k, type_dist, pref_matrix, directed=False):

Generates a graph based on a simple growing model with vertex types.

A single vertex is added at each time step. This new vertex tries to connect to k vertices in the graph. The probability that such a connection is realized depends on the types of the vertices involved.

Parameters
nthe number of vertices in the graph
kthe number of connections tried in each step
type_distlist giving the distribution of vertex types
pref_matrixmatrix (list of lists) giving the connection probabilities for different vertex types
directedwhether to generate a directed graph.
def Famous(name):

Generates a famous graph based on its name.

Several famous graphs are known to igraph including (but not limited to) the Chvatal graph, the Petersen graph or the Tutte graph. This method generates one of them based on its name (case insensitive). See the documentation of the C interface of igraph for the names available: https://igraph.org/c/doc.

Parameters
namethe name of the graph to be generated.
def farthest_points(directed=True, unconn=True, weights=None):

Returns two vertex IDs whose distance equals the actual diameter of the graph.

If there are many shortest paths with the length of the diameter, it returns the first one it found.

Parameters
directedwhether to consider directed paths.
unconnif True and the graph is unconnected, the longest geodesic within a component will be returned. If False and the graph is unconnected, the result contains the number of vertices if there are no weights or infinity if there are weights.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
Returns
a triplet containing the two vertex IDs and their distance. The IDs are None if the graph is unconnected and unconn is False.
def feedback_arc_set(weights=None, method='eades'):

Calculates an approximately or exactly minimal feedback arc set.

A feedback arc set is a set of edges whose removal makes the graph acyclic. Since this is always possible by removing all the edges, we are in general interested in removing the smallest possible number of edges, or an edge set with as small total weight as possible. This method calculates one such edge set. Note that the task is trivial for an undirected graph as it is enough to find a spanning tree and then remove all the edges not in the spanning tree. Of course it is more complicated for directed graphs.

Parameters
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name. When given, the algorithm will strive to remove lightweight edges in order to minimize the total weight of the feedback arc set.
methodthe algorithm to use. "eades" uses the greedy cycle breaking heuristic of Eades, Lin and Smyth, which is linear in the number of edges but not necessarily optimal; however, it guarantees that the number of edges to be removed is smaller than |E|/2 - |V|/6. "ip" uses an integer programming formulation which is guaranteed to yield an optimal result, but is too slow for large graphs.
Returns
the IDs of the edges to be removed, in a list.
Unknown Field: newfield
refReference
Unknown Field: ref
Eades P, Lin X and Smyth WF: A fast and effective heuristic for the feedback arc set problem. In: Proc Inf Process Lett 319-323, 1993.
def Forest_Fire(n, fw_prob, bw_factor=0.0, ambs=1, directed=False):

Generates a graph based on the forest fire model

The forest fire model is a growing graph model. In every time step, a new vertex is added to the graph. The new vertex chooses an ambassador (or more than one if ambs > 1) and starts a simulated forest fire at its ambassador(s). The fire spreads through the edges. The spreading probability along an edge is given by fwprob. The fire may also spread backwards on an edge by probability fwprob*bwfactor. When the fire ended, the newly added vertex connects to the vertices ``burned'' in the previous fire.

Parameters
nthe number of vertices in the graph
fw_probforward burning probability
bw_factorratio of backward and forward burning probability
ambsnumber of ambassadors chosen in each step
directedwhether the graph will be directed
def Full(n, directed=False, loops=False):

Generates a full graph (directed or undirected, with or without loops).

Parameters
nthe number of vertices.
directedwhether to generate a directed graph.
loopswhether self-loops are allowed.
def Full_Citation(n, directed=False):

Generates a full citation graph

A full citation graph is a graph where the vertices are indexed from 0 to n − 1 and vertex i has a directed edge towards all vertices with an index less than i.

Parameters
nthe number of vertices.
directedwhether to generate a directed graph.
def get_adjacency(type='both', eids=False):
overridden in igraph.Graph

Returns the adjacency matrix of a graph.

Parameters
typeone of "lower" (uses the lower triangle of the matrix), "upper" (uses the upper triangle) or "both" (uses both parts). Ignored for directed graphs.
eidsif True, the result matrix will contain zeros for non-edges and the ID of the edge plus one for edges in the appropriate cell. If False, the result matrix will contain the number of edges for each vertex pair.
Returns
the adjacency matrix.
def get_all_shortest_paths(v, to=None, weights=None, mode='out'):

Calculates all of the shortest paths from/to a given node in a graph.

Parameters
vthe source for the calculated paths
toa 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 VertexSeq object. None means all the vertices.
weightsedge weights in a list or the name of an edge attribute holding edge weights. If None, all edges are assumed to have equal weight.
modethe directionality of the paths. "in" means to calculate incoming paths, "out" means to calculate outgoing paths, "all" means to calculate both ones.
Returns
all of the shortest path from the given node to every other reachable node in the graph in a list. Note that in case of mode="in", the vertices in a path are returned in reversed order!
def get_diameter(directed=True, unconn=True, weights=None):

Returns a path with the actual diameter of the graph.

If there are many shortest paths with the length of the diameter, it returns the first one it founds.

Parameters
directedwhether to consider directed paths.
unconnif True and the graph is unconnected, the longest geodesic within a component will be returned. If False and the graph is unconnected, the result is the number of vertices if there are no weights or infinity if there are weights.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
Returns
the vertices in the path in order.
def get_edgelist():

Returns the edge list of a graph.

def get_eid(v1, v2, directed=True, error=True):

Returns the edge ID of an arbitrary edge between vertices v1 and v2

Parameters
v1the ID or name of the first vertex
v2the ID or name of the second vertex
directedwhether edge directions should be considered in directed graphs. The default is True. Ignored for undirected graphs.
errorif True, an exception will be raised when the given edge does not exist. If False, -1 will be returned in that case.
Returns
the edge ID of an arbitrary edge between vertices v1 and v2
def get_eids(pairs=None, path=None, directed=True, error=True):

Returns the edge IDs of some edges between some vertices.

This method can operate in two different modes, depending on which of the keyword arguments pairs and path are given.

The method does not consider multiple edges; if there are multiple edges between a pair of vertices, only the ID of one of the edges is returned.

Parameters
pairsa list of integer pairs. Each integer pair is considered as a source-target vertex pair; the corresponding edge is looked up in the graph and the edge ID is returned for each pair.
patha list of vertex IDs. The list is considered as a continuous path from the first vertex to the last, passing through the intermediate vertices. The corresponding edge IDs between the first and the second, the second and the third and so on are looked up in the graph and the edge IDs are returned. If both path and pairs are given, the two lists are concatenated.
directedwhether edge directions should be considered in directed graphs. The default is True. Ignored for undirected graphs.
errorif True, an exception will be raised if a given edge does not exist. If False, -1 will be returned in that case.
Returns
the edge IDs in a list
def get_incidence(types):
overridden in igraph.Graph

Internal function, undocumented.

See Also
Graph.get_incidence()
def get_isomorphisms_vf2(other=None, color1=None, color2=None, edge_color1=None, edge_color2=None, node_compat_fn=None, edge_compat_fn=None):

Returns all isomorphisms between the graph and another one

Vertex and edge colors may be used to restrict the isomorphisms, as only vertices and edges with the same color will be allowed to match each other.

Parameters
otherthe other graph. If None, the automorphisms will be returned.
color1optional vector storing the coloring of the vertices of the first graph. If None, all vertices have the same color.
color2optional vector storing the coloring of the vertices of the second graph. If None, all vertices have the same color.
edge_color1optional vector storing the coloring of the edges of the first graph. If None, all edges have the same color.
edge_color2optional vector storing the coloring of the edges of the second graph. If None, all edges have the same color.
node_compat_fna function that receives the two graphs and two node indices (one from the first graph, one from the second graph) and returns True if the nodes given by the two indices are compatible (i.e. they could be matched to each other) or False otherwise. This can be used to restrict the set of isomorphisms based on node-specific criteria that are too complicated to be represented by node color vectors (i.e. the color1 and color2 parameters). None means that every node is compatible with every other node.
edge_compat_fna function that receives the two graphs and two edge indices (one from the first graph, one from the second graph) and returns True if the edges given by the two indices are compatible (i.e. they could be matched to each other) or False otherwise. This can be used to restrict the set of isomorphisms based on edge-specific criteria that are too complicated to be represented by edge color vectors (i.e. the edge_color1 and edge_color2 parameters). None means that every edge is compatible with every other node.
Returns
a list of lists, each item of the list containing the mapping from vertices of the second graph to the vertices of the first one
def get_shortest_paths(v, to=None, weights=None, mode='out', output='vpath'):

Calculates the shortest paths from/to a given node in a graph.

Parameters
vthe source/destination for the calculated paths
toa vertex selector describing the destination/source 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 VertexSeq object. None means all the vertices.
weightsedge weights in a list or the name of an edge attribute holding edge weights. If None, all edges are assumed to have equal weight.
modethe directionality of the paths. "in" means to calculate incoming paths, "out" means to calculate outgoing paths, "all" means to calculate both ones.
outputdetermines what should be returned. If this is "vpath", a list of vertex IDs will be returned, one path for each target vertex. For unconnected graphs, some of the list elements may be empty. Note that in case of mode="in", the vertices in a path are returned in reversed order. If output="epath", edge IDs are returned instead of vertex IDs.
Returns
see the documentation of the output parameter.
def get_subisomorphisms_lad(other, domains=None, induced=False, time_limit=0):

Returns all subisomorphisms between the graph and another one using the LAD algorithm.

The optional domains argument may be used to restrict vertices that may match each other. You can also specify whether you are interested in induced subgraphs only or not.

Parameters
otherthe pattern graph we are looking for in the graph.
domainsa list of lists, one sublist belonging to each vertex in the template graph. Sublist i contains the indices of the vertices in the original graph that may match vertex i in the template graph. None means that every vertex may match every other vertex.
inducedwhether to consider induced subgraphs only.
time_limitan optimal time limit in seconds. Only the integral part of this number is taken into account. If the time limit is exceeded, the method will throw an exception.
Returns
a list of lists, each item of the list containing the mapping from vertices of the second graph to the vertices of the first one
def get_subisomorphisms_vf2(other, color1=None, color2=None, edge_color1=None, edge_color2=None, node_compat_fn=None, edge_compat_fn=None):

Returns all subisomorphisms between the graph and another one

Vertex and edge colors may be used to restrict the isomorphisms, as only vertices and edges with the same color will be allowed to match each other.

Parameters
otherthe other graph.
color1optional vector storing the coloring of the vertices of the first graph. If None, all vertices have the same color.
color2optional vector storing the coloring of the vertices of the second graph. If None, all vertices have the same color.
edge_color1optional vector storing the coloring of the edges of the first graph. If None, all edges have the same color.
edge_color2optional vector storing the coloring of the edges of the second graph. If None, all edges have the same color.
node_compat_fna function that receives the two graphs and two node indices (one from the first graph, one from the second graph) and returns True if the nodes given by the two indices are compatible (i.e. they could be matched to each other) or False otherwise. This can be used to restrict the set of isomorphisms based on node-specific criteria that are too complicated to be represented by node color vectors (i.e. the color1 and color2 parameters). None means that every node is compatible with every other node.
edge_compat_fna function that receives the two graphs and two edge indices (one from the first graph, one from the second graph) and returns True if the edges given by the two indices are compatible (i.e. they could be matched to each other) or False otherwise. This can be used to restrict the set of isomorphisms based on edge-specific criteria that are too complicated to be represented by edge color vectors (i.e. the edge_color1 and edge_color2 parameters). None means that every edge is compatible with every other node.
Returns
a list of lists, each item of the list containing the mapping from vertices of the second graph to the vertices of the first one
def girth(return_shortest_circle=False):

Returns the girth of the graph.

The girth of a graph is the length of the shortest circle in it.

Parameters
return_shortest_circlewhether to return one of the shortest circles found in the graph.
Returns
the length of the shortest circle or (if return_shortest_circle) is true, the shortest circle itself as a list
def gomory_hu_tree(capacity=None):
overridden in igraph.Graph

Internal function, undocumented.

See Also
Graph.gomory_hu_tree()
def Growing_Random(n, m, directed=False, citation=False):

Generates a growing random graph.

Parameters
nThe number of vertices in the graph
mThe number of edges to add in each step (after adding a new vertex)
directedwhether the graph should be directed.
citationwhether the new edges should originate from the most recently added vertex.
def harmonic_centrality(vertices=None, mode='all', cutoff=None, weights=None, normalized=True):

Calculates the harmonic centralities of given vertices in a graph.

The harmonic centerality of a vertex measures how easily other vertices can be reached from it (or the other way: how easily it can be reached from the other vertices). It is defined as the mean inverse distance to all other vertices.

If the graph is not connected, and there is no path between two vertices, the inverse distance is taken to be zero.

Parameters
verticesthe vertices for which the harmonic centrality must be returned. If None, uses all of the vertices in the graph.
modemust be one of "in", "out" and "all". "in" means that the length of the incoming paths, "out" means that the length of the outgoing paths must be calculated. "all" means that both of them must be calculated.
cutoffif it is not None, only paths less than or equal to this length are considered.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
normalizedWhether to normalize the result. If True, the result is the mean inverse path length to other vertices, i.e. it is normalized by the number of vertices minus one. If False, the result is the sum of inverse path lengths to other vertices.
Returns
the calculated harmonic centralities in a list
def has_multiple():

Checks whether the graph has multiple edges.

Returns
booleanTrue if the graph has at least one multiple edge, False otherwise.
def hub_score(weights=None, scale=True, arpack_options=None, return_eigenvalue=False):

Calculates Kleinberg's hub score for the vertices of the graph

Parameters
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
scalewhether to normalize the scores so that the largest one is 1.
arpack_optionsan ARPACKOptions object used to fine-tune the ARPACK eigenvector calculation. If omitted, the module-level variable called arpack_options is used.
return_eigenvaluewhether to return the largest eigenvalue
Returns
the hub scores in a list and optionally the largest eigenvalue as a second member of a tuple
See Also
authority_score()
def incident(vertex, mode='out'):

Returns the edges a given vertex is incident on.

Parameters
vertexa vertex ID
modewhether to return only successors ("out"), predecessors ("in") or both ("all"). Ignored for undirected graphs.
def independence_number():

Returns the independence number of the graph.

The independence number of the graph is the size of the largest independent vertex set.

See Also
largest_independent_vertex_sets() for the largest independent vertex sets
def independent_vertex_sets(min=0, max=0):

Returns some or all independent vertex sets of the graph as a list of tuples.

Two vertices are independent if there is no edge between them. Members of an independent vertex set are mutually independent.

Parameters
minthe minimum size of sets to be returned. If zero or negative, no lower bound will be used.
maxthe maximum size of sets to be returned. If zero or negative, no upper bound will be used.
def induced_subgraph(vertices, implementation='auto'):

Returns a subgraph spanned by the given vertices.

Parameters
verticesa list containing the vertex IDs which should be included in the result.
implementationthe implementation to use when constructing the new subgraph. igraph includes two implementations at the moment. "copy_and_delete" copies the original graph and removes those vertices that are not in the given set. This is more efficient if the size of the subgraph is comparable to the original graph. The other implementation ("create_from_scratch") constructs the result graph from scratch and then copies the attributes accordingly. This is a better solution if the subgraph is relatively small, compared to the original graph. "auto" selects between the two implementations automatically, based on the ratio of the size of the subgraph and the size of the original graph.
Returns
the subgraph
def is_bipartite(return_types=False):

Decides whether the graph is bipartite or not.

Vertices of a bipartite graph can be partitioned into two groups A and B in a way that all edges go between the two groups.

Parameters
return_typesif False, the method will simply return True or False depending on whether the graph is bipartite or not. If True, the actual group assignments are also returned as a list of boolean values. (Note that the group assignment is not unique, especially if the graph consists of multiple components, since the assignments of components are independent from each other).
Returns
True if the graph is bipartite, False if not. If return_types is True, the group assignment is also returned.
def is_chordal(alpha=None, alpham1=None):

Returns whether the graph is chordal or not.

A graph is chordal if each of its cycles of four or more nodes has a chord, i.e. an edge joining two nodes that are not adjacent in the cycle. An equivalent definition is that any chordless cycles have at most three nodes.

Parameters
alphathe alpha vector from the result of calling maximum_cardinality_search() on the graph. Useful only if you already have the alpha vector; simply passing None here will make igraph calculate the alpha vector on its own.
alpham1the inverse alpha vector from the result of calling maximum_cardinality_search() on the graph. Useful only if you already have the inverse alpha vector; simply passing None here will make igraph calculate the inverse alpha vector on its own.
Returns
True if the graph is chordal, False otherwise.
def is_connected(mode='strong'):

Decides whether the graph is connected.

Parameters
modewhether we should calculate strong or weak connectivity.
Returns
True if the graph is connected, False otherwise.
def is_dag():

Checks whether the graph is a DAG (directed acyclic graph).

A DAG is a directed graph with no directed cycles.

Returns
booleanTrue if it is a DAG, False otherwise.
def is_directed():

Checks whether the graph is directed.

Returns
booleanTrue if it is directed, False otherwise.
def is_loop(edges=None):

Checks whether a specific set of edges contain loop edges

Parameters
edgesedge indices which we want to check. If None, all edges are checked.
Returns
a list of booleans, one for every edge given
def is_minimal_separator(vertices):

Decides whether the given vertex set is a minimal separator.

A minimal separator is a set of vertices whose removal disconnects the graph, while the removal of any subset of the set keeps the graph connected.

Parameters
verticesa single vertex ID or a list of vertex IDs
Returns
True is the given vertex set is a minimal separator, False otherwise.
def is_multiple(edges=None):

Checks whether an edge is a multiple edge.

Also works for a set of edges -- in this case, every edge is checked one by one. Note that if there are multiple edges going between a pair of vertices, there is always one of them that is not reported as multiple (only the others). This allows one to easily detect the edges that have to be deleted in order to make the graph free of multiple edges.

Parameters
edgesedge indices which we want to check. If None, all edges are checked.
Returns
a list of booleans, one for every edge given
def is_mutual(edges=None):

Checks whether an edge has an opposite pair.

Also works for a set of edges -- in this case, every edge is checked one by one. The result will be a list of booleans (or a single boolean if only an edge index is supplied), every boolean corresponding to an edge in the edge set supplied. True is returned for a given edge a --> b if there exists another edge b --> a in the original graph (not the given edge set!). All edges in an undirected graph are mutual. In case there are multiple edges between a and b, it is enough to have at least one edge in either direction to report all edges between them as mutual, so the multiplicity of edges do not matter.

Parameters
edgesedge indices which we want to check. If None, all edges are checked.
Returns
a list of booleans, one for every edge given
def is_separator(vertices):

Decides whether the removal of the given vertices disconnects the graph.

Parameters
verticesa single vertex ID or a list of vertex IDs
Returns
True is the given vertex set is a separator, False if not.
def is_simple():

Checks whether the graph is simple (no loop or multiple edges).

Returns
booleanTrue if it is simple, False otherwise.
def is_tree(mode='out'):

Checks whether the graph is a (directed or undirected) tree graph.

For directed trees, the function may require that the edges are oriented outwards from the root or inwards to the root, depending on the value of the mode argument.

Parameters
modefor directed graphs, specifies how the edge directions should be taken into account. "all" means that the edge directions must be ignored, "out" means that the edges must be oriented away from the root, "in" means that the edges must be oriented towards the root. Ignored for undirected graphs.
Returns
booleanTrue if the graph is a tree, False otherwise.
def Isoclass(n, cls, directed=False):

Generates a graph with a given isomorphism class.

Parameters
nthe number of vertices in the graph (3 or 4)
clsthe isomorphism class
directedwhether the graph should be directed.
def isoclass(vertices):

Returns the isomorphism class of the graph or its subgraph.

Isomorphy class calculations are implemented only for graphs with 3 or 4 vertices.

Parameters
verticesa list of vertices if we want to calculate the isomorphism class for only a subset of vertices. None means to use the full graph.
Returns
the isomorphism class of the (sub)graph
def isomorphic(other):

Checks whether the graph is isomorphic to another graph.

The algorithm being used is selected using a simple heuristic:

  • If one graph is directed and the other undirected, an exception is thrown.
  • If the two graphs does not have the same number of vertices and edges, it returns with False
  • If the graphs have three or four vertices, then an O(1) algorithm is used with precomputed data.
  • Otherwise if the graphs are directed, then the VF2 isomorphism algorithm is used (see isomorphic_vf2).
  • Otherwise the BLISS isomorphism algorithm is used, see isomorphic_bliss.
Returns
True if the graphs are isomorphic, False otherwise.
def isomorphic_bliss(other, return_mapping_12=False, return_mapping_21=False, sh1='fl', sh2=None, color1=None, color2=None):

Checks whether the graph is isomorphic to another graph, using the BLISS isomorphism algorithm.

See http://www.tcs.hut.fi/Software/bliss/index.html for more information about the BLISS algorithm.

Parameters
otherthe other graph with which we want to compare the graph.
return_mapping_12if True, calculates the mapping which maps the vertices of the first graph to the second.
return_mapping_21if True, calculates the mapping which maps the vertices of the second graph to the first.
sh1

splitting heuristics for the first graph as a case-insensitive string, with the following possible values:

  • "f": first non-singleton cell
  • "fl": first largest non-singleton cell
  • "fs": first smallest non-singleton cell
  • "fm": first maximally non-trivially connected non-singleton cell
  • "flm": largest maximally non-trivially connected non-singleton cell
  • "fsm": smallest maximally non-trivially connected non-singleton cell
sh2splitting heuristics to be used for the second graph. This must be the same as sh1; alternatively, it can be None, in which case it will automatically use the same value as sh1. Currently it is present for backwards compatibility only.
color1optional vector storing the coloring of the vertices of the first graph. If None, all vertices have the same color.
color2optional vector storing the coloring of the vertices of the second graph. If None, all vertices have the same color.
Returns
if no mapping is calculated, the result is True if the graphs are isomorphic, False otherwise. If any or both mappings are calculated, the result is a 3-tuple, the first element being the above mentioned boolean, the second element being the 1 -> 2 mapping and the third element being the 2 -> 1 mapping. If the corresponding mapping was not calculated, None is returned in the appropriate element of the 3-tuple.
def isomorphic_vf2(other=None, color1=None, color2=None, edge_color1=None, edge_color2=None, return_mapping_12=False, return_mapping_21=False, node_compat_fn=None, edge_compat_fn=None, callback=None):

Checks whether the graph is isomorphic to another graph, using the VF2 isomorphism algorithm.

Vertex and edge colors may be used to restrict the isomorphisms, as only vertices and edges with the same color will be allowed to match each other.

Parameters
otherthe other graph with which we want to compare the graph. If None, the automorphjisms of the graph will be tested.
color1optional vector storing the coloring of the vertices of the first graph. If None, all vertices have the same color.
color2optional vector storing the coloring of the vertices of the second graph. If None, all vertices have the same color.
edge_color1optional vector storing the coloring of the edges of the first graph. If None, all edges have the same color.
edge_color2optional vector storing the coloring of the edges of the second graph. If None, all edges have the same color.
return_mapping_12if True, calculates the mapping which maps the vertices of the first graph to the second.
return_mapping_21if True, calculates the mapping which maps the vertices of the second graph to the first.
node_compat_fna function that receives the two graphs and two node indices (one from the first graph, one from the second graph) and returns True if the nodes given by the two indices are compatible (i.e. they could be matched to each other) or False otherwise. This can be used to restrict the set of isomorphisms based on node-specific criteria that are too complicated to be represented by node color vectors (i.e. the color1 and color2 parameters). None means that every node is compatible with every other node.
edge_compat_fna function that receives the two graphs and two edge indices (one from the first graph, one from the second graph) and returns True if the edges given by the two indices are compatible (i.e. they could be matched to each other) or False otherwise. This can be used to restrict the set of isomorphisms based on edge-specific criteria that are too complicated to be represented by edge color vectors (i.e. the edge_color1 and edge_color2 parameters). None means that every edge is compatible with every other node.
callbackif not None, the isomorphism search will not stop at the first match; it will call this callback function instead for every isomorphism found. The callback function must accept four arguments: the first graph, the second graph, a mapping from the nodes of the first graph to the second, and a mapping from the nodes of the second graph to the first. The function must return True if the search should continue or False otherwise.
Returns
if no mapping is calculated, the result is True if the graphs are isomorphic, False otherwise. If any or both mappings are calculated, the result is a 3-tuple, the first element being the above mentioned boolean, the second element being the 1 -> 2 mapping and the third element being the 2 -> 1 mapping. If the corresponding mapping was not calculated, None is returned in the appropriate element of the 3-tuple.
def K_Regular(n, k, directed=False, multiple=False):

Generates a k-regular random graph

A k-regular random graph is a random graph where each vertex has degree k. If the graph is directed, both the in-degree and the out-degree of each vertex will be k.

Parameters
nThe number of vertices in the graph
kThe degree of each vertex if the graph is undirected, or the in-degree and out-degree of each vertex if the graph is directed
directedwhether the graph should be directed.
multiplewhether it is allowed to create multiple edges.
def Kautz(m, n):

Generates a Kautz graph with parameters (m, n)

A Kautz graph is a labeled graph, vertices are labeled by strings of length n + 1 above an alphabet with m + 1 letters, with the restriction that every two consecutive letters in the string must be different. There is a directed edge from a vertex v to another vertex w if it is possible to transform the string of v into the string of w by removing the first letter and appending a letter to it.

Parameters
mthe size of the alphabet minus one
nthe length of the strings minus one
def knn(vids=None, weights=None):

Calculates the average degree of the neighbors for each vertex, and the same quantity as the function of vertex degree.

Parameters
vidsthe vertices for which the calculation is performed. None means all vertices.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name. If this is given, the vertex strength will be used instead of the vertex degree in the calculations, but the "ordinary" vertex degree will be used for the second (degree- dependent) list in the result.
Returns
two lists in a tuple. The first list contains the average degree of neighbors for each vertex, the second contains the average degree of neighbors as a function of vertex degree. The zeroth element of this list corresponds to vertices of degree 1.
def laplacian(weights=None, normalized=False):

Returns the Laplacian matrix of a graph.

The Laplacian matrix is similar to the adjacency matrix, but the edges are denoted with -1 and the diagonal contains the node degrees.

Normalized Laplacian matrices have 1 or 0 in their diagonals (0 for vertices with no edges), edges are denoted by 1 / sqrt(d_i * d_j) where d_i is the degree of node i.

Multiple edges and self-loops are silently ignored. Although it is possible to calculate the Laplacian matrix of a directed graph, it does not make much sense.

Parameters
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name. When edge weights are used, the degree of a node is considered to be the weight of its incident edges.
normalizedwhether to return the normalized Laplacian matrix.
Returns
the Laplacian matrix.
def largest_cliques():

Returns the largest cliques of the graph as a list of tuples.

Quite intuitively a clique is considered largest if there is no clique with more vertices in the whole graph. All largest cliques are maximal (i.e. nonextendable) but not all maximal cliques are largest.

See Also
clique_number() for the size of the largest cliques or maximal_cliques() for the maximal cliques
def largest_independent_vertex_sets():

Returns the largest independent vertex sets of the graph as a list of tuples.

Quite intuitively an independent vertex set is considered largest if there is no other set with more vertices in the whole graph. All largest sets are maximal (i.e. nonextendable) but not all maximal sets are largest.

See Also
independence_number() for the size of the largest independent vertex sets or maximal_independent_vertex_sets() for the maximal (nonextendable) independent vertex sets
def Lattice(dim, nei=1, directed=False, mutual=True, circular=True):

Generates a regular lattice.

Parameters
dimlist with the dimensions of the lattice
neivalue giving the distance (number of steps) within which two vertices will be connected.
directedwhether to create a directed graph.
mutualwhether to create all connections as mutual in case of a directed graph.
circularwhether the generated lattice is periodic.
def layout_bipartite(types='type', hgap=1, vgap=1, maxiter=100):

Place the vertices of a bipartite graph in two layers.

The layout is created by placing the vertices in two rows, according to their types. The positions of the vertices within the rows are then optimized to minimize the number of edge crossings using the heuristic used by the Sugiyama layout algorithm.

Parameters
typesan igraph vector containing the vertex types, or an attribute name. Anything that evalulates to False corresponds to vertices of the first kind, everything else to the second kind.
hgapminimum horizontal gap between vertices in the same layer.
vgapvertical gap between the two layers.
maxitermaximum number of iterations to take in the crossing reduction step. Increase this if you feel that you are getting too many edge crossings.
Returns
the calculated layout.
def layout_circle(dim=2, order=None):

Places the vertices of the graph uniformly on a circle or a sphere.

Parameters
dimthe desired number of dimensions for the layout. dim=2 means a 2D layout, dim=3 means a 3D layout.
orderthe order in which the vertices are placed along the circle. Not supported when dim is not equal to 2.
Returns
the calculated layout.
def layout_davidson_harel(seed=None, maxiter=10, fineiter=-1, cool_fact=0.75, weight_node_dist=1.0, weight_border=0.0, weight_edge_lengths=-1, weight_edge_crossings=-1, weight_node_edge_dist=-1):

Places the vertices on a 2D plane according to the Davidson-Harel layout algorithm.

The algorithm uses simulated annealing and a sophisticated energy function, which is unfortunately hard to parameterize for different graphs. The original publication did not disclose any parameter values, and the ones below were determined by experimentation.

The algorithm consists of two phases: an annealing phase and a fine-tuning phase. There is no simulated annealing in the second phase.

Parameters
seedif None, uses a random starting layout for the algorithm. If a matrix (list of lists), uses the given matrix as the starting position.
maxiterNumber of iterations to perform in the annealing phase.
fineiterNumber of iterations to perform in the fine-tuning phase. Negative numbers set up a reasonable default from the base-2 logarithm of the vertex count, bounded by 10 from above.
cool_factCooling factor of the simulated annealing phase.
weight_node_distWeight for the node-node distances in the energy function.
weight_borderWeight for the distance from the border component of the energy function. Zero means that vertices are allowed to sit on the border of the area designated for the layout.
weight_edge_lengthsWeight for the edge length component of the energy function. Negative numbers are replaced by the density of the graph divided by 10.
weight_edge_crossingsWeight for the edge crossing component of the energy function. Negative numbers are replaced by one minus the square root of the density of the graph.
weight_node_edge_distWeight for the node-edge distance component of the energy function. Negative numbers are replaced by 0.2 minus 0.2 times the density of the graph.
Returns
the calculated layout.
def layout_drl(weights=None, fixed=None, seed=None, options=None, dim=2):

Places the vertices on a 2D plane or in the 3D space ccording to the DrL layout algorithm.

This is an algorithm suitable for quite large graphs, but it can be surprisingly slow for small ones (where the simpler force-based layouts like layout_kamada_kawai() or layout_fruchterman_reingold() are more useful.

Parameters
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
fixedignored. We used to assume that the DrL layout supports fixed nodes, but later it turned out that the argument has no effect in the original DrL code. We kept the argument for sake of backwards compatibility, but it will have no effect on the final layout.
seedif None, uses a random starting layout for the algorithm. If a matrix (list of lists), uses the given matrix as the starting position.
options

if you give a string argument here, you can select from five default preset parameterisations: default, coarsen for a coarser layout, coarsest for an even coarser layout, refine for refining an existing layout and final for finalizing a layout. If you supply an object that is not a string, the DrL layout parameters are retrieved from the respective keys of the object (so it should be a dict or something else that supports the mapping protocol). The following keys can be used:

  • edge_cut: edge cutting is done in the late stages of the algorithm in order to achieve less dense layouts. Edges are cut if there is a lot of stress on them (a large value in the objective function sum). The edge cutting parameter is a value between 0 and 1 with 0 representing no edge cutting and 1 representing maximal edge cutting.
  • init_iterations: number of iterations in the initialization phase
  • init_temperature: start temperature during initialization
  • init_attraction: attraction during initialization
  • init_damping_mult: damping multiplier during initialization
  • liquid_iterations, liquid_temperature, liquid_attraction, liquid_damping_mult: same parameters for the liquid phase
  • expansion_iterations, expansion_temperature, expansion_attraction, expansion_damping_mult: parameters for the expansion phase
  • cooldown_...: parameters for the cooldown phase
  • crunch_...: parameters for the crunch phase
  • simmer_...: parameters for the simmer phase

Instead of a mapping, you can also use an arbitrary Python object here: if the object does not support the mapping protocol, an attribute of the object with the same name is looked up instead. If a parameter cannot be found either as a key or an attribute, the default from the default preset will be used.

dimthe desired number of dimensions for the layout. dim=2 means a 2D layout, dim=3 means a 3D layout.
Returns
the calculated layout.
def layout_fruchterman_reingold(weights=None, niter=500, seed=None, start_temp=None, minx=None, maxx=None, miny=None, maxy=None, minz=None, maxz=None, grid='auto'):

Places the vertices on a 2D plane according to the Fruchterman-Reingold algorithm.

This is a force directed layout, see Fruchterman, T. M. J. and Reingold, E. M.: Graph Drawing by Force-directed Placement. Software -- Practice and Experience, 21/11, 1129--1164, 1991

Parameters
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
niterthe number of iterations to perform. The default is 500.
seedif None, uses a random starting layout for the algorithm. If a matrix (list of lists), uses the given matrix as the starting position.
start_tempReal scalar, the start temperature. This is the maximum amount of movement alloved along one axis, within one step, for a vertex. Currently it is decreased linearly to zero during the iteration. The default is the square root of the number of vertices divided by 10.
minxif not None, it must be a vector with exactly as many elements as there are vertices in the graph. Each element is a minimum constraint on the X value of the vertex in the layout.
maxxsimilar to minx, but with maximum constraints
minysimilar to minx, but with the Y coordinates
maxysimilar to maxx, but with the Y coordinates
minzsimilar to minx, but with the Z coordinates. Use only for 3D layouts (dim=3).
maxzsimilar to maxx, but with the Z coordinates. Use only for 3D layouts (dim=3).
gridwhether to use a faster, but less accurate grid-based implementation of the algorithm. "auto" decides based on the number of vertices in the graph; a grid will be used if there are at least 1000 vertices. "grid" is equivalent to True, "nogrid" is equivalent to False.
Returns
the calculated layout.
def layout_graphopt(niter=500, node_charge=0.001, node_mass=30, spring_length=0, spring_constant=1, max_sa_movement=5, seed=None):

This is a port of the graphopt layout algorithm by Michael Schmuhl. graphopt version 0.4.1 was rewritten in C and the support for layers was removed.

graphopt uses physical analogies for defining attracting and repelling forces among the vertices and then the physical system is simulated until it reaches an equilibrium or the maximal number of iterations is reached.

See http://www.schmuhl.org/graphopt/ for the original graphopt.

Parameters
niterthe number of iterations to perform. Should be a couple of hundred in general.
node_chargethe charge of the vertices, used to calculate electric repulsion.
node_massthe mass of the vertices, used for the spring forces
spring_lengththe length of the springs
spring_constantthe spring constant
max_sa_movementthe maximum amount of movement allowed in a single step along a single axis.
seeda matrix containing a seed layout from which the algorithm will be started. If None, a random layout will be used.
Returns
the calculated layout.
def layout_grid(width=0, height=0, dim=2):

Places the vertices of a graph in a 2D or 3D grid.

Parameters
widththe number of vertices in a single row of the layout. Zero or negative numbers mean that the width should be determined automatically.
heightthe number of vertices in a single column of the layout. Zero or negative numbers mean that the height should be determined automatically. It must not be given if the number of dimensions is 2.
dimthe desired number of dimensions for the layout. dim=2 means a 2D layout, dim=3 means a 3D layout.
Returns
the calculated layout.
def layout_kamada_kawai(maxiter=1000, epsilon=0, kkconst=None, seed=None, minx=None, maxx=None, miny=None, maxy=None, minz=None, maxz=None, dim=2):

Places the vertices on a plane according to the Kamada-Kawai algorithm.

This is a force directed layout, see Kamada, T. and Kawai, S.: An Algorithm for Drawing General Undirected Graphs. Information Processing Letters, 31/1, 7--15, 1989.

Parameters
maxiterthe maximum number of iterations to perform.
epsilonquit if the energy of the system changes less than epsilon. See the original paper for details.
kkconstthe Kamada-Kawai vertex attraction constant. None means the square of the number of vertices.
seedif None, uses a random starting layout for the algorithm. If a matrix (list of lists), uses the given matrix as the starting position.
minxif not None, it must be a vector with exactly as many elements as there are vertices in the graph. Each element is a minimum constraint on the X value of the vertex in the layout.
maxxsimilar to minx, but with maximum constraints
minysimilar to minx, but with the Y coordinates
maxysimilar to maxx, but with the Y coordinates
minzsimilar to minx, but with the Z coordinates. Use only for 3D layouts (dim=3).
maxzsimilar to maxx, but with the Z coordinates. Use only for 3D layouts (dim=3).
dimthe desired number of dimensions for the layout. dim=2 means a 2D layout, dim=3 means a 3D layout.
Returns
the calculated layout.
def layout_lgl(maxiter=150, maxdelta=-1, area=-1, coolexp=1.5, repulserad=-1, cellsize=-1, root=None):

Places the vertices on a 2D plane according to the Large Graph Layout.

Parameters
maxiterthe number of iterations to perform.
maxdeltathe maximum distance to move a vertex in an iteration. If negative, defaults to the number of vertices.
areathe area of the square on which the vertices will be placed. If negative, defaults to the number of vertices squared.
coolexpthe cooling exponent of the simulated annealing.
repulseraddetermines the radius at which vertex-vertex repulsion cancels out attraction of adjacent vertices. If negative, defaults to area times the number of vertices.
cellsizethe size of the grid cells. When calculating the repulsion forces, only vertices in the same or neighboring grid cells are taken into account. Defaults to the fourth root of area.
rootthe root vertex, this is placed first, its neighbors in the first iteration, second neighbors in the second, etc. None means that a random vertex will be chosen.
Returns
the calculated layout.
def layout_mds(dist=None, dim=2, arpack_options=None):

Places the vertices in an Euclidean space with the given number of dimensions using multidimensional scaling.

This layout requires a distance matrix, where the intersection of row i and column j specifies the desired distance between vertex i and vertex j. The algorithm will try to place the vertices in a way that approximates the distance relations prescribed in the distance matrix. igraph uses the classical multidimensional scaling by Torgerson (see reference below).

For unconnected graphs, the method will decompose the graph into weakly connected components and then lay out the components individually using the appropriate parts of the distance matrix.

Parameters
distthe distance matrix. It must be symmetric and the symmetry is not checked -- results are unspecified when a non-symmetric distance matrix is used. If this parameter is None, the shortest path lengths will be used as distances. Directed graphs are treated as undirected when calculating the shortest path lengths to ensure symmetry.
dimthe number of dimensions. For 2D layouts, supply 2 here; for 3D layouts, supply 3.
arpack_optionsan ARPACKOptions object used to fine-tune the ARPACK eigenvector calculation. If omitted, the module-level variable called arpack_options is used.
Returns
the calculated layout.
Unknown Field: newfield
refReference
Unknown Field: ref
Cox & Cox: Multidimensional Scaling (1994), Chapman and Hall, London.
def layout_random(dim=2):

Places the vertices of the graph randomly.

Parameters
dimthe desired number of dimensions for the layout. dim=2 means a 2D layout, dim=3 means a 3D layout.
Returns
the coordinate pairs in a list.
def layout_reingold_tilford(mode='out', root=None, rootlevel=None):

Places the vertices on a 2D plane according to the Reingold-Tilford layout algorithm.

This is a tree layout. If the given graph is not a tree, a breadth-first search is executed first to obtain a possible spanning tree.

Parameters
modespecifies which edges to consider when builing the tree. If it is OUT then only the outgoing, if it is IN then only the incoming edges of a parent are considered. If it is ALL then all edges are used (this was the behaviour in igraph 0.5 and before). This parameter also influences how the root vertices are calculated if they are not given. See the root parameter.
rootthe index of the root vertex or root vertices. if this is a non-empty vector then the supplied vertex IDs are used as the roots of the trees (or a single tree if the graph is connected. If this is None or an empty list, the root vertices are automatically calculated based on topological sorting, performed with the opposite of the mode argument.
rootlevelthis argument is useful when drawing forests which are not trees. It specifies the level of the root vertices for every tree in the forest.
Returns
the calculated layout.
See Also
layout_reingold_tilford_circular
Unknown Field: newfield
refReference
Unknown Field: ref
EM Reingold, JS Tilford: Tidier Drawings of Trees. IEEE Transactions on Software Engineering 7:22, 223-228, 1981.
def layout_reingold_tilford_circular(mode='out', root=None, rootlevel=None):

Circular Reingold-Tilford layout for trees.

This layout is similar to the Reingold-Tilford layout, but the vertices are placed in a circular way, with the root vertex in the center.

See layout_reingold_tilford for the explanation of the parameters.

Returns
the calculated layout.
See Also
layout_reingold_tilford
Unknown Field: newfield
refReference
Unknown Field: ref
EM Reingold, JS Tilford: Tidier Drawings of Trees. IEEE Transactions on Software Engineering 7:22, 223-228, 1981.
def layout_star(center=0, order=None):

Calculates a star-like layout for the graph.

Parameters
centerthe ID of the vertex to put in the center
ordera numeric vector giving the order of the vertices (including the center vertex!). If it is None, the vertices will be placed in increasing vertex ID order.
Returns
the calculated layout.
def LCF(n, shifts, repeats):

Generates a graph from LCF notation.

LCF is short for Lederberg-Coxeter-Frucht, it is a concise notation for 3-regular Hamiltonian graphs. It consists of three parameters, the number of vertices in the graph, a list of shifts giving additional edges to a cycle backbone and another integer giving how many times the shifts should be performed. See http://mathworld.wolfram.com/LCFNotation.html for details.

Parameters
nthe number of vertices
shiftsthe shifts in a list or tuple
repeatsthe number of repeats
def linegraph():

Returns the line graph of the graph.

The line graph L(G) of an undirected graph is defined as follows: L(G) has one vertex for each edge in G and two vertices in L(G) are connected iff their corresponding edges in the original graph share an end point.

The line graph of a directed graph is slightly different: two vertices are connected by a directed edge iff the target of the first vertex's corresponding edge is the same as the source of the second vertex's corresponding edge.

def maxdegree(vertices=None, mode='all', loops=False):

Returns the maximum degree of a vertex set in the graph.

This method accepts a single vertex ID or a list of vertex IDs as a parameter, and returns the degree of the given vertices (in the form of a single integer or a list, depending on the input parameter).

Parameters
verticesa single vertex ID or a list of vertex IDs, or None meaning all the vertices in the graph.
modethe type of degree to be returned ("out" for out-degrees, "in" IN for in-degrees or "all" for the sum of them).
loopswhether self-loops should be counted.
def maxflow(source, target, capacity=None):
overridden in igraph.Graph

Returns the maximum flow between the source and target vertices.

Parameters
sourcethe source vertex ID
targetthe target vertex ID
capacitythe capacity of the edges. It must be a list or a valid attribute name or None. In the latter case, every edge will have the same capacity.
Returns
a tuple containing the following: the value of the maximum flow between the given vertices, the flow value on all the edges, the edge IDs that are part of the corresponding minimum cut, and the vertex IDs on one side of the cut. For directed graphs, the flow value vector gives the flow value on each edge. For undirected graphs, the flow value is positive if the flow goes from the smaller vertex ID to the bigger one and negative if the flow goes from the bigger vertex ID to the smaller.
Unknown Field: attention
this function has a more convenient interface in class Graph which wraps the result in a Flow object. It is advised to use that.
def maxflow_value(source, target, capacity=None):

Returns the value of the maximum flow between the source and target vertices.

Parameters
sourcethe source vertex ID
targetthe target vertex ID
capacitythe capacity of the edges. It must be a list or a valid attribute name or None. In the latter case, every edge will have the same capacity.
Returns
the value of the maximum flow between the given vertices
def maximal_cliques(min=0, max=0, file=None):

Returns the maximal cliques of the graph as a list of tuples.

A maximal clique is a clique which can't be extended by adding any other vertex to it. A maximal clique is not necessarily one of the largest cliques in the graph.

Parameters
minthe minimum size of maximal cliques to be returned. If zero or negative, no lower bound will be used.
maxthe maximum size of maximal cliques to be returned. If zero or negative, no upper bound will be used. If nonzero, the size of every maximal clique found will be compared to this value and a clique will be returned only if its size is smaller than this limit.
filea file object or the name of the file to write the results to. When this argument is None, the maximal cliques will be returned as a list of lists.
Returns
the maximal cliques of the graph as a list of lists, or None if the file argument was given.@see: largest_cliques() for the largest cliques.
def maximal_independent_vertex_sets():

Returns the maximal independent vertex sets of the graph as a list of tuples.

A maximal independent vertex set is an independent vertex set which can't be extended by adding any other vertex to it. A maximal independent vertex set is not necessarily one of the largest independent vertex sets in the graph.

See Also
largest_independent_vertex_sets() for the largest independent vertex sets
Unknown Field: newfield
refReference
Unknown Field: ref
S. Tsukiyama, M. Ide, H. Ariyoshi and I. Shirawaka: A new algorithm for generating all the maximal independent sets. SIAM J Computing, 6:505--517, 1977.
def maximum_cardinality_search():

Conducts a maximum cardinality search on the graph. The function computes a rank alpha for each vertex such that visiting vertices in decreasing rank order corresponds to always choosing the vertex with the most already visited neighbors as the next one to visit.

Maximum cardinality search is useful in deciding the chordality of a graph: a graph is chordal if and only if any two neighbors of a vertex that are higher in rank than the original vertex are connected to each other.

The result of this function can be passed to is_chordal() to speed up the chordality computation if you also need the result of the maximum cardinality search for other purposes.

Returns
a tuple consisting of the rank vector and its inverse.
def mincut(source=None, target=None, capacity=None):
overridden in igraph.Graph

Calculates the minimum cut between the source and target vertices or within the whole graph.

The minimum cut is the minimum set of edges that needs to be removed to separate the source and the target (if they are given) or to disconnect the graph (if the source and target are not given). The minimum is calculated using the weights (capacities) of the edges, so the cut with the minimum total capacity is calculated. For undirected graphs and no source and target, the method uses the Stoer-Wagner algorithm. For a given source and target, the method uses the push-relabel algorithm; see the references below.

Parameters
sourcethe source vertex ID. If None, target must also be {None} and the calculation will be done for the entire graph (i.e. all possible vertex pairs).
targetthe target vertex ID. If None, source must also be {None} and the calculation will be done for the entire graph (i.e. all possible vertex pairs).
capacitythe capacity of the edges. It must be a list or a valid attribute name or None. In the latter case, every edge will have the same capacity.
Returns
the value of the minimum cut, the IDs of vertices in the first and second partition, and the IDs of edges in the cut, packed in a 4-tuple
Unknown Field: attention
this function has a more convenient interface in class Graph which wraps the result in a Cut object. It is advised to use that.
Unknown Field: newfield
refReference
Unknown Field: ref
M. Stoer, F. Wagner: A simple min-cut algorithm. Journal of the ACM 44(4):585-591, 1997.
A. V. Goldberg, R. E. Tarjan: A new approach to the maximum-flow problem. Journal of the ACM 35(4):921-940, 1988.
def mincut_value(source=-1, target=-1, capacity=None):

Returns the minimum cut between the source and target vertices or within the whole graph.

Parameters
sourcethe source vertex ID. If negative, the calculation is done for every vertex except the target and the minimum is returned.
targetthe target vertex ID. If negative, the calculation is done for every vertex except the source and the minimum is returned.
capacitythe capacity of the edges. It must be a list or a valid attribute name or None. In the latter case, every edge will have the same capacity.
Returns
the value of the minimum cut between the given vertices
def minimum_size_separators():

Returns a list containing all separator vertex sets of minimum size.

A vertex set is a separator if its removal disconnects the graph. This method lists all the separators for which no smaller separator set exists in the given graph.

Returns
a list where each item lists the vertex indices of a given separator of minimum size.
Unknown Field: newfield
refReference
Unknown Field: ref
Arkady Kanevsky: Finding all minimum-size separating vertex sets in a graph. Networks 23:533--541, 1993.
def modularity(membership, weights=None, resolution=1, directed=True):
overridden in igraph.Graph

Calculates the modularity of the graph with respect to some vertex types.

The modularity of a graph w.r.t. some division measures how good the division is, or how separated are the different vertex types from each other. It is defined as Q = 1 ⁄ (2m)*sum(Aij − gamma*ki*kj ⁄ (2m)delta(ci, cj), i, j). m is the number of edges, Aij is the element of the A adjacency matrix in row i and column j, ki is the degree of node i, kj is the degree of node j, Ci and cj are the types of the two vertices (i and j), and gamma is a resolution parameter that defaults to 1 for the classical definition of modularity. delta(x, y) is one iff x = y, 0 otherwise.

If edge weights are given, the definition of modularity is modified as follows: Aij becomes the weight of the corresponding edge, ki is the total weight of edges incident on vertex i, kj is the total weight of edges incident on vertex j and m is the total edge weight in the graph.

Parameters
membershipthe membership vector, e.g. the vertex type index for each vertex.
weightsoptional edge weights or None if all edges are weighed equally.
resolutionthe resolution parameter gamma in the formula above. The classical definition of modularity is retrieved when the resolution parameter is set to 1.
directedwhether to consider edge directions if the graph is directed. True will use the directed variant of the modularity measure where the in- and out-degrees of nodes are treated separately; False will treat directed graphs as undirected.
Returns
the modularity score. Score larger than 0.3 usually indicates strong community structure.
Unknown Field: attention
method overridden in Graph to allow VertexClustering objects as a parameter. This method is not strictly necessary, since the VertexClustering class provides a variable called modularity.
Unknown Field: newfield
refReference
Unknown Field: ref
MEJ Newman and M Girvan: Finding and evaluating community structure in networks. Phys Rev E 69 026113, 2004.
def motifs_randesu(size=3, cut_prob=None, callback=None):

Counts the number of motifs in the graph

Motifs are small subgraphs of a given structure in a graph. It is argued that the motif profile (ie. the number of different motifs in the graph) is characteristic for different types of networks and network function is related to the motifs in the graph.

This function is able to find the different motifs of size three and four (ie. the number of different subgraphs with three and four vertices) in the network.

In a big network the total number of motifs can be very large, so it takes a lot of time to find all of them. In such cases, a sampling method can be used. This function is capable of doing sampling via the cut_prob argument. This argument gives the probability that a branch of the motif search tree will not be explored.

Parameters
sizethe size of the motifs (3 or 4).
cut_probthe cut probabilities for different levels of the search tree. This must be a list of length size or None to find all motifs.
callbackNone or a callable that will be called for every motif found in the graph. The callable must accept three parameters: the graph itself, the list of vertices in the motif and the isomorphism class of the motif (see isoclass()). The search will stop when the callback returns an object with a non-zero truth value or raises an exception.
Returns
the list of motifs if callback is None, or None otherwise
See Also
Graph.motifs_randesu_no()
Unknown Field: newfield
refReference
Unknown Field: ref
S. Wernicke and F. Rasche: FANMOD: a tool for fast network motif detection, Bioinformatics 22(9), 1152--1153, 2006.
def motifs_randesu_estimate(size=3, cut_prob=None, sample=None):

Counts the total number of motifs in the graph

Motifs are small subgraphs of a given structure in a graph. This function estimates the total number of motifs in a graph without assigning isomorphism classes to them by extrapolating from a random sample of vertices.

Parameters
sizethe size of the motifs (3 or 4).
cut_probthe cut probabilities for different levels of the search tree. This must be a list of length size or None to find all motifs.
samplethe size of the sample or the vertex IDs of the vertices to be used for sampling.
See Also
Graph.motifs_randesu()
Unknown Field: newfield
refReference
Unknown Field: ref
S. Wernicke and F. Rasche: FANMOD: a tool for fast network motif detection, Bioinformatics 22(9), 1152--1153, 2006.
def motifs_randesu_no(size=3, cut_prob=None):

Counts the total number of motifs in the graph

Motifs are small subgraphs of a given structure in a graph. This function counts the total number of motifs in a graph without assigning isomorphism classes to them.

Parameters
sizethe size of the motifs (3 or 4).
cut_probthe cut probabilities for different levels of the search tree. This must be a list of length size or None to find all motifs.
See Also
Graph.motifs_randesu()
Unknown Field: newfield
refReference
Unknown Field: ref
S. Wernicke and F. Rasche: FANMOD: a tool for fast network motif detection, Bioinformatics 22(9), 1152--1153, 2006.
def neighborhood(vertices=None, order=1, mode='all', mindist=0):

For each vertex specified by vertices, returns the vertices reachable from that vertex in at most order steps. If mindist is larger than zero, vertices that are reachable in less than mindist steps are excluded.

Parameters
verticesa single vertex ID or a list of vertex IDs, or None meaning all the vertices in the graph.
orderthe order of the neighborhood, i.e. the maximum number of steps to take from the seed vertex.
modespecifies how to take into account the direction of the edges if a directed graph is analyzed. "out" means that only the outgoing edges are followed, so all vertices reachable from the source vertex in at most order steps are counted. "in" means that only the incoming edges are followed (in reverse direction of course), so all vertices from which the source vertex is reachable in at most order steps are counted. "all" treats directed edges as undirected.
mindistthe minimum distance required to include a vertex in the result. If this is one, the seed vertex is not included. If this is two, the direct neighbors of the seed vertex are not included either, and so on.
Returns
a single list specifying the neighborhood if vertices was an integer specifying a single vertex index, or a list of lists if vertices was a list or None.
def neighborhood_size(vertices=None, order=1, mode='all', mindist=0):

For each vertex specified by vertices, returns the number of vertices reachable from that vertex in at most order steps. If mindist is larger than zero, vertices that are reachable in less than mindist steps are excluded.

Parameters
verticesa single vertex ID or a list of vertex IDs, or None meaning all the vertices in the graph.
orderthe order of the neighborhood, i.e. the maximum number of steps to take from the seed vertex.
modespecifies how to take into account the direction of the edges if a directed graph is analyzed. "out" means that only the outgoing edges are followed, so all vertices reachable from the source vertex in at most order steps are counted. "in" means that only the incoming edges are followed (in reverse direction of course), so all vertices from which the source vertex is reachable in at most order steps are counted. "all" treats directed edges as undirected.
mindistthe minimum distance required to include a vertex in the result. If this is one, the seed vertex is not counted. If this is two, the direct neighbors of the seed vertex are not counted either, and so on.
Returns
a single number specifying the neighborhood size if vertices was an integer specifying a single vertex index, or a list of sizes if vertices was a list or None.
def neighbors(vertex, mode='all'):

Returns adjacent vertices to a given vertex.

Parameters
vertexa vertex ID
modewhether to return only successors ("out"), predecessors ("in") or both ("all"). Ignored for undirected graphs.
def path_length_hist(directed=True):
overridden in igraph.Graph

Calculates the path length histogram of the graph

Parameters
directedwhether to consider directed paths
Returns
a tuple. The first item of the tuple is a list of path lengths, the ith element of the list contains the number of paths with length i + 1. The second item contains the number of unconnected vertex pairs as a float (since it might not fit into an integer)
Unknown Field: attention
this function is wrapped in a more convenient syntax in the derived class Graph. It is advised to use that instead of this version.
def permute_vertices(permutation):

Permutes the vertices of the graph according to the given permutation and returns the new graph.

Vertex k of the original graph will become vertex permutation[k] in the new graph. No validity checks are performed on the permutation vector.

Returns
the new graph
def personalized_pagerank(vertices=None, directed=True, damping=0.85, reset=None, reset_vertices=None, weights=None, arpack_options=None, implementation='prpack', niter=1000, eps=0.001):

Calculates the personalized PageRank values of a graph.

The personalized PageRank calculation is similar to the PageRank calculation, but the random walk is reset to a non-uniform distribution over the vertices in every step with probability 1 − damping instead of a uniform distribution.

Parameters
verticesthe indices of the vertices being queried. None means all of the vertices.
directedwhether to consider directed paths.
dampingthe damping factor. 1 − damping is the PageRank value for vertices with no incoming links.
resetthe distribution over the vertices to be used when resetting the random walk. Can be a sequence, an iterable or a vertex attribute name as long as they return a list of floats whose length is equal to the number of vertices. If None, a uniform distribution is assumed, which makes the method equivalent to the original PageRank algorithm.
reset_verticesan alternative way to specify the distribution over the vertices to be used when resetting the random walk. Simply supply a list of vertex IDs here, or a VertexSeq or a Vertex. Resetting will take place using a uniform distribution over the specified vertices.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
arpack_optionsan ARPACKOptions object used to fine-tune the ARPACK eigenvector calculation. If omitted, the module-level variable called arpack_options is used. This argument is ignored if not the ARPACK implementation is used, see the implementation argument.
implementation

which implementation to use to solve the PageRank eigenproblem. Possible values are:

  • "prpack": use the PRPACK library. This is a new implementation in igraph 0.7
  • "arpack": use the ARPACK library. This implementation was used from version 0.5, until version 0.7.
  • "power": use a simple power method. This is the implementation that was used before igraph version 0.5.
niterThe number of iterations to use in the power method implementation. It is ignored in the other implementations.
epsThe power method implementation will consider the calculation as complete if the difference of PageRank values between iterations change less than this value for every node. It is ignored by the other implementations.
Returns
a list with the personalized PageRank values of the specified vertices.
def predecessors(vertex):

Returns the predecessors of a given vertex.

Equivalent to calling the neighbors() method with type="in".

def Preference(n, type_dist, pref_matrix, attribute=None, directed=False, loops=False):

Generates a graph based on vertex types and connection probabilities.

This is practically the nongrowing variant of Establishment. A given number of vertices are generated. Every vertex is assigned to a vertex type according to the given type probabilities. Finally, every vertex pair is evaluated and an edge is created between them with a probability depending on the types of the vertices involved.

Parameters
nthe number of vertices in the graph
type_distlist giving the distribution of vertex types
pref_matrixmatrix giving the connection probabilities for different vertex types.
attributethe vertex attribute name used to store the vertex types. If None, vertex types are not stored.
directedwhether to generate a directed graph.
loopswhether loop edges are allowed.
def radius(mode='out'):

Calculates the radius of the graph.

The radius of a graph is defined as the minimum eccentricity of its vertices (see eccentricity()).

Parameters
modewhat kind of paths to consider for the calculation in case of directed graphs. OUT considers paths that follow edge directions, IN considers paths that follow the opposite edge directions, ALL ignores edge directions. The argument is ignored for undirected graphs.
Returns
the radius
See Also
eccentricity()
def random_walk(start, steps, mode='out', stuck='return'):

Performs a random walk of a given length from a given node.

Parameters
startthe starting vertex of the walk
stepsthe number of steps that the random walk should take
modewhether to follow outbound edges only ("out"), inbound edges only ("in") or both ("all"). Ignored for undirected graphs.@param stuck: what to do when the random walk gets stuck. "return" returns a partial random walk; "error" throws an exception.
stuckUndocumented
Returns
a random walk that starts from the given vertex and has at most the given length (shorter if the random walk got stuck)
def Read_DIMACS(f, directed=False):
overridden in igraph.Graph

Reads a graph from a file conforming to the DIMACS minimum-cost flow file format.

For the exact description of the format, see http://lpsolve.sourceforge.net/5.5/DIMACS.htm

Restrictions compared to the official description of the format:

  • igraph's DIMACS reader requires only three fields in an arc definition, describing the edge's source and target node and its capacity.
  • Source vertices are identified by 's' in the FLOW field, target vertices are identified by 't'.
  • Node indices start from 1. Only a single source and target node is allowed.
Parameters
fthe name of the file or a Python file handle
directedwhether the generated graph should be directed.
Returns
the generated graph, the source and the target of the flow and the edge capacities in a tuple
def Read_DL(f, directed=True):

Reads an UCINET DL file and creates a graph based on it.

Parameters
fthe name of the file or a Python file handle
directedwhether the generated graph should be directed.
def Read_Edgelist(f, directed=True):

Reads an edge list from a file and creates a graph based on it.

Please note that the vertex indices are zero-based. A vertex of zero degree will be created for every integer that is in range but does not appear in the edgelist.

Parameters
fthe name of the file or a Python file handle
directedwhether the generated graph should be directed.
def Read_GML(f):

Reads a GML file and creates a graph based on it.

Parameters
fthe name of the file or a Python file handle
def Read_GraphDB(f, directed=False):

Reads a GraphDB format file and creates a graph based on it.

GraphDB is a binary format, used in the graph database for isomorphism testing (see http://amalfi.dis.unina.it/graph/).

Parameters
fthe name of the file or a Python file handle
directedwhether the generated graph should be directed.
def Read_GraphML(f, directed=True, index=0):

Reads a GraphML format file and creates a graph based on it.

Parameters
fthe name of the file or a Python file handle
directedUndocumented
indexif the GraphML file contains multiple graphs, specifies the one that should be loaded. Graph indices start from zero, so if you want to load the first graph, specify 0 here.
def Read_Lgl(f, names=True, weights='if_present', directed=True):

Reads an .lgl file used by LGL.

It is also useful for creating graphs from "named" (and optionally weighted) edge lists.

This format is used by the Large Graph Layout program. See the documentation of LGL regarding the exact format description.

LGL originally cannot deal with graphs containing multiple or loop edges, but this condition is not checked here, as igraph is happy with these.

Parameters
fthe name of the file or a Python file handle
namesIf True, the vertex names are added as a vertex attribute called 'name'.
weightsIf True, the edge weights are added as an edge attribute called 'weight', even if there are no weights in the file. If False, the edge weights are never added, even if they are present. "auto" or "if_present" means that weights are added if there is at least one weighted edge in the input file, but they are not added otherwise.
directedwhether the graph being created should be directed
def Read_Ncol(f, names=True, weights='if_present', directed=True):

Reads an .ncol file used by LGL.

It is also useful for creating graphs from "named" (and optionally weighted) edge lists.

This format is used by the Large Graph Layout program. See the repository of LGL for more information.

LGL originally cannot deal with graphs containing multiple or loop edges, but this condition is not checked here, as igraph is happy with these.

Parameters
fthe name of the file or a Python file handle
namesIf True, the vertex names are added as a vertex attribute called 'name'.
weightsIf True, the edge weights are added as an edge attribute called 'weight', even if there are no weights in the file. If False, the edge weights are never added, even if they are present. "auto" or "if_present" means that weights are added if there is at least one weighted edge in the input file, but they are not added otherwise.
directedwhether the graph being created should be directed
def Read_Pajek(f):

Reads a Pajek format file and creates a graph based on it.

Parameters
fthe name of the file or a Python file handle
def Realize_Degree_Sequence(out, in_=None, allowed_edge_types='simple', method='smallest'):

Generates a graph from a degree sequence.

This method implements a Havel-Hakimi style graph construction from a given degree sequence. In each step, the algorithm picks two vertices in a deterministic manner and connects them. The way the vertices are picked is defined by the method parameter. The allowed edge types (i.e. whether multiple or loop edges are allowed) are specified in the allowed_edge_types parameter.

Parameters
outUndocumented
in_Undocumented
allowed_edge_types

controls whether loops or multi-edges are allowed during the generation process. Note that not all combinations are supported for all types of graphs; an exception will be raised for unsupported combinations. Possible values are:

  • "simple": simple graphs (no self-loops, no multi-edges)
  • "loops": single self-loops allowed, but not multi-edges
  • "multi": multi-edges allowed, but not self-loops
  • "all": multi-edges and self-loops allowed
method

controls how the vertices are selected during the generation process. Possible values are:

  • smallest: The vertex with smallest remaining degree first.
  • largest: The vertex with the largest remaining degree first.
  • index: The vertices are selected in order of their index.
outdegthe degree sequence of an undirected graph (if indeg=None), or the out-degree sequence of a directed graph.
indegNone to generate an undirected graph, the in-degree sequence to generate a directed graph.
def Recent_Degree(n, m, window, outpref=False, directed=False, power=1):

Generates a graph based on a stochastic model where the probability of an edge gaining a new node is proportional to the edges gained in a given time window.

Parameters
nthe number of vertices
meither the number of outgoing edges generated for each vertex or a list containing the number of outgoing edges for each vertex explicitly.
windowsize of the window in time steps
outprefTrue if the out-degree of a given vertex should also increase its citation probability (as well as its in-degree), but it defaults to False.
directedTrue if the generated graph should be directed (default: False).
powerthe power constant of the nonlinear model. It can be omitted, and in this case the usual linear model will be used.
def reciprocity(ignore_loops=True, mode='default'):

Reciprocity defines the proportion of mutual connections in a directed graph. It is most commonly defined as the probability that the opposite counterpart of a directed edge is also included in the graph. This measure is calculated if mode is "default".

Prior to igraph 0.6, another measure was implemented, defined as the probability of mutual connection between a vertex pair if we know that there is a (possibly non-mutual) connection between them. In other words, (unordered) vertex pairs are classified into three groups: (1) disconnected, (2) non-reciprocally connected and (3) reciprocally connected. The result is the size of group (3), divided by the sum of sizes of groups (2) and (3). This measure is calculated if mode is "ratio".

Parameters
ignore_loopswhether loop edges should be ignored.
modethe algorithm to use to calculate the reciprocity; see above for more details.
Returns
the reciprocity of the graph
def rewire(n=1000, mode='simple'):

Randomly rewires the graph while preserving the degree distribution.

Please note that the rewiring is done "in-place", so the original graph will be modified. If you want to preserve the original graph, use the copy method before.

Parameters
nthe number of rewiring trials.
modethe rewiring algorithm to use. It can either be "simple" or "loops"; the former does not create or destroy loop edges while the latter does.
def rewire_edges(prob, loops=False, multiple=False):

Rewires the edges of a graph with constant probability.

Each endpoint of each edge of the graph will be rewired with a constant probability, given in the first argument.

Please note that the rewiring is done "in-place", so the original graph will be modified. If you want to preserve the original graph, use the copy method before.

Parameters
probrewiring probability
loopswhether the algorithm is allowed to create loop edges
multiplewhether the algorithm is allowed to create multiple edges.
def Ring(n, directed=False, mutual=False, circular=True):

Generates a ring graph.

Parameters
nthe number of vertices in the ring
directedwhether to create a directed ring.
mutualwhether to create mutual edges in a directed ring.
circularwhether to create a closed ring.
def SBM(n, pref_matrix, block_sizes, directed=False, loops=False):

Generates a graph based on a stochastic blockmodel.

A given number of vertices are generated. Every vertex is assigned to a vertex type according to the given block sizes. Vertices of the same type will be assigned consecutive vertex IDs. Finally, every vertex pair is evaluated and an edge is created between them with a probability depending on the types of the vertices involved. The probabilities are taken from the preference matrix.

Parameters
nthe number of vertices in the graph
pref_matrixmatrix giving the connection probabilities for different vertex types.
block_sizeslist giving the number of vertices in each block; must sum up to n.
directedwhether to generate a directed graph.
loopswhether loop edges are allowed.
def shortest_paths(source=None, target=None, weights=None, mode='out'):

Calculates shortest path lengths for given vertices in a graph.

The algorithm used for the calculations is selected automatically: a simple BFS is used for unweighted graphs, Dijkstra's algorithm is used when all the weights are positive. Otherwise, the Bellman-Ford algorithm is used if the number of requested source vertices is larger than 100 and Johnson's algorithm is used otherwise.

Parameters
sourcea list containing the source vertex IDs which should be included in the result. If None, all vertices will be considered.
targeta list containing the target vertex IDs which should be included in the result. If None, all vertices will be considered.
weightsa list containing the edge weights. It can also be an attribute name (edge weights are retrieved from the given attribute) or None (all edges have equal weight).
modethe type of shortest paths to be used for the calculation in directed graphs. "out" means only outgoing, "in" means only incoming paths. "all" means to consider the directed graph as an undirected one.
Returns
the shortest path lengths for given vertices in a matrix
def similarity_dice(vertices=None, pairs=None, mode='all', loops=True):

Dice similarity coefficient of vertices.

The Dice similarity coefficient of two vertices is twice the number of their common neighbors divided by the sum of their degrees. This coefficient is very similar to the Jaccard coefficient, but usually gives higher similarities than its counterpart.

Parameters
verticesthe vertices to be analysed. If None and pairs is also None, all vertices will be considered.
pairsthe vertex pairs to be analysed. If this is given, vertices must be None, and the similarity values will be calculated only for the given pairs. Vertex pairs must be specified as tuples of vertex IDs.
modewhich neighbors should be considered for directed graphs. Can be "all", "in" or "out", ignored for undirected graphs.
loopswhether vertices should be considered adjacent to themselves. Setting this to True assumes a loop edge for all vertices even if none is present in the graph. Setting this to False may result in strange results: nonadjacent vertices may have larger similarities compared to the case when an edge is added between them -- however, this might be exactly the result you want to get.
Returns
the pairwise similarity coefficients for the vertices specified, in the form of a matrix if pairs is None or in the form of a list if pairs is not None.
def similarity_inverse_log_weighted(vertices=None, mode='all'):

Inverse log-weighted similarity coefficient of vertices.

Each vertex is assigned a weight which is 1 / log(degree). The log-weighted similarity of two vertices is the sum of the weights of their common neighbors.

Parameters
verticesthe vertices to be analysed. If None, all vertices will be considered.
modewhich neighbors should be considered for directed graphs. Can be "all", "in" or "out", ignored for undirected graphs. "in" means that the weights are determined by the out-degrees, "out" means that the weights are determined by the in-degrees.
Returns
the pairwise similarity coefficients for the vertices specified, in the form of a matrix (list of lists).
def similarity_jaccard(vertices=None, pairs=None, mode='all', loops=True):

Jaccard similarity coefficient of vertices.

The Jaccard similarity coefficient of two vertices is the number of their common neighbors divided by the number of vertices that are adjacent to at least one of them.

Parameters
verticesthe vertices to be analysed. If None and pairs is also None, all vertices will be considered.
pairsthe vertex pairs to be analysed. If this is given, vertices must be None, and the similarity values will be calculated only for the given pairs. Vertex pairs must be specified as tuples of vertex IDs.
modewhich neighbors should be considered for directed graphs. Can be "all", "in" or "out", ignored for undirected graphs.
loopswhether vertices should be considered adjacent to themselves. Setting this to True assumes a loop edge for all vertices even if none is present in the graph. Setting this to False may result in strange results: nonadjacent vertices may have larger similarities compared to the case when an edge is added between them -- however, this might be exactly the result you want to get.
Returns
the pairwise similarity coefficients for the vertices specified, in the form of a matrix if pairs is None or in the form of a list if pairs is not None.
def simplify(multiple=True, loops=True, combine_edges=None):

Simplifies a graph by removing self-loops and/or multiple edges.

For example, suppose you have a graph with an edge attribute named weight. graph.simplify(combine_edges=max) will take the maximum of the weights of multiple edges and assign that weight to the collapsed edge. graph.simplify(combine_edges=sum) will take the sum of the weights. You can also write graph.simplify(combine_edges=dict(weight="sum")) or graph.simplify(combine_edges=dict(weight=sum)), since sum is recognised both as a Python built-in function and as a string constant.

Parameters
multiplewhether to remove multiple edges.
loopswhether to remove loops.
combine_edges

specifies how to combine the attributes of multiple edges between the same pair of vertices into a single attribute. If it is None, only one of the edges will be kept and all the attributes will be lost. If it is a function, the attributes of multiple edges will be collected and passed on to that function which will return the new attribute value that has to be assigned to the single collapsed edge. It can also be one of the following string constants:

  • "ignore": all the edge attributes will be ignored.
  • "sum": the sum of the edge attribute values will be used for the new edge.
  • "product": the product of the edge attribute values will be used for the new edge.
  • "mean": the mean of the edge attribute values will be used for the new edge.
  • "median": the median of the edge attribute values will be used for the new edge.
  • "min": the minimum of the edge attribute values will be used for the new edge.
  • "max": the maximum of the edge attribute values will be used for the new edge.
  • "first": the attribute value of the first edge in the collapsed set will be used for the new edge.
  • "last": the attribute value of the last edge in the collapsed set will be used for the new edge.
  • "random": a randomly selected value will be used for the new edge
  • "concat": the attribute values will be concatenated for the new edge.

You can also use a dict mapping edge attribute names to functions or the above string constants if you want to make the behaviour of the simplification process depend on the name of the attribute. None is a special key in this dict, its value will be used for all the attributes not specified explicitly in the dictionary.

def st_mincut(source, target, capacity=None):
overridden in igraph.Graph

Calculates the minimum cut between the source and target vertices in a graph.

Parameters
sourcethe source vertex ID
targetthe target vertex ID
capacitythe capacity of the edges. It must be a list or a valid attribute name or None. In the latter case, every edge will have the same capacity.
Returns
the value of the minimum cut, the IDs of vertices in the first and second partition, and the IDs of edges in the cut, packed in a 4-tuple
Unknown Field: attention
this function has a more convenient interface in class Graph which wraps the result in a list of Cut objects. It is advised to use that.
def Star(n, mode='undirected', center=0):

Generates a star graph.

Parameters
nthe number of vertices in the graph
modeGives the type of the star graph to create. Should be either "in", "out", "mutual" or "undirected"
centerVertex ID for the central vertex in the star.
def Static_Fitness(m, fitness_out, fitness_in=None, loops=False, multiple=False):

Generates a non-growing graph with edge probabilities proportional to node fitnesses.

The algorithm randomly selects vertex pairs and connects them until the given number of edges are created. Each vertex is selected with a probability proportional to its fitness; for directed graphs, a vertex is selected as a source proportional to its out-fitness and as a target proportional to its in-fitness.

Parameters
mthe number of edges in the graph
fitness_outa numeric vector with non-negative entries, one for each vertex. These values represent the fitness scores (out-fitness scores for directed graphs). fitness is an alias of this keyword argument.
fitness_ina numeric vector with non-negative entries, one for each vertex. These values represent the in-fitness scores for directed graphs. For undirected graphs, this argument must be None.
loopswhether loop edges are allowed.
multiplewhether multiple edges are allowed.
Returns
a directed or undirected graph with the prescribed power-law degree distributions.
def Static_Power_Law(n, m, exponent_out, exponent_in=-1, loops=False, multiple=False, finite_size_correction=True):

Generates a non-growing graph with prescribed power-law degree distributions.

Parameters
nthe number of vertices in the graph
mthe number of edges in the graph
exponent_outthe exponent of the out-degree distribution, which must be between 2 and infinity (inclusive). When exponent_in is not given or negative, the graph will be undirected and this parameter specifies the degree distribution. exponent is an alias to this keyword argument.
exponent_inthe exponent of the in-degree distribution, which must be between 2 and infinity (inclusive) It can also be negative, in which case an undirected graph will be generated.
loopswhether loop edges are allowed.
multiplewhether multiple edges are allowed.
finite_size_correctionwhether to apply a finite-size correction to the generated fitness values for exponents less than 3. See the paper of Cho et al for more details.
Returns
a directed or undirected graph with the prescribed power-law degree distributions.
Unknown Field: newfield
refReference
Unknown Field: ref
Goh K-I, Kahng B, Kim D: Universal behaviour of load distribution in scale-free networks. Phys Rev Lett 87(27):278701, 2001.
Cho YS, Kim JS, Park J, Kahng B, Kim D: Percolation transitions in scale-free networks under the Achlioptas process. Phys Rev Lett 103:135702, 2009.
def strength(vertices, mode='all', loops=True, weights=None):

Returns the strength (weighted degree) of some vertices from the graph

This method accepts a single vertex ID or a list of vertex IDs as a parameter, and returns the strength (that is, the sum of the weights of all incident edges) of the given vertices (in the form of a single integer or a list, depending on the input parameter).

Parameters
verticesa single vertex ID or a list of vertex IDs
modethe type of degree to be returned ("out" for out-degrees, "in" for in-degrees or "all" for the sum of them).
loopswhether self-loops should be counted.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name. ``None`` means to treat the graph as unweighted, falling back to ordinary degree calculations.
def subcomponent(v, mode='all'):

Determines the indices of vertices which are in the same component as a given vertex.

Parameters
vthe index of the vertex used as the source/destination
modeif equals to "in", returns the vertex IDs from where the given vertex can be reached. If equals to "out", returns the vertex IDs which are reachable from the given vertex. If equals to "all", returns all vertices within the same component as the given vertex, ignoring edge directions. Note that this is not equal to calculating the union of the results of "in" and "out".
Returns
the indices of vertices which are in the same component as a given vertex.
def subgraph_edges(edges, delete_vertices=True):

Returns a subgraph spanned by the given edges.

Parameters
edgesa list containing the edge IDs which should be included in the result.
delete_verticesif True, vertices not incident on any of the specified edges will be deleted from the result. If False, all vertices will be kept.
Returns
the subgraph
def subisomorphic_lad(other, domains=None, induced=False, time_limit=0, return_mapping=False):

Checks whether a subgraph of the graph is isomorphic to another graph.

The optional domains argument may be used to restrict vertices that may match each other. You can also specify whether you are interested in induced subgraphs only or not.

Parameters
otherthe pattern graph we are looking for in the graph.
domainsa list of lists, one sublist belonging to each vertex in the template graph. Sublist i contains the indices of the vertices in the original graph that may match vertex i in the template graph. None means that every vertex may match every other vertex.
inducedwhether to consider induced subgraphs only.
time_limitan optimal time limit in seconds. Only the integral part of this number is taken into account. If the time limit is exceeded, the method will throw an exception.
return_mappingwhen True, the function will return a tuple, where the first element is a boolean denoting whether a subisomorphism has been found or not, and the second element describes the mapping of the vertices from the template graph to the original graph. When False, only the boolean is returned.
Returns
if no mapping is calculated, the result is True if the graph contains a subgraph that is isomorphic to the given template, False otherwise. If the mapping is calculated, the result is a tuple, the first element being the above mentioned boolean, and the second element being the mapping from the target to the original graph.
def subisomorphic_vf2(other, color1=None, color2=None, edge_color1=None, edge_color2=None, return_mapping_12=False, return_mapping_21=False, callback=None, node_compat_fn=None, edge_compat_fn=None):

Checks whether a subgraph of the graph is isomorphic to another graph.

Vertex and edge colors may be used to restrict the isomorphisms, as only vertices and edges with the same color will be allowed to match each other.

Parameters
otherthe other graph with which we want to compare the graph.
color1optional vector storing the coloring of the vertices of the first graph. If None, all vertices have the same color.
color2optional vector storing the coloring of the vertices of the second graph. If None, all vertices have the same color.
edge_color1optional vector storing the coloring of the edges of the first graph. If None, all edges have the same color.
edge_color2optional vector storing the coloring of the edges of the second graph. If None, all edges have the same color.
return_mapping_12if True, calculates the mapping which maps the vertices of the first graph to the second. The mapping can contain -1 if a given node is not mapped.
return_mapping_21if True, calculates the mapping which maps the vertices of the second graph to the first. The mapping can contain -1 if a given node is not mapped.
callbackif not None, the subisomorphism search will not stop at the first match; it will call this callback function instead for every subisomorphism found. The callback function must accept four arguments: the first graph, the second graph, a mapping from the nodes of the first graph to the second, and a mapping from the nodes of the second graph to the first. The function must return True if the search should continue or False otherwise.
node_compat_fna function that receives the two graphs and two node indices (one from the first graph, one from the second graph) and returns True if the nodes given by the two indices are compatible (i.e. they could be matched to each other) or False otherwise. This can be used to restrict the set of isomorphisms based on node-specific criteria that are too complicated to be represented by node color vectors (i.e. the color1 and color2 parameters). None means that every node is compatible with every other node.
edge_compat_fna function that receives the two graphs and two edge indices (one from the first graph, one from the second graph) and returns True if the edges given by the two indices are compatible (i.e. they could be matched to each other) or False otherwise. This can be used to restrict the set of isomorphisms based on edge-specific criteria that are too complicated to be represented by edge color vectors (i.e. the edge_color1 and edge_color2 parameters). None means that every edge is compatible with every other node.
Returns
if no mapping is calculated, the result is True if the graph contains a subgraph that's isomorphic to the given one, False otherwise. If any or both mappings are calculated, the result is a 3-tuple, the first element being the above mentioned boolean, the second element being the 1 -> 2 mapping and the third element being the 2 -> 1 mapping. If the corresponding mapping was not calculated, None is returned in the appropriate element of the 3-tuple.
def successors(vertex):

Returns the successors of a given vertex.

Equivalent to calling the neighbors() method with type="out".

def to_directed(mode='mutual'):

Converts an undirected graph to directed.

Parameters
modespecifies how to convert undirected edges into directed ones. True or "mutual" creates a mutual edge pair for each undirected edge. False or "arbitrary" picks an arbitrary (but deterministic) edge direction for each edge. "random" picks a random direction for each edge. "acyclic" picks the edge directions in a way that the resulting graph will be acyclic if there were no self-loops in the original graph.
def to_prufer():

Converts a tree graph into a Prufer sequence.

Returns
the Prufer sequence as a list
def to_undirected(mode='collapse', combine_edges=None):

Converts a directed graph to undirected.

Parameters
modespecifies what to do with multiple directed edges going between the same vertex pair. True or "collapse" means that only a single edge should be created from multiple directed edges. False or "each" means that every edge will be kept (with the arrowheads removed). "mutual" creates one undirected edge for each mutual directed edge pair.
combine_edgesspecifies how to combine the attributes of multiple edges between the same pair of vertices into a single attribute. See simplify() for more details.
def topological_sorting(mode='out'):

Calculates a possible topological sorting of the graph.

Returns a partial sorting and issues a warning if the graph is not a directed acyclic graph.

Parameters
modeif "out", vertices are returned according to the forward topological order -- all vertices come before their successors. If "in", all vertices come before their ancestors.
Returns
a possible topological ordering as a list
def transitivity_avglocal_undirected(mode='nan'):
overridden in igraph.Graph

Calculates the average of the vertex transitivities of the graph.

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 mode parameter.

Note that this measure is different from the global transitivity measure (see transitivity_undirected()) as it simply takes the average local transitivity across the whole network.

Parameters
modedefines how to treat vertices with degree less than two. If TRANSITIVITT_ZERO or "zero", these vertices will have zero transitivity. If TRANSITIVITY_NAN or "nan", these vertices will be excluded from the average.
See Also
transitivity_undirected(), transitivity_local_undirected()
Unknown Field: newfield
refReference
Unknown Field: ref
D. J. Watts and S. Strogatz: Collective dynamics of small-world networks. Nature 393(6884):440-442, 1998.
def transitivity_local_undirected(vertices=None, mode='nan', weights=None):

Calculates the local transitivity (clustering coefficient) of the given vertices in the graph.

The transitivity measures the probability that two neighbors of a vertex are connected. In case of the local transitivity, this probability is calculated separately for each vertex.

Note that this measure is different from the global transitivity measure (see transitivity_undirected()) as it calculates a transitivity value for each vertex individually.

The traditional local transitivity measure applies for unweighted graphs only. When the weights argument is given, this function calculates the weighted local transitivity proposed by Barrat et al (see references).

Parameters
verticesa list containing the vertex IDs which should be included in the result. None means all of the vertices.
modedefines how to treat vertices with degree less than two. If TRANSITIVITT_ZERO or "zero", these vertices will have zero transitivity. If TRANSITIVITY_NAN or "nan", these vertices will have NaN (not a number) as their transitivity.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
Returns
the transitivities for the given vertices in a list
See Also
transitivity_undirected(), transitivity_avglocal_undirected()
Unknown Field: newfield
refReference
Unknown Field: ref
Watts DJ and Strogatz S: Collective dynamics of small-world networks. Nature 393(6884):440-442, 1998.
Barrat A, Barthelemy M, Pastor-Satorras R and Vespignani A: The architecture of complex weighted networks. PNAS 101, 3747 (2004). http://arxiv.org/abs/cond-mat/0311416.
def transitivity_undirected(mode='nan'):

Calculates the global transitivity (clustering coefficient) of the graph.

The transitivity measures the probability that two neighbors of a vertex are connected. More precisely, this is the ratio of the triangles and connected triplets in the graph. The result is a single real number. Directed graphs are considered as undirected ones.

Note that this measure is different from the local transitivity measure (see transitivity_local_undirected()) as it calculates a single value for the whole graph.

Parameters
modeif TRANSITIVITY_ZERO or "zero", the result will be zero if the graph does not have any triplets. If "nan" or TRANSITIVITY_NAN, the result will be NaN (not a number).
Returns
the transitivity
See Also
transitivity_local_undirected(), transitivity_avglocal_undirected()
Unknown Field: newfield
refReference
Unknown Field: ref
S. Wasserman and K. Faust: Social Network Analysis: Methods and Applications. Cambridge: Cambridge University Press, 1994.
def Tree(n, children, type='undirected'):

Generates a tree in which almost all vertices have the same number of children.

Parameters
nthe number of vertices in the graph
childrenthe number of children of a vertex in the graph
typedetermines whether the tree should be directed, and if this is the case, also its orientation. Must be one of "in", "out" and "undirected".
def Tree_Game(n, directed=False, method='lerw'):

Generates a random tree by sampling uniformly from the set of labelled trees with a given number of nodes.

Parameters
nthe number of vertices in the tree
directedwhether the graph should be directed
method

the generation method to be used. One of the following:

  • "prufer" -- samples Prufer sequences uniformly, then converts them to trees
  • "lerw" -- performs a loop-erased random walk on the complete graph to uniformly sample its spanning trees (Wilson's algorithm). This is the default choice as it supports both directed and undirected graphs.
def triad_census():
overridden in igraph.Graph

Triad census, as defined by Davis and Leinhardt

Calculating the triad census means classifying every triplets of vertices in a directed graph. A triplet can be in one of 16 states, these are listed in the documentation of the C interface of igraph.

Unknown Field: attention
this function has a more convenient interface in class Graph which wraps the result in a TriadCensus object. It is advised to use that. The name of the triplet classes are also documented there.
def unfold_tree(sources=None, mode='out'):

Unfolds the graph using a BFS to a tree by duplicating vertices as necessary.

Parameters
sourcesthe source vertices to start the unfolding from. It should be a list of vertex indices, preferably one vertex from each connected component. You can use topological_sorting() to determine a suitable set. A single vertex index is also accepted.
modewhich edges to follow during the BFS. OUT follows outgoing edges, IN follows incoming edges, ALL follows both. Ignored for undirected graphs.
Returns
the unfolded tree graph and a mapping from the new vertex indices to the old ones.
def vcount():

Counts the number of vertices.

Returns
integerthe number of vertices in the graph.
def vertex_attributes():
Returns
the attribute name list of the vertices of the graph
def vertex_connectivity(source=-1, target=-1, checks=True, neighbors='error'):

Calculates the vertex connectivity of the graph or between some vertices.

The vertex connectivity between two given vertices is the number of vertices that have to be removed in order to disconnect the two vertices into two separate components. This is also the number of vertex disjoint directed paths between the vertices (apart from the source and target vertices of course). The vertex connectivity of the graph is the minimal vertex connectivity over all vertex pairs.

This method calculates the vertex connectivity of a given vertex pair if both the source and target vertices are given. If none of them is given (or they are both negative), the overall vertex connectivity is returned.

Parameters
sourcethe source vertex involved in the calculation.
targetthe target vertex involved in the calculation.
checksif the whole graph connectivity is calculated and this is True, igraph performs some basic checks before calculation. If the graph is not strongly connected, then the connectivity is obviously zero. If the minimum degree is one, then the connectivity is also one. These simple checks are much faster than checking the entire graph, therefore it is advised to set this to True. The parameter is ignored if the connectivity between two given vertices is computed.
neighborstells igraph what to do when the two vertices are connected. "error" raises an exception, "infinity" returns infinity, "ignore" ignores the edge.
Returns
the vertex connectivity
def Watts_Strogatz(dim, size, nei, p, loops=False, multiple=False):
Parameters
dimthe dimension of the lattice
sizethe size of the lattice along all dimensions
neivalue giving the distance (number of steps) within which two vertices will be connected.
prewiring probability
loopsspecifies whether loop edges are allowed
multiplespecifies whether multiple edges are allowed
See Also
Lattice(), rewire(), rewire_edges() if more flexibility is needed
Unknown Field: newfield
refReference
Unknown Field: ref
Duncan J Watts and Steven H Strogatz: Collective dynamics of small world networks, Nature 393, 440-442, 1998
def Weighted_Adjacency(matrix, mode='directed', attr='weight', loops=True):
overridden in igraph.Graph

Generates a graph from its adjacency matrix.

Parameters
matrixthe adjacency matrix
mode

the mode to be used. Possible values are:

  • "directed" - the graph will be directed and a matrix element gives the number of edges between two vertices.
  • "undirected" - alias to "max" for convenience.
  • "max" - undirected graph will be created and the number of edges between vertex i and j is max(A(i, j), A(j, i))
  • "min" - like "max", but with min(A(i, j), A(j, i))
  • "plus" - like "max", but with A(i, j) + A(j, i)
  • "upper" - undirected graph with the upper right triangle of the matrix (including the diagonal)
  • "lower" - undirected graph with the lower left triangle of the matrix (including the diagonal)
attrthe name of the edge attribute that stores the edge weights.
loopswhether to include loop edges. When False, the diagonal of the adjacency matrix will be ignored.
def write_dimacs(f, source, target, capacity=None):
overridden in igraph.Graph

Writes the graph in DIMACS format to the given file.

Parameters
fthe name of the file to be written or a Python file handle
sourcethe source vertex ID
targetthe target vertex ID
capacitythe capacities of the edges in a list. If it is not a list, the corresponding edge attribute will be used to retrieve capacities.
def write_dot(f):

Writes the graph in DOT format to the given file.

DOT is the format used by the GraphViz software package.

Parameters
fthe name of the file to be written or a Python file handle
def write_edgelist(f):

Writes the edge list of a graph to a file.

Directed edges are written in (from, to) order.

Parameters
fthe name of the file to be written or a Python file handle
def write_gml(f, creator=None, ids=None):

Writes the graph in GML format to the given file.

Parameters
fthe name of the file to be written or a Python file handle
creatoroptional creator information to be written to the file. If None, the current date and time is added.
idsoptional numeric vertex IDs to use in the file. This must be a list of integers or None. If None, the id attribute of the vertices are used, or if they don't exist, numeric vertex IDs will be generated automatically.
def write_graphml(f):

Writes the graph to a GraphML file.

Parameters
fthe name of the file to be written or a Python file handle
def write_leda(f, names='name', weights='weights'):

Writes the graph to a file in LEDA native format.

The LEDA format supports at most one attribute per vertex and edge. You can specify which vertex and edge attribute you want to use. Note that the name of the attribute is not saved in the LEDA file.

Parameters
fthe name of the file to be written or a Python file handle
namesthe name of the vertex attribute to be stored along with the vertices. It is usually used to store the vertex names (hence the name of the keyword argument), but you may also use a numeric attribute. If you don't want to store any vertex attributes, supply None here.
weightsthe name of the edge attribute to be stored along with the edges. It is usually used to store the edge weights (hence the name of the keyword argument), but you may also use a string attribute. If you don't want to store any edge attributes, supply None here.
def write_lgl(f, names='name', weights='weights', isolates=True):

Writes the edge list of a graph to a file in .lgl format.

Note that multiple edges and/or loops break the LGL software, but igraph does not check for this condition. Unless you know that the graph does not have multiple edges and/or loops, it is wise to call simplify() before saving.

Parameters
fthe name of the file to be written or a Python file handle
namesthe name of the vertex attribute containing the name of the vertices. If you don't want to store vertex names, supply None here.
weightsthe name of the edge attribute containing the weight of the vertices. If you don't want to store weights, supply None here.
isolateswhether to include isolated vertices in the output.
def write_ncol(f, names='name', weights='weights'):

Writes the edge list of a graph to a file in .ncol format.

Note that multiple edges and/or loops break the LGL software, but igraph does not check for this condition. Unless you know that the graph does not have multiple edges and/or loops, it is wise to call simplify() before saving.

Parameters
fthe name of the file to be written or a Python file handle
namesthe name of the vertex attribute containing the name of the vertices. If you don't want to store vertex names, supply None here.
weightsthe name of the edge attribute containing the weight of the vertices. If you don't want to store weights, supply None here.
def write_pajek(f):

Writes the graph in Pajek format to the given file.

Parameters
fthe name of the file to be written or a Python file handle
def __graph_as_capsule(...):

__graph_as_capsule()

Returns the igraph graph encapsulated by the Python object as a PyCapsule

.A PyCapsule is practically a regular C pointer, wrapped in a Python object. This function should not be used directly by igraph users, it is useful only in the case when the underlying igraph object must be passed to other C code through Python.

def __register_destructor(destructor):

Registers a destructor to be called when the object is freed by Python. This function should not be used directly by igraph users.

def _Bipartite(types, edges, directed=False):

Internal function, undocumented.

See Also
Graph.Bipartite()
def _Full_Bipartite(n1, n2, directed=False, loops=False):

Internal function, undocumented.

See Also
Graph.Full_Bipartite()
def _get_all_simple_paths(v, to=None, cutoff=-1, mode='out'):

Internal function, undocumented.

See Also
Graph.get_all_simple_paths()
def _GRG(n, radius, torus=False):

Internal function, undocumented.

See Also
Graph.GRG()
def _Incidence(matrix, directed=False, mode='all', multiple=False):

Internal function, undocumented.

See Also
Graph.Incidence()
def _is_matching(matching, types=None):

Internal function, undocumented.

def _is_maximal_matching(matching, types=None):

Internal function, undocumented.

Use igraph.Matching.is_maximal instead.

def _layout_sugiyama(...):

Internal function, undocumented.

See Also
Graph.layout_sugiyama()
def _maximum_bipartite_matching(types, weights=None):

Internal function, undocumented.

See Also
igraph.Graph.maximum_bipartite_matching
def _Random_Bipartite(n1, n2, p=None, m=None, directed=False, neimode='all'):

Internal function, undocumented.

See Also
Graph.Random_Bipartite()
def _raw_pointer():

Returns the memory address of the igraph graph encapsulated by the Python object as an ordinary Python integer.

This function should not be used directly by igraph users, it is useful only if you want to access some unwrapped function in the C core of igraph using the ctypes module.

def _spanning_tree(weights=None):

Internal function, undocumented.

See Also
Graph.spanning_tree()