python-igraph API reference

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

class documentation

Generic graph.

This class is built on top of GraphBase, so the order of the methods in the generated API documentation is a little bit obscure: inherited methods come after the ones implemented directly in the subclass. Graph provides many functions that GraphBase does not, mostly because these functions are not speed critical and they were easier to implement in Python than in pure C. An example is the attribute handling in the constructor: the constructor of Graph accepts three dictionaries corresponding to the graph, vertex and edge attributes while the constructor of GraphBase does not. This extension was needed to make Graph serializable through the pickle module. Graph also overrides some functions from GraphBase to provide a more convenient interface; e.g., layout functions return a Layout instance from Graph instead of a list of coordinate pairs.

Graphs can also be indexed by strings or pairs of vertex indices or vertex names. When a graph is indexed by a string, the operation translates to the retrieval, creation, modification or deletion of a graph attribute:

>>> g = Graph.Full(3)
>>> g["name"] = "Triangle graph"
>>> g["name"]
'Triangle graph'
>>> del g["name"]

When a graph is indexed by a pair of vertex indices or names, the graph itself is treated as an adjacency matrix and the corresponding cell of the matrix is returned:

>>> g = Graph.Full(3)
>>> g.vs["name"] = ["A", "B", "C"]
>>> g[1, 2]
1
>>> g["A", "B"]
1
>>> g["A", "B"] = 0
>>> g.ecount()
2

Assigning values different from zero or one to the adjacency matrix will be translated to one, unless the graph is weighted, in which case the numbers will be treated as weights:

>>> g.is_weighted()
False
>>> g["A", "B"] = 2
>>> g["A", "B"]
1
>>> g.es["weight"] = 1.0
>>> g.is_weighted()
True
>>> g["A", "B"] = 2
>>> g["A", "B"]
2
>>> g.es["weight"]
[1.0, 1.0, 2]
Method __init__ __init__(n=0, edges=None, directed=False, graph_attrs=None, vertex_attrs=None, edge_attrs=None)
Method add_edge Adds a single edge to the graph.
Method add_edges Adds some edges to the graph.
Method add_vertex No summary
Method add_vertices Adds some vertices to the graph.
Method as_directed Returns a directed copy of this graph. Arguments are passed on to to_directed() that is invoked on the copy.
Method as_undirected Returns an undirected copy of this graph. Arguments are passed on to to_undirected() that is invoked on the copy.
Method delete_edges Deletes some edges from the graph.
Method indegree Returns the in-degrees in a list.
Method outdegree Returns the out-degrees in a list.
Method all_st_cuts Returns all the cuts between the source and target vertices in a directed graph.
Method all_st_mincuts Returns all the mincuts between the source and target vertices in a directed graph.
Method biconnected_components Calculates the biconnected components of the graph.
Method clear Clears the graph, deleting all vertices, edges, and attributes.
Method cohesive_blocks Calculates the cohesive block structure of the graph.
Method clusters Calculates the (strong or weak) clusters (connected components) for a given graph.
Method degree_distribution Calculates the degree distribution of the graph.
Method dyad_census Calculates the dyad census of the graph.
Method get_adjacency Returns the adjacency matrix of a graph.
Method get_adjacency_sparse Returns the adjacency matrix of a graph as a SciPy CSR matrix.
Method get_adjlist Returns the adjacency list representation of the graph.
Method get_all_simple_paths Calculates all the simple paths from a given node to some other nodes (or all of them) in a graph.
Method get_inclist Returns the incidence list representation of the graph.
Method gomory_hu_tree Calculates the Gomory-Hu tree of an undirected graph with optional edge capacities.
Method is_named Returns whether the graph is named.
Method is_weighted Returns whether the graph is weighted.
Method maxflow Returns a maximum flow between the given source and target vertices in a graph.
Method mincut Calculates the minimum cut between the given source and target vertices or within the whole graph.
Method st_mincut Calculates the minimum cut between the source and target vertices in a graph.
Method modularity Calculates the modularity score of the graph with respect to a given clustering.
Method path_length_hist Returns the path length histogram of the graph
Method pagerank Calculates the PageRank values of a graph.
Method spanning_tree Calculates a minimum spanning tree for a graph.
Method transitivity_avglocal_undirected Calculates the average of the vertex transitivities of the graph.
Method triad_census Calculates the triad census of the graph.
Method count_automorphisms_vf2 Returns the number of automorphisms of the graph.
Method get_automorphisms_vf2 Returns all the automorphisms of the graph
Method community_fastgreedy Community structure 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_leading_eigenvector_naive Naive implementation of Newman's eigenvector community structure detection.
Method community_leading_eigenvector Newman's leading eigenvector method for detecting community structure.
Method community_label_propagation Finds the community structure of the graph according to the label propagation method of Raghavan et al.
Method community_multilevel Community structure based on the multilevel algorithm of Blondel et al.
Method community_optimal_modularity Calculates the optimal modularity score of the graph and the corresponding community structure.
Method community_edge_betweenness Community structure based on the betweenness of the edges in the network.
Method community_spinglass Finds the community structure of the graph according to the spinglass community detection method of Reichardt & Bornholdt.
Method community_walktrap Community detection algorithm of Latapy & Pons, based on random walks.
Method k_core Returns some k-cores of the graph.
Method community_leiden Finds the community structure of the graph using the Leiden algorithm of Traag, van Eck & Waltman.
Method layout Returns the layout of the graph according to a layout algorithm.
Method layout_auto Chooses and runs a suitable layout function based on simple topological properties of the graph.
Method layout_sugiyama Places the vertices using a layered Sugiyama layout.
Method maximum_bipartite_matching Finds a maximum matching in a bipartite graph.
Class Variable from_networkx Undocumented
Class Variable from_graph_tool Undocumented
Class Variable Read_GraphMLz Undocumented
Class Variable Read_Pickle Undocumented
Class Variable Read_Picklez Undocumented
Class Variable Read_Adjacency Undocumented
Class Variable Read Undocumented
Class Variable DictList Undocumented
Class Variable TupleList Undocumented
Class Variable ListDict Undocumented
Class Variable DictDict Undocumented
Class Variable DataFrame Undocumented
Class Variable Bipartite Undocumented
Class Variable Incidence Undocumented
Class Variable Full_Bipartite Undocumented
Class Variable Random_Bipartite Undocumented
Class Variable GRG Undocumented
Class Variable Formula Undocumented
Property vs The vertex sequence of the graph
Property es The edge sequence of the graph
Method bipartite_projection Projects a bipartite graph into two one-mode graphs. Edge directions are ignored while projecting.
Method bipartite_projection_size No summary
Method get_incidence Returns the incidence matrix of a bipartite graph. The incidence matrix is an n times m matrix, where n and m are the number of vertices in the two vertex classes.
Method dfs Conducts a depth first search (DFS) on the graph.
Method __iadd__ In-place addition (disjoint union).
Method __add__ Copies the graph and extends the copy depending on the type of the other object given.
Method __and__ Graph intersection operator.
Method __isub__ In-place subtraction (difference).
Method __sub__ Removes the given object(s) from the graph
Method __mul__ Copies exact replicas of the original graph an arbitrary number of times.
Method __bool__ Returns True if the graph has at least one vertex, False otherwise.
Method __or__ Graph union operator.
Method __coerce__ Coercion rules.
Method __reduce__ Support for pickling.
Class Variable __iter__ Undocumented
Class Variable __hash__ Undocumented
Method __plot__ Plots the graph to the given Cairo context or matplotlib Axes.
Method __str__ Returns a string representation of the graph.
Method summary Returns the summary of the graph.
Method disjoint_union Creates the disjoint union of two (or more) graphs.
Method union Creates the union of two (or more) graphs.
Method intersection Creates the intersection of two (or more) graphs.
Property _as_parameter_ Undocumented
Class Method _reconstruct Reconstructs a Graph object from Python's pickled format.
Class Variable _format_mapping Undocumented
Class Variable _layout_mapping Undocumented

Inherited from GraphBase:

Method vcount Counts the number of vertices.
Method ecount Counts the number of edges.
Method is_dag Checks whether the graph is a DAG (directed acyclic graph).
Method is_directed Checks whether the graph is directed.
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 delete_vertices Deletes vertices and all its edges from the graph.
Method degree Returns some vertex degrees from the graph.
Method strength Returns the strength (weighted degree) of some vertices from the graph
Method is_loop Checks whether a specific set of edges contain loop edges
Method is_multiple Checks whether an edge is a multiple edge.
Method has_multiple Checks whether the graph has multiple edges.
Method is_mutual Checks whether an edge has an opposite pair.
Method count_multiple Counts the multiplicities of the given edges.
Method neighbors Returns adjacent vertices to a given vertex.
Method successors Returns the successors of a given vertex.
Method predecessors Returns the predecessors of a given vertex.
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 incident Returns the edges a given vertex is incident on.
Method Adjacency Generates a graph from its adjacency matrix.
Method Asymmetric_Preference Generates a graph based on asymmetric vertex types and connection probabilities.
Method Atlas Generates a graph from the Graph Atlas.
Method Barabasi Generates a graph based on the Barabasi-Albert model.
Method De_Bruijn Generates a de Bruijn graph with parameters (m, n)
Method Establishment Generates a graph based on a simple growing model with vertex types.
Method Erdos_Renyi Generates a graph based on the Erdos-Renyi model.
Method Famous Generates a famous graph based on its name.
Method Forest_Fire Generates a graph based on the forest fire model
Method Full_Citation Generates a full citation graph
Method Full Generates a full graph (directed or undirected, with or without loops).
Method Growing_Random Generates a growing random graph.
Method Kautz Generates a Kautz graph with parameters (m, n)
Method K_Regular Generates a k-regular random graph
Method Preference Generates a graph based on vertex types and connection probabilities.
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 SBM Generates a graph based on a stochastic blockmodel.
Method Star Generates a star graph.
Method Lattice Generates a regular lattice.
Method LCF Generates a graph from LCF notation.
Method Realize_Degree_Sequence Generates a graph from a degree sequence.
Method Ring Generates a ring 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 Tree Generates a tree in which almost all vertices have the same number of children.
Method Degree_Sequence Generates a graph with a given degree sequence.
Method Isoclass Generates a graph with a given isomorphism class.
Method Tree_Game Generates a random tree by sampling uniformly from the set of labelled trees with a given number of nodes.
Method Watts_Strogatz No summary
Method Weighted_Adjacency Generates a graph from its adjacency matrix.
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 average_path_length Calculates the average path length in a graph.
Method authority_score Calculates Kleinberg's authority score for the vertices of the graph
Method betweenness Calculates or estimates the betweenness of vertices in a graph.
Method bridges Returns the list of bridges in the graph.
Method chordal_completion chordal_complation(alpha=None, alpham1=None) --
Method closeness Calculates the closeness centralities of given vertices in a graph.
Method harmonic_centrality Calculates the harmonic centralities of given vertices in a graph.
Method copy Creates a copy of the graph.
Method decompose Decomposes the graph into subgraphs.
Method contract_vertices Contracts some vertices in the graph, i.e. replaces groups of vertices with single vertices. Edges are not affected.
Method constraint Calculates Burt's constraint scores for given vertices in a graph.
Method density Calculates the density of the graph.
Method diameter Calculates the diameter of the graph.
Method get_diameter Returns a path with the actual diameter of the graph.
Method farthest_points Returns two vertex IDs whose distance equals the actual diameter of the graph.
Method diversity Calculates the structural diversity index of the vertices.
Method eccentricity Calculates the eccentricities of given vertices in a graph.
Method edge_betweenness Calculates or estimates the edge betweennesses in a graph.
Method eigen_adjacency Undocumented
Method edge_connectivity Calculates the edge connectivity of the graph or between some vertices.
Method eigenvector_centrality Calculates the eigenvector centralities of the vertices in a graph.
Method feedback_arc_set Calculates an approximately or exactly minimal feedback arc set.
Method get_shortest_paths Calculates the shortest paths from/to a given node in a graph.
Method get_all_shortest_paths Calculates all of the shortest paths from/to a given node in a graph.
Method girth Returns the girth of the graph.
Method convergence_degree Undocumented (yet).
Method convergence_field_size Undocumented (yet).
Method hub_score Calculates Kleinberg's hub score for the vertices of the graph
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 knn Calculates the average degree of the neighbors for each vertex, and the same quantity as the function of vertex degree.
Method is_connected Decides whether the graph is connected.
Method linegraph Returns the line graph of the graph.
Method maxdegree Returns the maximum degree of a vertex set in the graph.
Method maximum_cardinality_search No summary
Method neighborhood No summary
Method neighborhood_size No summary
Method personalized_pagerank Calculates the personalized PageRank values of a graph.
Method permute_vertices Permutes the vertices of the graph according to the given permutation and returns the new graph.
Method radius Calculates the radius of the graph.
Method reciprocity No summary
Method rewire Randomly rewires the graph while preserving the degree distribution.
Method rewire_edges Rewires the edges of a graph with constant probability.
Method shortest_paths Calculates shortest path lengths for given vertices in a graph.
Method simplify Simplifies a graph by removing self-loops and/or multiple edges.
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 topological_sorting Calculates a possible topological sorting of the graph.
Method to_prufer Converts a tree graph into a Prufer sequence.
Method transitivity_undirected Calculates the global transitivity (clustering coefficient) of the graph.
Method transitivity_local_undirected Calculates the local transitivity (clustering coefficient) of the given vertices in the graph.
Method unfold_tree Unfolds the graph using a BFS to a tree by duplicating vertices as necessary.
Method vertex_connectivity Calculates the vertex connectivity of the graph or between some vertices.
Method bibcoupling Calculates bibliographic coupling scores for given vertices in a graph.
Method cocitation Calculates cocitation scores 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 motifs_randesu Counts the number of motifs in the graph
Method motifs_randesu_no Counts the total number of motifs in the graph
Method motifs_randesu_estimate Counts the total number of motifs in the graph
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_grid Places the vertices of a graph in a 2D or 3D grid.
Method layout_star Calculates a star-like layout for the graph.
Method layout_kamada_kawai Places the vertices on a plane according to the Kamada-Kawai algorithm.
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_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_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_random Places the vertices of the graph randomly.
Method bfs Conducts a breadth first search (BFS) on the graph.
Method bfsiter Constructs a breadth first search (BFS) iterator of the graph.
Method dfsiter Constructs a depth first search (DFS) iterator of the graph.
Method get_edgelist Returns the edge list of a graph.
Method to_directed Converts an undirected graph to directed.
Method to_undirected Converts a directed graph to undirected.
Method laplacian Returns the Laplacian matrix of a graph.
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_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_GML Reads a GML file and creates a graph based on it.
Method Read_Ncol Reads an .ncol file used by LGL.
Method Read_Lgl Reads an .lgl file used by LGL.
Method Read_Pajek Reads a Pajek format file and creates a graph based on it.
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_ncol Writes the edge list of a graph to a file in .ncol format.
Method write_lgl Writes the edge list of a graph to a file in .lgl format.
Method write_pajek Writes the graph in Pajek 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 canonical_permutation Calculates the canonical permutation of a graph using the BLISS isomorphism algorithm.
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 count_isomorphisms_vf2 Determines the number of isomorphisms between the graph and another one
Method get_isomorphisms_vf2 Returns all isomorphisms between the graph and another one
Method subisomorphic_vf2 Checks whether a subgraph of the graph is isomorphic to another graph.
Method count_subisomorphisms_vf2 Determines the number of subisomorphisms between the graph and another one
Method get_subisomorphisms_vf2 Returns all subisomorphisms between the graph and another one
Method subisomorphic_lad Checks whether a subgraph of the graph is isomorphic to another graph.
Method get_subisomorphisms_lad Returns all subisomorphisms between the graph and another one using the LAD algorithm.
Method attributes
Method vertex_attributes
Method edge_attributes
Method complementer Returns the complementer of the graph
Method compose Returns the composition of two graphs.
Method difference Subtracts the given graph from the original
Method dominator Returns the dominator tree from the given root node
Method maxflow_value Returns the value of the maximum flow between the source and target vertices.
Method mincut_value Returns the minimum cut between the source and target vertices or within the whole graph.
Method all_minimal_st_separators Returns a list containing all the minimal s-t separators of a graph.
Method is_minimal_separator Decides whether the given vertex set is a minimal separator.
Method is_separator Decides whether the removal of the given vertices disconnects the graph.
Method minimum_size_separators Returns a list containing all separator vertex sets of minimum size.
Method cliques Returns some or all cliques of the graph as a list of tuples.
Method largest_cliques Returns the largest cliques of the graph as a list of tuples.
Method maximal_cliques Returns the maximal cliques of the graph as a list of tuples.
Method clique_number Returns the clique number of the graph.
Method independent_vertex_sets Returns some or all independent vertex sets 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 maximal_independent_vertex_sets Returns the maximal independent vertex sets of the graph as a list of tuples.
Method independence_number Returns the independence number of the graph.
Method coreness Finds the coreness (shell index) of the vertices of the network.
Method random_walk Performs a random walk of a given length from a given node.
Method _Bipartite Internal function, undocumented.
Method _Full_Bipartite Internal function, undocumented.
Method _GRG Internal function, undocumented.
Method _Incidence Internal function, undocumented.
Method _Random_Bipartite Internal function, undocumented.
Method _get_all_simple_paths Internal function, undocumented.
Method _spanning_tree Internal function, undocumented.
Method _layout_sugiyama Internal function, undocumented.
Method _is_matching Internal function, undocumented.
Method _is_maximal_matching Internal function, undocumented.
Method _maximum_bipartite_matching Internal function, undocumented.
Method __graph_as_capsule __graph_as_capsule()
Method _raw_pointer Returns the memory address of the igraph graph encapsulated by the Python object as an ordinary Python integer.
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.
def __init__(self, *args, **kwds):

__init__(n=0, edges=None, directed=False, graph_attrs=None, vertex_attrs=None, edge_attrs=None)

Constructs a graph from scratch.

ParametersargsUndocumented
kwdsUndocumented
nthe number of vertices. Can be omitted, the default is zero. Note that if the edge list contains vertices with indexes larger than or equal to m, then the number of vertices will be adjusted accordingly.
edgesthe edge list where every list item is a pair of integers. If any of the integers is larger than n-1, the number of vertices is adjusted accordingly. None means no edges.
directedwhether the graph should be directed
graph_attrsthe attributes of the graph as a dictionary.
vertex_attrsthe attributes of the vertices as a dictionary. Every dictionary value must be an iterable with exactly n items.
edge_attrsthe attributes of the edges as a dictionary. Every dictionary value must be an iterable with exactly m items where m is the number of edges.
def add_edge(self, source, target, **kwds):

Adds a single edge to the graph.

Keyword arguments (except the source and target arguments) will be assigned to the edge as attributes.

The performance cost of adding a single edge or several edges to a graph is similar. Thus, when adding several edges, a single add_edges() call is more efficient than multiple add_edge() calls.

Parameterssourcethe source vertex of the edge or its name.
targetthe target vertex of the edge or its name.
kwdsUndocumented
Returnsthe newly added edge as an Edge object. Use add_edges([(source, target)]) if you don't need the Edge object and want to avoid the overhead of creating it.
def add_edges(self, es, attributes=None):

Adds some edges to the graph.

Parametersesthe list of edges to be added. Every edge is represented with a tuple containing the vertex IDs or names of the two endpoints. Vertices are enumerated from zero.
attributesdict of sequences, all of length equal to the number of edges to be added, containing the attributes of the new edges.
def add_vertex(self, name=None, **kwds):

Adds a single vertex to the graph. Keyword arguments will be assigned as vertex attributes. Note that name as a keyword argument is treated specially; if a graph has name as a vertex attribute, it allows one to refer to vertices by their names in most places where igraph expects a vertex ID.

Returnsthe newly added vertex as a Vertex object. Use add_vertices(1) if you don't need the Vertex object and want to avoid the overhead of creating t.
def add_vertices(self, n, attributes=None):

Adds some vertices to the graph.

Note that if n is a sequence of strings, indicating the names of the new vertices, and attributes has a key name, the two conflict. In that case the attribute will be applied.

Parametersnthe number of vertices to be added, or the name of a single vertex to be added, or a sequence of strings, each corresponding to the name of a vertex to be added. Names will be assigned to the name vertex attribute.
attributesdict of sequences, all of length equal to the number of vertices to be added, containing the attributes of the new vertices. If n is a string (so a single vertex is added), then the values of this dict are the attributes themselves, but if n=1 then they have to be lists of length 1.
def as_directed(self, *args, **kwds):

Returns a directed copy of this graph. Arguments are passed on to to_directed() that is invoked on the copy.

def as_undirected(self, *args, **kwds):

Returns an undirected copy of this graph. Arguments are passed on to to_undirected() that is invoked on the copy.

def delete_edges(self, *args, **kwds):

Deletes some edges from the graph.

The set of edges to be deleted is determined by the positional and keyword arguments. If the function is called without any arguments, all edges are deleted. If any keyword argument is present, or the first positional argument is callable, an edge sequence is derived by calling EdgeSeq.select with the same positional and keyword arguments. Edges in the derived edge sequence will be removed. Otherwise the first positional argument is considered as follows:

  • None - deletes all edges (deprecated since 0.8.3)
  • a single integer - deletes the edge with the given ID
  • a list of integers - deletes the edges denoted by the given IDs
  • a list of 2-tuples - deletes the edges denoted by the given source-target vertex pairs. When multiple edges are present between a given source-target vertex pair, only one is removed.
Unknown Field: deprecateddelete_edges(None) has been replaced by delete_edges() - with no arguments - since igraph 0.8.3.
def indegree(self, *args, **kwds):

Returns the in-degrees in a list.

See degree for possible arguments.

def outdegree(self, *args, **kwds):

Returns the out-degrees in a list.

See degree for possible arguments.

def all_st_cuts(self, source, target):

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.

Parameterssourcethe source vertex ID
targetthe target vertex ID
Returnsa list of Cut objects.
Unknown Field: newfieldrefReference
Unknown Field: refJS Provan and DR Shier: A paradigm for listing (s,t)-cuts in graphs. Algorithmica 15, 351--372, 1996.
def all_st_mincuts(self, source, target, capacity=None):

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

This function lists all minimum edge-cuts between a source and a target vertex.

Parameterssourcethe source vertex ID
targetthe target vertex ID
capacitythe edge capacities (weights). If None, all edges have equal weight. May also be an attribute name.
Returnsa list of Cut objects.
Unknown Field: newfieldrefReference
Unknown Field: refJS Provan and DR Shier: A paradigm for listing (s,t)-cuts in graphs. Algorithmica 15, 351--372, 1996.
def biconnected_components(self, return_articulation_points=False):

Calculates the biconnected components of the graph.

Parametersreturn_articulation_pointswhether to return the articulation points as well
Returnsa VertexCover object describing the biconnected components, and optionally the list of articulation points as well
def clear(self):

Clears the graph, deleting all vertices, edges, and attributes.

See Alsodelete_vertices and delete_edges.
def cohesive_blocks(self):

Calculates the cohesive block structure of the graph.

Cohesive blocking is a method of determining hierarchical subsets of graph vertices based on their structural cohesion (i.e. vertex connectivity). For a given graph G, a subset of its vertices S is said to be maximally k-cohesive if there is no superset of S with vertex connectivity greater than or equal to k. Cohesive blocking is a process through which, given a k-cohesive set of vertices, maximally l-cohesive subsets are recursively identified with l > k. Thus a hierarchy of vertex subsets is obtained in the end, with the entire graph G at its root.

Returnsan instance of CohesiveBlocks. See the documentation of CohesiveBlocks for more information.
See AlsoCohesiveBlocks
def clusters(self, mode='strong'):

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

Parametersmodemust be either "strong" or "weak", depending on the clusters being sought. Optional, defaults to "strong".
Returnsa VertexClustering object
def degree_distribution(self, bin_width=1, *args, **kwds):

Calculates the degree distribution of the graph.

Unknown keyword arguments are directly passed to degree().

Parametersbin_widththe bin width of the histogram
argsUndocumented
kwdsUndocumented
Returnsa histogram representing the degree distribution of the graph.
def dyad_census(self, *args, **kwds):

Calculates the dyad census of the graph.

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

Returnsa DyadCensus object.
Unknown Field: newfieldrefReference
Unknown Field: refHolland, P.W. and Leinhardt, S. (1970). A Method for Detecting Structure in Sociometric Data. American Journal of Sociology, 70, 492-513.
def get_adjacency(self, type=GET_ADJACENCY_BOTH, attribute=None, default=0, eids=False):

Returns the adjacency matrix of a graph.

Parameterstypeeither GET_ADJACENCY_LOWER (uses the lower triangle of the matrix) or GET_ADJACENCY_UPPER (uses the upper triangle) or GET_ADJACENCY_BOTH (uses both parts). Ignored for directed graphs.
attributeif None, returns the ordinary adjacency matrix. When the name of a valid edge attribute is given here, the matrix returned will contain the default value at the places where there is no edge or the value of the given attribute where there is an edge. Multiple edges are not supported, the value written in the matrix in this case will be unpredictable. This parameter is ignored if eids is True
defaultthe default value written to the cells in the case of adjacency matrices with attributes.
eidsspecifies whether the edge IDs should be returned in the adjacency matrix. Since zero is a valid edge ID, the cells in the matrix that correspond to unconnected vertex pairs will contain -1 instead of 0 if eids is True. If eids is False, the number of edges will be returned in the matrix for each vertex pair.
Returnsthe adjacency matrix as a Matrix.
def get_adjacency_sparse(self, attribute=None):

Returns the adjacency matrix of a graph as a SciPy CSR matrix.

Parametersattributeif None, returns the ordinary adjacency matrix. When the name of a valid edge attribute is given here, the matrix returned will contain the default value at the places where there is no edge or the value of the given attribute where there is an edge.
Returnsthe adjacency matrix as a scipy.sparse.csr_matrix.
def get_adjlist(self, mode='out'):

Returns the adjacency list representation of the graph.

The adjacency list representation is a list of lists. Each item of the outer list belongs to a single vertex of the graph. The inner list contains the neighbors of the given vertex.

Parametersmodeif "out", returns the successors of the vertex. If "in", returns the predecessors of the vertex. If "all"", both the predecessors and the successors will be returned. Ignored for undirected graphs.
def get_all_simple_paths(self, v, to=None, cutoff=-1, mode='out'):

Calculates all the simple paths from a given node to some other nodes (or all of them) in a graph.

A path is simple if its vertices are unique, i.e. no vertex is visited more than once.

Note that potentially there are exponentially many paths between two vertices of a graph, especially if your graph is lattice-like. In this case, you may run out of memory when using this function.

Parametersvthe 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.
cutoffmaximum length of path that is considered. If negative, paths of all lengths are considered.
modethe directionality of the paths. "in" means to calculate incoming paths, "out" means to calculate outgoing paths, "all" means to calculate both ones.
Returnsall of the simple paths from the given node to every other reachable node in the graph in a list. Note that in case of mode="in", the vertices in a path are returned in reversed order!
def get_inclist(self, mode='out'):

Returns the incidence list representation of the graph.

The incidence list representation is a list of lists. Each item of the outer list belongs to a single vertex of the graph. The inner list contains the IDs of the incident edges of the given vertex.

Parametersmodeif "out", returns the successors of the vertex. If "in", returns the predecessors of the vertex. If "all", both the predecessors and the successors will be returned. Ignored for undirected graphs.
def gomory_hu_tree(self, capacity=None, flow='flow'):

Calculates the Gomory-Hu tree of an undirected graph with optional edge capacities.

The Gomory-Hu tree is a concise representation of the value of all the maximum flows (or minimum cuts) in a graph. The vertices of the tree correspond exactly to the vertices of the original graph in the same order. Edges of the Gomory-Hu tree are annotated by flow values. The value of the maximum flow (or minimum cut) between an arbitrary (u,v) vertex pair in the original graph is then given by the minimum flow value (i.e. edge annotation) along the shortest path between u and v in the Gomory-Hu tree.

Parameterscapacitythe edge capacities (weights). If None, all edges have equal weight. May also be an attribute name.
flowthe name of the edge attribute in the returned graph in which the flow values will be stored.
Returnsthe Gomory-Hu tree as a Graph object.
def is_named(self):

Returns whether the graph is named.

A graph is named if and only if it has a "name" vertex attribute.

def is_weighted(self):

Returns whether the graph is weighted.

A graph is weighted if and only if it has a "weight" edge attribute.

def maxflow(self, source, target, capacity=None):

Returns a maximum flow between the given source and target vertices in a graph.

A maximum flow from source to target is an assignment of non-negative real numbers to the edges of the graph, satisfying two properties:

  1. For each edge, the flow (i.e. the assigned number) is not more than the capacity of the edge (see the capacity argument)
  2. For every vertex except the source and the target, the incoming flow is the same as the outgoing flow.

The value of the flow is the incoming flow of the target or the outgoing flow of the source (which are equal). The maximum flow is the maximum possible such value.

ParameterssourceUndocumented
targetUndocumented
capacitythe edge capacities (weights). If None, all edges have equal weight. May also be an attribute name.
Returnsa Flow object describing the maximum flow
def mincut(self, source=None, target=None, capacity=None):

Calculates the minimum cut between the given 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 neither the source nor the target are 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.

Parameterssourcethe source vertex ID. If None, the 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, the source must also be None and the calculation will be done for the entire graph (i.e. all possible vertex pairs).
capacitythe edge capacities (weights). If None, all edges have equal weight. May also be an attribute name.
Returnsa Cut object describing the minimum cut
def st_mincut(self, source, target, capacity=None):

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

Parameterssourcethe 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.
Returnsthe 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
def modularity(self, membership, weights=None):

Calculates the modularity score of the graph with respect to a given clustering.

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's defined as Q=1/(2m)*sum(Aij-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, and Ci and cj are the types of the two vertices (i and j). 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 adjacent to vertex i, kj is the total weight of edges adjacent to vertex j and m is the total edge weight in the graph.

Parametersmembershipa membership list or a VertexClustering object
weightsoptional edge weights or None if all edges are weighed equally. Attribute names are also allowed.
Returnsthe modularity score
Unknown Field: newfieldrefReference
Unknown Field: refMEJ Newman and M Girvan: Finding and evaluating community structure in networks. Phys Rev E 69 026113, 2004.
def path_length_hist(self, directed=True):

Returns the path length histogram of the graph

Parametersdirectedwhether to consider directed paths. Ignored for undirected graphs.
Returnsa Histogram object. The object will also have an unconnected attribute that stores the number of unconnected vertex pairs (where the second vertex can not be reached from the first one). The latter one will be of type long (and not a simple integer), since this can be very large.
def pagerank(self, vertices=None, directed=True, damping=0.85, weights=None, arpack_options=None, implementation='prpack', niter=1000, eps=0.001):

Calculates the PageRank values of a graph.

Parametersverticesthe 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 nodes with no incoming links. It is also the probability of resetting the random walk to a uniform distribution in each step.
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.
implementationwhich 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.
Returnsa list with the Google PageRank values of the specified vertices.
def spanning_tree(self, weights=None, return_tree=True):

Calculates a minimum spanning tree for a graph.

Parametersweightsa vector containing weights for every edge in the graph. None means that the graph is unweighted.
return_treewhether to return the minimum spanning tree (when return_tree is True) or to return the IDs of the edges in the minimum spanning tree instead (when return_tree is False). The default is True for historical reasons as this argument was introduced in igraph 0.6.
Returnsthe spanning tree as a Graph object if return_tree is True or the IDs of the edges that constitute the spanning tree if return_tree is False.
Unknown Field: newfieldrefReference
Unknown Field: refPrim, R.C.: Shortest connection networks and some generalizations. Bell System Technical Journal 36:1389-1401, 1957.
def transitivity_avglocal_undirected(self, mode='nan', weights=None):

Calculates the average of the vertex transitivities of the graph.

In the unweighted case, the transitivity measures the probability that two neighbors of a vertex are connected. In case of the average local transitivity, this probability is calculated for each vertex and then the average is taken. Vertices with less than two neighbors require special treatment, they will either be left out from the calculation or they will be considered as having zero transitivity, depending on the mode parameter. The calculation is slightly more involved for weighted graphs; in this case, weights are taken into account according to the formula of Barrat et al (see the references).

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

Parametersmodedefines how to treat vertices with degree less than two. If TRANSITIVITY_ZERO or "zero", these vertices will have zero transitivity. If TRANSITIVITY_NAN or "nan", these vertices will be excluded from the average.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
See Alsotransitivity_undirected(), transitivity_local_undirected()
Unknown Field: newfieldrefReference
Unknown Field: refWatts 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 triad_census(self, *args, **kwds):

Calculates the triad census of the graph.

Returnsa TriadCensus object.
Unknown Field: newfieldrefReference
Unknown Field: refDavis, J.A. and Leinhardt, S. (1972). The Structure of Positive Interpersonal Relations in Small Groups. In: J. Berger (Ed.), Sociological Theories in Progress, Volume 2, 218-251. Boston: Houghton Mifflin.
def count_automorphisms_vf2(self, color=None, edge_color=None, node_compat_fn=None, edge_compat_fn=None):

Returns the number of automorphisms of the graph.

This function simply calls count_isomorphisms_vf2 with the graph itself. See count_isomorphisms_vf2 for an explanation of the parameters.

Returnsthe number of automorphisms of the graph
See AlsoGraph.count_isomorphisms_vf2
def get_automorphisms_vf2(self, color=None, edge_color=None, node_compat_fn=None, edge_compat_fn=None):

Returns all the automorphisms of the graph

This function simply calls get_isomorphisms_vf2 with the graph itself. See get_isomorphisms_vf2 for an explanation of the parameters.

Returnsa list of lists, each item containing a possible mapping of the graph vertices to itself according to the automorphism
See AlsoGraph.get_isomorphisms_vf2
def community_fastgreedy(self, weights=None):

Community structure based on the greedy optimization of modularity.

This algorithm merges individual nodes into communities in a way that greedily maximizes the modularity score of the graph. It can be proven that if no merge can increase the current modularity score, the algorithm can be stopped since no further increase can be achieved.

This algorithm is said to run almost in linear time on sparse graphs.

Parametersweightsedge attribute name or a list containing edge weights
Returnsan appropriate VertexDendrogram object.
Unknown Field: newfieldrefReference
Unknown Field: refA Clauset, MEJ Newman and C Moore: Finding community structure in very large networks. Phys Rev E 70, 066111 (2004).
def community_infomap(self, edge_weights=None, vertex_weights=None, trials=10):

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

Parametersedge_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.
Returnsan appropriate VertexClustering object with an extra attribute called codelength that stores the code length determined by the algorithm.
Unknown Field: newfieldrefReference
Unknown Field: refM. Rosvall and C. T. Bergstrom: Maps of information flow reveal community structure in complex networks, PNAS 105, 1118 (2008). http://dx.doi.org/10.1073/pnas.0706851105, 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://dx.doi.org/10.1140/epjst/e2010-01179-1, http://arxiv.org/abs/0906.1405.
def community_leading_eigenvector_naive(self, clusters=None, return_merges=False):

Naive implementation of Newman's eigenvector community structure detection.

This function splits the network into two components according to the leading eigenvector of the modularity matrix and then recursively takes the given number of steps by splitting the communities as individual networks. This is not the correct way, however, see the reference for explanation. Consider using the correct community_leading_eigenvector method instead.

Parametersclustersthe desired number of communities. If None, 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, so the actual number of discovered communities can be less than the desired one.
return_mergeswhether the returned object should be a dendrogram instead of a single clustering.
Returnsan appropriate VertexClustering or VertexDendrogram object.
Unknown Field: newfieldrefReference
Unknown Field: refMEJ Newman: Finding community structure in networks using the eigenvectors of matrices, arXiv:physics/0605087
def community_leading_eigenvector(self, clusters=None, weights=None, arpack_options=None):

Newman's leading eigenvector method for detecting community structure.

This is the proper implementation of the recursive, divisive algorithm: each split is done by maximizing the modularity regarding the original network.

Parametersclustersthe desired number of communities. If None, 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, so the actual number of discovered communities can be less than the desired one.
weightsname of an edge attribute or a list containing edge weights.
arpack_optionsan ARPACKOptions object used to fine-tune the ARPACK eigenvector calculation. If omitted, the module-level variable called arpack_options is used.
Returnsan appropriate VertexClustering object.
Unknown Field: newfieldrefReference
Unknown Field: refMEJ Newman: Finding community structure in networks using the eigenvectors of matrices, arXiv:physics/0605087
def community_label_propagation(self, weights=None, initial=None, fixed=None):

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.

Parametersweightsname 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. It may also be the name of a vertex attribute; each attribute value will be interpreted as a Boolean.
Returnsan appropriate VertexClustering object.
Unknown Field: newfieldrefReference
Unknown Field: refRaghavan, 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_multilevel(self, weights=None, return_levels=False):

Community structure based on 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 adjacent 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.

This algorithm is said to run almost in linear time on sparse graphs.

Parametersweightsedge attribute name or a list containing edge weights
return_levelsif True, the communities at each level are returned in a list. If False, only the community structure with the best modularity is returned.
Returnsa list of VertexClustering objects, one corresponding to each level (if return_levels is True), or a VertexClustering corresponding to the best modularity.
Unknown Field: newfieldrefReference
Unknown Field: refVD 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(self, *args, **kwds):

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.

Returnsthe calculated membership vector and the corresponding modularity in a tuple.
def community_edge_betweenness(self, clusters=None, directed=True, weights=None):

Community structure based on the betweenness of the edges in the network.

The idea is that the betweenness of the edges connecting two communities is typically high, as many of the shortest paths between nodes in separate communities go through them. So we gradually remove the edge with the highest betweenness and recalculate the betweennesses after every removal. This way sooner or later the network falls of to separate components. The result of the clustering will be represented by a dendrogram.

Parametersclustersthe number of clusters we would like to see. This practically defines the "level" where we "cut" the dendrogram to get the membership vector of the vertices. If None, the dendrogram is cut at the level which maximizes the modularity when the graph is unweighted; otherwise the dendrogram is cut at at a single cluster (because cluster count selection based on modularities does not make sense for this method if not all the weights are equal).
directedwhether the directionality of the edges should be taken into account or not.
weightsname of an edge attribute or a list containing edge weights.
Returnsa VertexDendrogram object, initally cut at the maximum modularity or at the desired number of clusters.
def community_spinglass(self, *args, **kwds):

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

ParametersargsUndocumented
kwdsUndocumented
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 of 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. Note the underscore at the end of the argument name; this is due to the fact that lambda is a reserved keyword in Python.
Returnsan appropriate VertexClustering object.
Unknown Field: newfieldrefReference
Unknown Field: refReichardt J and Bornholdt S: Statistical mechanics of community detection. Phys Rev E 74:016110 (2006). http://arxiv.org/abs/cond-mat/0603718.
Traag VA and Bruggeman J: Community detection in networks with positive and negative links. Phys Rev E 80:036115 (2009). http://arxiv.org/abs/0811.2329.
def community_walktrap(self, weights=None, steps=4):

Community detection algorithm of Latapy & Pons, based on random walks.

The basic idea of the algorithm is that short random walks tend to stay in the same community. The result of the clustering will be represented as a dendrogram.

Parametersweightsname of an edge attribute or a list containing edge weights
stepslength of random walks to perform
Returnsa VertexDendrogram object, initially cut at the maximum modularity.
Unknown Field: newfieldrefReference
Unknown Field: refPascal Pons, Matthieu Latapy: Computing communities in large networks using random walks, http://arxiv.org/abs/physics/0512106.
def k_core(self, *args):

Returns some k-cores of the graph.

The method accepts an arbitrary number of arguments representing the desired indices of the k-cores to be returned. The arguments can also be lists or tuples. The result is a single Graph object if an only integer argument was given, otherwise the result is a list of Graph objects representing the desired k-cores in the order the arguments were specified. If no argument is given, returns all k-cores in increasing order of k.

def community_leiden(self, objective_function='CPM', weights=None, resolution_parameter=1.0, beta=0.01, initial_membership=None, n_iterations=2, node_weights=None):

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

Parametersobjective_functionwhether to use the Constant Potts Model (CPM) or modularity. Must be either "CPM" or "modularity".
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
resolution_parameterthe resolution parameter to use. Higher resolutions lead to more smaller communities, while lower resolutions lead to fewer larger communities.
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. Using a negative number of iterations will run until a stable iteration is encountered (i.e. the quality was not increased during that iteration).
node_weightsthe node weights used in the Leiden algorithm. If this is not provided, it will be automatically determined on the basis of whether you want to use CPM or modularity. If you do provide this, please make sure that you understand what you are doing.
Returnsan appropriate VertexClustering object.
Unknown Field: newfieldrefReference
Unknown Field: refTraag, V. A., Waltman, L., & van Eck, N. J. (2019). From Louvain to Leiden: guaranteeing well-connected communities. Scientific reports, 9(1), 5233. doi: 10.1038/s41598-019-41695-z
def layout(self, layout=None, *args, **kwds):

Returns the layout of the graph according to a layout algorithm.

Parameters and keyword arguments not specified here are passed to the layout algorithm directly. See the documentation of the layout algorithms for the explanation of these parameters.

Registered layout names understood by this method are:

Parameterslayoutthe layout to use. This can be one of the registered layout names or a callable which returns either a Layout object or a list of lists containing the coordinates. If None, uses the value of the plotting.layout configuration key.
argsUndocumented
kwdsUndocumented
Returnsa Layout object.
def layout_auto(self, *args, **kwds):

Chooses and runs a suitable layout function based on simple topological properties of the graph.

This function tries to choose an appropriate layout function for the graph using the following rules:

  1. If the graph has an attribute called layout, it will be used. It may either be a Layout instance, a list of coordinate pairs, the name of a layout function, or a callable function which generates the layout when called with the graph as a parameter.
  2. Otherwise, if the graph has vertex attributes called x and y, these will be used as coordinates in the layout. When a 3D layout is requested (by setting dim to 3), a vertex attribute named z will also be needed.
  3. Otherwise, if the graph is connected and has at most 100 vertices, the Kamada-Kawai layout will be used (see layout_kamada_kawai()).
  4. Otherwise, if the graph has at most 1000 vertices, the Fruchterman-Reingold layout will be used (see layout_fruchterman_reingold()).
  5. If everything else above failed, the DrL layout algorithm will be used (see layout_drl()).

All the arguments of this function except dim are passed on to the chosen layout function (in case we have to call some layout function).

ParametersargsUndocumented
kwdsUndocumented
dimspecifies whether we would like to obtain a 2D or a 3D layout.
Returnsa Layout object.
def layout_sugiyama(self, layers=None, weights=None, hgap=1, vgap=1, maxiter=100, return_extended_graph=False):

Places the vertices using a layered Sugiyama layout.

This is a layered layout that is most suitable for directed acyclic graphs, although it works on undirected or cyclic graphs as well.

Each vertex is assigned to a layer and each layer is placed on a horizontal line. Vertices within the same layer are then permuted using the barycenter heuristic that tries to minimize edge crossings.

Dummy vertices will be added on edges that span more than one layer. The returned layout therefore contains more rows than the number of nodes in the original graph; the extra rows correspond to the dummy vertices.

Parameterslayersa vector specifying a non-negative integer layer index for each vertex, or the name of a numeric vertex attribute that contains the layer indices. If None, a layering will be determined automatically. For undirected graphs, a spanning tree will be extracted and vertices will be assigned to layers using a breadth first search from the node with the largest degree. For directed graphs, cycles are broken by reversing the direction of edges in an approximate feedback arc set using the heuristic of Eades, Lin and Smyth, and then using longest path layering to place the vertices in layers.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
hgapminimum horizontal gap between vertices in the same layer.
vgapvertical gap between layers. The layer index will be multiplied by vgap to obtain the Y coordinate.
maxitermaximum number of iterations to take in the crossing reduction step. Increase this if you feel that you are getting too many edge crossings.
return_extended_graphspecifies that the extended graph with the added dummy vertices should also be returned. When this is True, the result will be a tuple containing the layout and the extended graph. The first |V| nodes of the extended graph will correspond to the nodes of the original graph, the remaining ones are dummy nodes. Plotting the extended graph with the returned layout and hidden dummy nodes will produce a layout that is similar to the original graph, but with the added edge bends. The extended graph also contains an edge attribute called _original_eid which specifies the ID of the edge in the original graph from which the edge of the extended graph was created.
Returnsthe calculated layout, which may (and usually will) have more rows than the number of vertices; the remaining rows correspond to the dummy nodes introduced in the layering step. When return_extended_graph is True, it will also contain the extended graph.
Unknown Field: newfieldrefReference
Unknown Field: refK Sugiyama, S Tagawa, M Toda: Methods for visual understanding of hierarchical system structures. IEEE Systems, Man and Cybernetics 11(2):109-125, 1981.
P Eades, X Lin and WF Smyth: A fast effective heuristic for the feedback arc set problem. Information Processing Letters 47:319-323, 1993.
def maximum_bipartite_matching(self, types='type', weights=None, eps=None):

Finds a maximum matching in a bipartite graph.

A maximum matching is a set of edges such that each vertex is incident on at most one matched edge and the number (or weight) of such edges in the set is as large as possible.

Parameterstypesvertex types in a list or the name of a vertex attribute holding vertex types. Types should be denoted by zeros and ones (or False and True) for the two sides of the bipartite graph. If omitted, it defaults to type, which is the default vertex type attribute for bipartite graphs.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
epsa small real number used in equality tests in the weighted bipartite matching algorithm. Two real numbers are considered equal in the algorithm if their difference is smaller than this value. This is required to avoid the accumulation of numerical errors. If you pass None here, igraph will try to determine an appropriate value automatically.
Returnsan instance of Matching.
from_networkx =

Undocumented

from_graph_tool =

Undocumented

Read_GraphMLz =

Undocumented

Read_Pickle =

Undocumented

Read_Picklez =

Undocumented

Read_Adjacency =

Undocumented

Read =

Undocumented

DictList =

Undocumented

TupleList =

Undocumented

ListDict =

Undocumented

DictDict =

Undocumented

DataFrame =

Undocumented

Bipartite =

Undocumented

Incidence =

Undocumented

Full_Bipartite =

Undocumented

Random_Bipartite =

Undocumented

GRG =

Undocumented

Formula =

Undocumented

@property
vs =

The vertex sequence of the graph

@property
es =

The edge sequence of the graph

def bipartite_projection(self, types='type', multiplicity=True, probe1=-1, which='both'):

Projects a bipartite graph into two one-mode graphs. Edge directions are ignored while projecting.

Examples:

>>> g = Graph.Full_Bipartite(10, 5)
>>> g1, g2 = g.bipartite_projection()
>>> g1.isomorphic(Graph.Full(10))
True
>>> g2.isomorphic(Graph.Full(5))
True
Parameterstypesan 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.
multiplicityif True, then igraph keeps the multiplicity of the edges in the projection in an edge attribute called "weight". E.g., if there is an A-C-B and an A-D-B triplet in the bipartite graph and there is no other X (apart from X=B and X=D) for which an A-X-B triplet would exist in the bipartite graph, the multiplicity of the A-B edge in the projection will be 2.
probe1this argument can be used to specify the order of the projections in the resulting list. If given and non-negative, then it is considered as a vertex ID; the projection containing the vertex will be the first one in the result.
whichthis argument can be used to specify which of the two projections should be returned if only one of them is needed. Passing 0 here means that only the first projection is returned, while 1 means that only the second projection is returned. (Note that we use 0 and 1 because Python indexing is zero-based). False is equivalent to 0 and True is equivalent to 1. Any other value means that both projections will be returned in a tuple.
Returnsa tuple containing the two projected one-mode graphs if which is not 1 or 2, or the projected one-mode graph specified by the which argument if its value is 0, 1, False or True.
def bipartite_projection_size(self, types='type', *args, **kwds):

Calculates the number of vertices and edges in the bipartite projections of this graph according to the specified vertex types. This is useful if you have a bipartite graph and you want to estimate the amount of memory you would need to calculate the projections themselves.

Parameterstypesan 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.
argsUndocumented
kwdsUndocumented
Returnsa 4-tuple containing the number of vertices and edges in the first projection, followed by the number of vertices and edges in the second projection.
def get_incidence(self, types='type', *args, **kwds):

Returns the incidence matrix of a bipartite graph. The incidence matrix is an n times m matrix, where n and m are the number of vertices in the two vertex classes.

Parameterstypesan 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.
argsUndocumented
kwdsUndocumented
Returnsthe incidence matrix and two lists in a triplet. The first list defines the mapping between row indices of the matrix and the original vertex IDs. The second list is the same for the column indices.
def dfs(self, vid, mode=OUT):

Conducts a depth first search (DFS) on the graph.

Parametersvidthe root vertex ID
modeeither "in" or "out" or "all", ignored for undirected graphs.
Returnsa tuple with the following items:
  • The vertex IDs visited (in order)
  • The parent of every vertex in the DFS
@property
_as_parameter_ =

Undocumented

def __iadd__(self, other):

In-place addition (disjoint union).

See Also__add__
def __add__(self, other):

Copies the graph and extends the copy depending on the type of the other object given.

Parametersotherif it is an integer, the copy is extended by the given number of vertices. If it is a string, the copy is extended by a single vertex whose name attribute will be equal to the given string. If it is a tuple with two elements, the copy is extended by a single edge. If it is a list of tuples, the copy is extended by multiple edges. If it is a Graph, a disjoint union is performed.
def __and__(self, other):

Graph intersection operator.

Parametersotherthe other graph to take the intersection with.
Returnsthe intersected graph.
def __isub__(self, other):

In-place subtraction (difference).

See Also__sub__
def __sub__(self, other):

Removes the given object(s) from the graph

Parametersotherif it is an integer, removes the vertex with the given ID from the graph (note that the remaining vertices will get re-indexed!). If it is a tuple, removes the given edge. If it is a graph, takes the difference of the two graphs. Accepts lists of integers or lists of tuples as well, but they can't be mixed! Also accepts Edge and EdgeSeq objects.
def __mul__(self, other):

Copies exact replicas of the original graph an arbitrary number of times.

Parametersotherif it is an integer, multiplies the graph by creating the given number of identical copies and taking the disjoint union of them.
def __bool__(self):

Returns True if the graph has at least one vertex, False otherwise.

def __or__(self, other):

Graph union operator.

Parametersotherthe other graph to take the union with.
Returnsthe union graph.
def __coerce__(self, other):

Coercion rules.

This method is needed to allow the graph to react to additions with lists, tuples, integers, strings, vertices, edges and so on.

@classmethod
def _reconstruct(cls, attrs, *args, **kwds):

Reconstructs a Graph object from Python's pickled format.

This method is for internal use only, it should not be called directly.

def __reduce__(self):

Support for pickling.

__iter__ =

Undocumented

__hash__ =

Undocumented

def __plot__(self, backend, context, *args, **kwds):

Plots the graph to the given Cairo context or matplotlib Axes.

The visual style of vertices and edges can be modified at three places in the following order of precedence (lower indices override higher indices):

  1. Keyword arguments of this function (or of plot() which is passed intact to Graph.__plot__().
  2. Vertex or edge attributes, specified later in the list of keyword arguments.
  3. igraph-wide plotting defaults (see igraph.config.Configuration)
  4. Built-in defaults.

E.g., if the vertex_size keyword attribute is not present, but there exists a vertex attribute named size, the sizes of the vertices will be specified by that attribute.

Besides the usual self-explanatory plotting parameters (context, bbox, palette), it accepts the following keyword arguments:

  • autocurve: whether to use curves instead of straight lines for multiple edges on the graph plot. This argument may be True or False; when omitted, True is assumed for graphs with less than 10.000 edges and False otherwise.
  • drawer_factory: a subclass of AbstractCairoGraphDrawer which will be used to draw the graph. You may also provide a function here which takes two arguments: the Cairo context to draw on and a bounding box (an instance of BoundingBox). If this keyword argument is missing, igraph will use the default graph drawer which should be suitable for most purposes. It is safe to omit this keyword argument unless you need to use a specific graph drawer.
  • keep_aspect_ratio: whether to keep the aspect ratio of the layout that igraph calculates to place the nodes. True means that the layout will be scaled proportionally to fit into the bounding box where the graph is to be drawn but the aspect ratio will be kept the same (potentially leaving empty space next to, below or above the graph). False means that the layout will be scaled independently along the X and Y axis in order to fill the entire bounding box. The default is False.
  • layout: the layout to be used. If not an instance of Layout, it will be passed to layout to calculate the layout. Note that if you want a deterministic layout that does not change with every plot, you must either use a deterministic layout function (like layout_circle) or calculate the layout in advance and pass a Layout object here.
  • margin: the top, right, bottom, left margins as a 4-tuple. If it has less than 4 elements or is a single float, the elements will be re-used until the length is at least 4.
  • mark_groups: whether to highlight some of the vertex groups by colored polygons. This argument can be one of the following:
    • False: no groups will be highlighted
    • True: only valid if the object plotted is a VertexClustering or VertexCover. The vertex groups in the clutering or cover will be highlighted such that the i-th group will be colored by the i-th color from the current palette. If used when plotting a graph, it will throw an error.
    • A dict mapping tuples of vertex indices to color names. The given vertex groups will be highlighted by the given colors.
    • A list containing pairs or an iterable yielding pairs, where the first element of each pair is a list of vertex indices and the second element is a color.
    • A VertexClustering or VertexCover instance. The vertex groups in the clustering or cover will be highlighted such that the i-th group will be colored by the i-th color from the current palette.

    In place of lists of vertex indices, you may also use VertexSeq instances.

    In place of color names, you may also use color indices into the current palette. None as a color name will mean that the corresponding group is ignored.

  • vertex_size: size of the vertices. The corresponding vertex attribute is called size. The default is 10. Vertex sizes are measured in the unit of the Cairo context on which igraph is drawing.
  • vertex_color: color of the vertices. The corresponding vertex attribute is color, the default is red. Colors can be specified either by common X11 color names (see the source code of igraph.drawing.colors for a list of known colors), by 3-tuples of floats (ranging between 0 and 255 for the R, G and B components), by CSS-style string specifications (#rrggbb) or by integer color indices of the specified palette.
  • vertex_frame_color: color of the frame (i.e. stroke) of the vertices. The corresponding vertex attribute is frame_color, the default is black. See vertex_color for the possible ways of specifying a color.
  • vertex_frame_width: the width of the frame (i.e. stroke) of the vertices. The corresponding vertex attribute is frame_width. The default is 1. Vertex frame widths are measured in the unit of the Cairo context on which igraph is drawing.
  • vertex_shape: shape of the vertices. Alternatively it can be specified by the shape vertex attribute. Possibilities are: square, {circle}, {triangle}, {triangle-down} or hidden. See the source code of igraph.drawing for a list of alternative shape names that are also accepted and mapped to these.
  • vertex_label: labels drawn next to the vertices. The corresponding vertex attribute is label.
  • vertex_label_dist: distance of the midpoint of the vertex label from the center of the corresponding vertex. The corresponding vertex attribute is label_dist.
  • vertex_label_color: color of the label. Corresponding vertex attribute: label_color. See vertex_color for color specification syntax.
  • vertex_label_size: font size of the label, specified in the unit of the Cairo context on which we are drawing. Corresponding vertex attribute: label_size.
  • vertex_label_angle: the direction of the line connecting the midpoint of the vertex with the midpoint of the label. This can be used to position the labels relative to the vertices themselves in conjunction with vertex_label_dist. Corresponding vertex attribute: label_angle. The default is -math.pi/2.
  • vertex_order: drawing order of the vertices. This must be a list or tuple containing vertex indices; vertices are then drawn according to this order.
  • vertex_order_by: an alternative way to specify the drawing order of the vertices; this attribute is interpreted as the name of a vertex attribute, and vertices are drawn such that those with a smaller attribute value are drawn first. You may also reverse the order by passing a tuple here; the first element of the tuple should be the name of the attribute, the second element specifies whether the order is reversed (True, False, "asc" and "desc" are accepted values).
  • edge_color: color of the edges. The corresponding edge attribute is color, the default is red. See vertex_color for color specification syntax.
  • edge_curved: whether the edges should be curved. Positive numbers correspond to edges curved in a counter-clockwise direction, negative numbers correspond to edges curved in a clockwise direction. Zero represents straight edges. True is interpreted as 0.5, False is interpreted as 0. The default is 0 which makes all the edges straight.
  • edge_width: width of the edges in the default unit of the Cairo context on which we are drawing. The corresponding edge attribute is width, the default is 1.
  • edge_arrow_size: arrow size of the edges. The corresponding edge attribute is arrow_size, the default is 1.
  • edge_arrow_width: width of the arrowhead on the edge. The corresponding edge attribute is arrow_width, the default is 1.
  • edge_order: drawing order of the edges. This must be a list or tuple containing edge indices; edges are then drawn according to this order.
  • edge_order_by: an alternative way to specify the drawing order of the edges; this attribute is interpreted as the name of an edge attribute, and edges are drawn such that those with a smaller attribute value are drawn first. You may also reverse the order by passing a tuple here; the first element of the tuple should be the name of the attribute, the second element specifies whether the order is reversed (True, False, "asc" and "desc" are accepted values).
def __str__(self):

Returns a string representation of the graph.

Behind the scenes, this method constructs a GraphSummary instance and invokes its __str__ method with a verbosity of 1 and attribute printing turned off.

See the documentation of GraphSummary for more details about the output.

def summary(self, verbosity=0, width=None, *args, **kwds):

Returns the summary of the graph.

The output of this method is similar to the output of the __str__ method. If verbosity is zero, only the header line is returned (see __str__ for more details), otherwise the header line and the edge list is printed.

Behind the scenes, this method constructs a GraphSummary object and invokes its __str__ method.

Parametersverbosityif zero, only the header line is returned (see __str__ for more details), otherwise the header line and the full edge list is printed.
widththe number of characters to use in one line. If None, no limit will be enforced on the line lengths.
argsUndocumented
kwdsUndocumented
Returnsthe summary of the graph.
def disjoint_union(self, other):

Creates the disjoint union of two (or more) graphs.

Parametersothergraph or list of graphs to be united with the current one.
Returnsthe disjoint union graph
def union(self, other, byname='auto'):

Creates the union of two (or more) graphs.

Parametersothergraph or list of graphs to be united with the current one.
bynamewhether to use vertex names instead of ids. See igraph.union for details.
Returnsthe union graph
def intersection(self, other, byname='auto'):

Creates the intersection of two (or more) graphs.

Parametersothergraph or list of graphs to be intersected with the current one.
bynamewhether to use vertex names instead of ids. See igraph.intersection for details.
Returnsthe intersection graph
_format_mapping =

Undocumented

(type: dict)
_layout_mapping =

Undocumented

(type: dict[str, str])
API Documentation for python-igraph, generated by pydoctor 21.2.2 at 2021-10-18 16:23:19.