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]
Class Method Adjacency Generates a graph from its adjacency matrix.
Class Method Bipartite Creates a bipartite graph with the given vertex types and edges. This is similar to the default constructor of the graph, the only difference is that it checks whether all the edges go between the two vertex classes and it assigns the type vector to a ...
Class Method DataFrame Generates a graph from one or two dataframes.
Class Method DictList Constructs a graph from a list-of-dictionaries representation.
Class Method from_graph_tool Converts the graph from graph-tool
Class Method from_networkx Converts the graph from networkx
Class Method Full_Bipartite Generates a full bipartite graph (directed or undirected, with or without loops).
Class Method GRG Generates a random geometric graph.
Class Method Incidence Creates a bipartite graph from an incidence matrix.
Class Method Random_Bipartite Generates a random bipartite graph with the given number of vertices and edges (if m is given), or with the given number of vertices and the given connection probability (if p is given).
Class Method Read Unified reading function for graphs.
Class Method Read_Adjacency Constructs a graph based on an adjacency matrix from the given file.
Class Method Read_DIMACS Reads a graph from a file conforming to the DIMACS minimum-cost flow file format.
Class Method Read_GraphMLz Reads a graph from a zipped GraphML file.
Class Method Read_Pickle Reads a graph from Python pickled format
Class Method Read_Picklez Reads a graph from compressed Python pickled format, uncompressing it on-the-fly.
Class Method TupleList Constructs a graph from a list-of-tuples representation.
Class Method Weighted_Adjacency Generates a graph from its weighted adjacency matrix.
Method __add__ Copies the graph and extends the copy depending on the type of the other object given.
Method __and__ Graph intersection operator.
Method __bool__ Returns True if the graph has at least one vertex, False otherwise.
Method __coerce__ Coercion rules.
Method __iadd__ In-place addition (disjoint union).
Method __init__ __init__(n=0, edges=None, directed=False, graph_attrs=None, vertex_attrs=None, edge_attrs=None)
Method __isub__ In-place subtraction (difference).
Method __mul__ Copies exact replicas of the original graph an arbitrary number of times.
Method __or__ Graph union operator.
Method __plot__ Plots the graph to the given Cairo context in the given bounding box
Method __reduce__ Support for pickling.
Method __str__ Returns a string representation of the graph.
Method __sub__ Removes the given object(s) from the graph
Method add_edge Adds a single edge to the graph.
Method add_edges Adds some edges to the graph.
Method add_vertex 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.
Method add_vertices Adds some vertices to the 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 the mincuts between the source and target vertices in a directed 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 biconnected_components Calculates the biconnected components 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 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.
Method clear Clears the graph, deleting all vertices, edges, and attributes.
Method clusters Calculates the (strong or weak) clusters (connected components) for a given graph.
Method cohesive_blocks Calculates the cohesive block structure of the graph.
Method community_edge_betweenness Community structure based on the betweenness of the edges in the network.
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_label_propagation Finds the community structure of the graph according to the label propagation method of Raghavan et al.
Method community_leading_eigenvector Newman's leading eigenvector method for detecting community structure.
Method community_leading_eigenvector_naive Naive implementation of Newman's eigenvector community structure detection.
Method community_leiden Finds the community structure of the graph using the Leiden algorithm of Traag, van Eck & Waltman.
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_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 count_automorphisms_vf2 Returns the number of automorphisms of the graph.
Method degree_distribution Calculates the degree distribution of the graph.
Method delete_edges Deletes some edges from the graph.
Method dfs Conducts a depth first search (DFS) on the graph.
Method disjoint_union Creates the disjoint union of two (or more) graphs.
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_automorphisms_vf2 Returns all the automorphisms of the graph
Method get_edge_dataframe Export edges with attributes to pandas.DataFrame
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 get_inclist Returns the incidence list representation of the graph.
Method get_vertex_dataframe Export vertices with attributes to pandas.DataFrame
Method gomory_hu_tree Calculates the Gomory-Hu tree of an undirected graph with optional edge capacities.
Method indegree Returns the in-degrees in a list.
Method intersection Creates the intersection of two (or more) graphs.
Method is_named Returns whether the graph is named.
Method is_weighted Returns whether the graph is weighted.
Method k_core Returns some k-cores of the graph.
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 maxflow Returns a maximum flow between the given source and target vertices in a graph.
Method maximum_bipartite_matching Finds a maximum matching in a bipartite graph.
Method mincut Calculates the minimum cut between the given source and target vertices or within the whole graph.
Method modularity Calculates the modularity score of the graph with respect to a given clustering.
Method outdegree Returns the out-degrees in a list.
Method pagerank Calculates the PageRank values of a graph.
Method path_length_hist Returns the path length histogram of the graph
Method spanning_tree Calculates a minimum spanning tree for a graph.
Method st_mincut Calculates the minimum cut between the source and target vertices in a graph.
Method summary Returns the summary of the graph.
Method to_graph_tool Converts the graph to graph-tool
Method to_networkx Converts the graph to networkx format.
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 union Creates the union of two (or more) graphs.
Method write Unified writing function for graphs.
Method write_adjacency Writes the adjacency matrix of the graph to the given file
Method write_dimacs Writes the graph in DIMACS format to the given file.
Method write_graphmlz Writes the graph to a zipped GraphML file.
Method write_pickle Saves the graph in Python pickled format
Method write_picklez Saves the graph in Python pickled format, compressed with gzip.
Method write_svg Saves the graph as an SVG (Scalable Vector Graphics) file
Class Variable __hash__ Undocumented
Class Variable __iter__ Undocumented
Class Variable Formula Undocumented
Property es The edge sequence of the graph
Property vs The vertex sequence of the graph
Class Method _identify_format _identify_format(filename)
Class Method _reconstruct Reconstructs a Graph object from Python's pickled format.
Class Variable _format_mapping Undocumented
Class Variable _layout_mapping Undocumented
Property _as_parameter_ Undocumented

Inherited from GraphBase:

Method __new__ Create and return a new object. See help(type) for accurate signature.
Method all_minimal_st_separators Returns a list containing all the minimal s-t separators of a 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 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 cocitation Calculates cocitation scores for given vertices in a graph.
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_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 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_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_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 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_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_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 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 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_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 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_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 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 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.
@classmethod
def Adjacency(cls, matrix, mode='directed', *args, **kwargs):

Generates a graph from its adjacency matrix.

Parameters
matrix

the adjacency matrix. Possible types are:

  • a list of lists
  • a numpy 2D array or matrix (will be converted to list of lists)
  • a scipy.sparse matrix (will be converted to a COO matrix, but not to a dense 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 vertex.
  • "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)
*argsUndocumented
**kwargsUndocumented
@classmethod
def Bipartite(cls, types, edges, directed=False, *args, **kwds):

Creates a bipartite graph with the given vertex types and edges. This is similar to the default constructor of the graph, the only difference is that it checks whether all the edges go between the two vertex classes and it assigns the type vector to a type attribute afterwards.

Examples:

>>> g = Graph.Bipartite([0, 1, 0, 1], [(0, 1), (2, 3), (0, 3)])
>>> g.is_bipartite()
True
>>> g.vs["type"]
[False, True, False, True]
Parameters
typesthe vertex types as a boolean list. Anything that evaluates to False will denote a vertex of the first kind, anything that evaluates to True will denote a vertex of the second kind.
edgesthe edges as a list of tuples.
directedwhether to create a directed graph. Bipartite networks are usually undirected, so the default is False
*argsUndocumented
**kwdsUndocumented
Returns
the graph with a binary vertex attribute named "type" that stores the vertex classes.
@classmethod
def DataFrame(cls, edges, directed=True, vertices=None, use_vids=False):

Generates a graph from one or two dataframes.

Parameters
edgespandas DataFrame containing edges and metadata. The first two columns of this DataFrame contain the source and target vertices for each edge. These indicate the vertex *names* rather than IDs unless `use_vids` is True and these are non-negative integers. Further columns may contain edge attributes.
directedbool setting whether the graph is directed
verticesNone (default) or pandas DataFrame containing vertex metadata. The first column of the DataFrame must contain the unique vertex *names*. If `use_vids` is True, the DataFrame's index must contain the vertex IDs as a sequence of intergers from `0` to `len(vertices) - 1`. All other columns will be added as vertex attributes by column name.
use_vidsUndocumented
Returns

the graph

Vertex names in either the `edges` or `vertices` arguments that are set to NaN (not a number) will be set to the string "NA". That might lead to unexpected behaviour: fill your NaNs with values before calling this function to mitigate.

Unknown Field: use_vids
whether to interpret the first two columns of the `edges` argument as vertex ids (0-based integers) instead of vertex names. If this argument is set to True and the first two columns of `edges` are not integers, an error is thrown.
@classmethod
def DictList(cls, vertices, edges, directed=False, vertex_name_attr='name', edge_foreign_keys=('source', 'target'), iterative=False):

Constructs a graph from a list-of-dictionaries representation.

This representation assumes that vertices and edges are encoded in two lists, each list containing a Python dict for each vertex and each edge, respectively. A distinguished element of the vertex dicts contain a vertex ID which is used in the edge dicts to refer to source and target vertices. All the remaining elements of the dict are considered vertex and edge attributes. Note that the implementation does not assume that the objects passed to this method are indeed lists of dicts, but they should be iterable and they should yield objects that behave as dicts. So, for instance, a database query result is likely to be fit as long as it's iterable and yields dict-like objects with every iteration.

Parameters
verticesthe data source for the vertices or None if there are no special attributes assigned to vertices and we should simply use the edge list of dicts to infer vertex names.
edgesthe data source for the edges.
directedwhether the constructed graph will be directed
vertex_name_attrthe name of the distinguished key in the dicts in the vertex data source that contains the vertex names. Ignored if vertices is None.
edge_foreign_keysthe name of the attributes in the dicts in the edge data source that contain the source and target vertex names.
iterativewhether to add the edges to the graph one by one, iteratively, or to build a large edge list first and use that to construct the graph. The latter approach is faster but it may not be suitable if your dataset is large. The default is to add the edges in a batch from an edge list.
Returns
the graph that was constructed
@classmethod
def from_graph_tool(cls, g):

Converts the graph from graph-tool

Parameters
ggraph-tool Graph
@classmethod
def from_networkx(cls, g):

Converts the graph from networkx

Vertex names will be converted to "_nx_name" attribute and the vertices will get new ids from 0 up (as standard in igraph).

Parameters
gnetworkx Graph or DiGraph
@classmethod
def Full_Bipartite(cls, n1, n2, directed=False, mode='all', *args, **kwds):

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

>>> g = Graph.Full_Bipartite(2, 3)
>>> g.is_bipartite()
True
>>> g.vs["type"]
[False, False, True, True, True]
Parameters
n1the number of vertices of the first kind.
n2the number of vertices of the second kind.
directedwhether tp generate a directed graph.
modeif "out", then all vertices of the first kind are connected to the others; "in" specifies the opposite direction, "all" creates mutual edges. Ignored for undirected graphs.
*argsUndocumented
**kwdsUndocumented
Returns
the graph with a binary vertex attribute named "type" that stores the vertex classes.
@classmethod
def GRG(cls, n, radius, torus=False):

Generates a random geometric graph.

The algorithm drops the vertices randomly on the 2D unit square and connects them if they are closer to each other than the given radius. The coordinates of the vertices are stored in the vertex attributes x and y.

Parameters
nThe number of vertices in the graph
radiusThe given radius
torusThis should be True if we want to use a torus instead of a square.
@classmethod
def Incidence(cls, matrix, directed=False, mode='out', multiple=False, weighted=None, *args, **kwds):

Creates a bipartite graph from an incidence matrix.

Example:

>>> g = Graph.Incidence([[0, 1, 1], [1, 1, 0]])
Parameters
matrixthe incidence matrix.
directedwhether to create a directed graph.
modedefines the direction of edges in the graph. If "out", then edges go from vertices of the first kind (corresponding to rows of the matrix) to vertices of the second kind (the columns of the matrix). If "in", the opposite direction is used. "all" creates mutual edges. Ignored for undirected graphs.
multipledefines what to do with non-zero entries in the matrix. If False, non-zero entries will create an edge no matter what the value is. If True, non-zero entries are rounded up to the nearest integer and this will be the number of multiple edges created.
weighteddefines whether to create a weighted graph from the incidence matrix. If it is c{None} then an unweighted graph is created and the multiple argument is used to determine the edges of the graph. If it is a string then for every non-zero matrix entry, an edge is created and the value of the entry is added as an edge attribute named by the weighted argument. If it is True then a weighted graph is created and the name of the edge attribute will be ‘weight’.
*argsUndocumented
**kwdsUndocumented
Returns
the graph with a binary vertex attribute named "type" that stores the vertex classes.
Raises
ValueErrorif the weighted and multiple are passed together.
@classmethod
def Random_Bipartite(cls, n1, n2, p=None, m=None, directed=False, neimode='all', *args, **kwds):

Generates a random bipartite graph with the given number of vertices and edges (if m is given), or with the given number of vertices and the given connection probability (if p is given).

If m is given but p is not, the generated graph will have n1 vertices of type 1, n2 vertices of type 2 and m randomly selected edges between them. If p is given but m is not, the generated graph will have n1 vertices of type 1 and n2 vertices of type 2, and each edge will exist between them with probability p.

Parameters
n1the number of vertices of type 1.
n2the number of vertices of type 2.
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.
neimodeif the graph is directed, specifies how the edges will be generated. If it is "all", edges will be generated in both directions (from type 1 to type 2 and vice versa) independently. If it is "out" edges will always point from type 1 to type 2. If it is "in", edges will always point from type 2 to type 1. This argument is ignored for undirected graphs.
*argsUndocumented
**kwdsUndocumented
@classmethod
def Read(cls, f, format=None, *args, **kwds):

Unified reading function for graphs.

This method tries to identify the format of the graph given in the first parameter and calls the corresponding reader method.

The remaining arguments are passed to the reader method without any changes.

Parameters
fthe file containing the graph to be loaded
formatthe format of the file (if known in advance). None means auto-detection. Possible values are: "ncol" (NCOL format), "lgl" (LGL format), "graphdb" (GraphDB format), "graphml", "graphmlz" (GraphML and gzipped GraphML format), "gml" (GML format), "net", "pajek" (Pajek format), "dimacs" (DIMACS format), "edgelist", "edges" or "edge" (edge list), "adjacency" (adjacency matrix), "dl" (DL format used by UCINET), "pickle" (Python pickled format), "picklez" (gzipped Python pickled format)
*argsUndocumented
**kwdsUndocumented
Raises
IOErrorif the file format can't be identified and none was given.
@classmethod
def Read_Adjacency(cls, f, sep=None, comment_char='#', attribute=None, *args, **kwds):

Constructs a graph based on an adjacency matrix from the given file.

Additional positional and keyword arguments not mentioned here are passed intact to Adjacency.

Parameters
fthe name of the file to be read or a file object
septhe string that separates the matrix elements in a row. None means an arbitrary sequence of whitespace characters.
comment_charlines starting with this string are treated as comments.
attributean edge attribute name where the edge weights are stored in the case of a weighted adjacency matrix. If None, no weights are stored, values larger than 1 are considered as edge multiplicities.
*argsUndocumented
**kwdsUndocumented
Returns
the created graph
@classmethod
def Read_DIMACS(cls, f, directed=False):

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

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

Restrictions compared to the official description of the format are as follows:

  • 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 indices of the source and target vertices are attached as graph attributes source and target, the edge capacities are stored in the capacity edge attribute.
@classmethod
def Read_GraphMLz(cls, f, directed=True, index=0):

Reads a graph from a zipped GraphML file.

Parameters
fthe name of the file
directedUndocumented
indexif the GraphML file contains multiple graphs, specified the one that should be loaded. Graph indices start from zero, so if you want to load the first graph, specify 0 here.
Returns
the loaded graph object
@classmethod
def Read_Pickle(cls, fname=None):

Reads a graph from Python pickled format

Parameters
fnamethe name of the file, a stream to read from, or a string containing the pickled data.
Returns
the created graph object.
@classmethod
def Read_Picklez(cls, fname):

Reads a graph from compressed Python pickled format, uncompressing it on-the-fly.

Parameters
fnamethe name of the file or a stream to read from.
Returns
the created graph object.
@classmethod
def TupleList(cls, edges, directed=False, vertex_name_attr='name', edge_attrs=None, weights=False):

Constructs a graph from a list-of-tuples representation.

This representation assumes that the edges of the graph are encoded in a list of tuples (or lists). Each item in the list must have at least two elements, which specify the source and the target vertices of the edge. The remaining elements (if any) specify the edge attributes of that edge, where the names of the edge attributes originate from the edge_attrs list. The names of the vertices will be stored in the vertex attribute given by vertex_name_attr.

The default parameters of this function are suitable for creating unweighted graphs from lists where each item contains the source vertex and the target vertex. If you have a weighted graph, you can use items where the third item contains the weight of the edge by setting edge_attrs to "weight" or ["weight"]. If you have even more edge attributes, add them to the end of each item in the edges list and also specify the corresponding edge attribute names in edge_attrs as a list.

Parameters
edgesthe data source for the edges. This must be a list where each item is a tuple (or list) containing at least two items: the name of the source and the target vertex. Note that names will be assigned to the name vertex attribute (or another vertex attribute if vertex_name_attr is specified), even if all the vertex names in the list are in fact numbers.
directedwhether the constructed graph will be directed
vertex_name_attrthe name of the vertex attribute that will contain the vertex names.
edge_attrsthe names of the edge attributes that are filled with the extra items in the edge list (starting from index 2, since the first two items are the source and target vertices). None means that only the source and target vertices will be extracted from each item. If you pass a string here, it will be wrapped in a list for convenience.
weightsalternative way to specify that the graph is weighted. If you set weights to true and edge_attrs is not given, it will be assumed that edge_attrs is ["weight"] and igraph will parse the third element from each item into an edge weight. If you set weights to a string, it will be assumed that edge_attrs contains that string only, and igraph will store the edge weights in that attribute.
Returns
the graph that was constructed
@classmethod
def Weighted_Adjacency(cls, matrix, mode='directed', attr='weight', loops=True):

Generates a graph from its weighted adjacency matrix.

Parameters
matrix

the adjacency matrix. Possible types are:

  • a list of lists
  • a numpy 2D array or matrix (will be converted to list of lists)
  • a scipy.sparse matrix (will be converted to a COO matrix, but not to a dense 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 vertex.
  • "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)

These values can also be given as strings without the ADJ prefix.

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 __add__(self, other):

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

Parameters
otherif 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.

Parameters
otherthe other graph to take the intersection with.
Returns
the intersected graph.
def __bool__(self):

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

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.

def __iadd__(self, other):

In-place addition (disjoint union).

See Also
__add__
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.

Parameters
*argsUndocumented
**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 __isub__(self, other):

In-place subtraction (difference).

See Also
__sub__
def __mul__(self, other):

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

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

Graph union operator.

Parameters
otherthe other graph to take the union with.
Returns
the union graph.
def __plot__(self, context, bbox, palette, *args, **kwds):

Plots the graph to the given Cairo context in the given bounding box

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 __reduce__(self):

Support for pickling.

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 __sub__(self, other):

Removes the given object(s) from the graph

Parameters
otherif 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 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.

Parameters
sourcethe source vertex of the edge or its name.
targetthe target vertex of the edge or its name.
**kwdsUndocumented
Returns
the 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.

Parameters
esthe 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.

Returns
the 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.

Parameters
nthe 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 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.

Parameters
sourcethe source vertex ID
targetthe target vertex ID
Returns
a list of Cut objects.
Unknown Field: newfield
refReference
Unknown Field: ref
JS 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.

Parameters
sourcethe source vertex ID
targetthe target vertex ID
capacitythe edge capacities (weights). If None, all edges have equal weight. May also be an attribute name.
Returns
a list of Cut objects.
Unknown Field: newfield
refReference
Unknown Field: ref
JS Provan and DR Shier: A paradigm for listing (s,t)-cuts in graphs. Algorithmica 15, 351--372, 1996.
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 biconnected_components(self, return_articulation_points=False):

Calculates the biconnected components of the graph.

Parameters
return_articulation_pointswhether to return the articulation points as well
Returns
a VertexCover object describing the biconnected components, and optionally the list of articulation points as well
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
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.
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.
Returns
a 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.

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.
*argsUndocumented
**kwdsUndocumented
Returns
a 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 clear(self):

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

See Also
delete_vertices and delete_edges.
def clusters(self, mode='strong'):

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

Parameters
modemust be either "strong" or "weak", depending on the clusters being sought. Optional, defaults to "strong".
Returns
a VertexClustering object
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.

Returns
an instance of CohesiveBlocks. See the documentation of CohesiveBlocks for more information.
See Also
CohesiveBlocks
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.

Parameters
clustersthe 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.
Returns
a VertexDendrogram object, initally cut at the maximum modularity or at the desired number of clusters.
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.

Parameters
weightsedge attribute name or a list containing edge weights
Returns
an appropriate VertexDendrogram object.
Unknown Field: newfield
refReference
Unknown Field: ref
A 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.

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
an appropriate VertexClustering object with an extra attribute called codelength that stores the code length determined by the algorithm.
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://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_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.

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. It may also be the name of a vertex attribute; each attribute value will be interpreted as a Boolean.
Returns
an appropriate VertexClustering object.
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(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.

Parameters
clustersthe 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.
Returns
an appropriate VertexClustering object.
Unknown Field: newfield
refReference
Unknown Field: ref
MEJ Newman: Finding community structure in networks using the eigenvectors of matrices, arXiv:physics/0605087
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.

Parameters
clustersthe 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.
Returns
an appropriate VertexClustering or VertexDendrogram object.
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(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.

Parameters
objective_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.
Returns
an appropriate VertexClustering object.
Unknown Field: newfield
refReference
Unknown Field: ref
Traag, 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 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.

Parameters
weightsedge 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.
Returns
a list of VertexClustering objects, one corresponding to each level (if return_levels is True), or a VertexClustering corresponding to the best modularity.
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(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.

Returns
the calculated membership vector and the corresponding modularity in a tuple.
def community_spinglass(self, *args, **kwds):

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

Parameters
*argsUndocumented
**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.
Returns
an appropriate VertexClustering object.
Unknown Field: newfield
refReference
Unknown Field: ref
Reichardt 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.

Parameters
weightsname of an edge attribute or a list containing edge weights
stepslength of random walks to perform
Returns
a VertexDendrogram object, initially cut at the maximum modularity.
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 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.

Returns
the number of automorphisms of the graph
See Also
Graph.count_isomorphisms_vf2
def degree_distribution(self, bin_width=1, *args, **kwds):

Calculates the degree distribution of the graph.

Unknown keyword arguments are directly passed to degree().

Parameters
bin_widththe bin width of the histogram
*argsUndocumented
**kwdsUndocumented
Returns
a histogram representing the degree distribution of the graph.
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: deprecated
delete_edges(None) has been replaced by delete_edges() - with no arguments - since igraph 0.8.3.
def dfs(self, vid, mode=OUT):

Conducts a depth first search (DFS) 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 parent of every vertex in the DFS
def disjoint_union(self, other):

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

Parameters
othergraph or list of graphs to be united with the current one.
Returns
the disjoint union 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).

Returns
a DyadCensus object.
Unknown Field: newfield
refReference
Unknown Field: ref
Holland, 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.

Parameters
typeeither 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.
Returns
the adjacency matrix as a Matrix.
def get_adjacency_sparse(self, attribute=None):

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

Parameters
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.
Returns
the 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.

Parameters
modeif "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.

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.
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.
Returns
all of the simple paths from the given node to every other reachable node in the graph in a list. Note that in case of mode="in", the vertices in a path are returned in reversed order!
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.

Returns
a list of lists, each item containing a possible mapping of the graph vertices to itself according to the automorphism
See Also
Graph.get_isomorphisms_vf2
def get_edge_dataframe(self):

Export edges with attributes to pandas.DataFrame

If you want to use source and target vertex IDs as index, you can do:

>>> from string import ascii_letters
>>> graph = Graph.GRG(25, 0.4)
>>> graph.vs["name"] = ascii_letters[:graph.vcount()]
>>> df = graph.get_edge_dataframe()
>>> df.set_index(['source', 'target'], inplace=True)

The index will be a pandas.MultiIndex. You can use the `drop=False` option to keep the `source` and `target` columns.

If you want to use vertex names in the source and target columns:

>>> df = graph.get_edge_dataframe()
>>> df_vert = graph.get_vertex_dataframe()
>>> df['source'].replace(df_vert['name'], inplace=True)
>>> df['target'].replace(df_vert['name'], inplace=True)
>>> df_vert.set_index('name', inplace=True)  # Optional
Returns
a pandas.DataFrame representing edges and their attributes. The index uses edge IDs, from 0 to M - 1 where M is the number of edges. The first two columns of the dataframe represent the IDs of source and target vertices for each edge. These columns have names "source" and "target". If your edges have attributes with the same names, they will be present in the dataframe, but not in the first two columns.
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.

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.
*argsUndocumented
**kwdsUndocumented
Returns
the 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 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.

Parameters
modeif "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_vertex_dataframe(self):

Export vertices with attributes to pandas.DataFrame

If you want to use vertex names as index, you can do:

>>> from string import ascii_letters
>>> graph = Graph.GRG(25, 0.4)
>>> graph.vs["name"] = ascii_letters[:graph.vcount()]
>>> df = graph.get_vertex_dataframe()
>>> df.set_index('name', inplace=True)
Returns
a pandas.DataFrame representing vertices and their attributes. The index uses vertex IDs, from 0 to N - 1 where N is the number of vertices.
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.

Parameters
capacitythe 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.
Returns
the Gomory-Hu tree as a Graph object.
def indegree(self, *args, **kwds):

Returns the in-degrees in a list.

See degree for possible arguments.

def intersection(self, other, byname='auto'):

Creates the intersection of two (or more) graphs.

Parameters
othergraph or list of graphs to be intersected with the current one.
bynamewhether to use vertex names instead of ids. See igraph.intersection for details.
Returns
the intersection graph
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 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 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:

  • auto, automatic: automatic layout (see layout_auto)
  • bipartite: bipartite layout (see layout_bipartite)
  • circle, circular: circular layout (see layout_circle)
  • dh, davidson_harel: Davidson-Harel layout (see layout_davidson_harel)
  • drl: DrL layout for large graphs (see layout_drl)
  • drl_3d: 3D DrL layout for large graphs (see layout_drl)
  • fr, fruchterman_reingold: Fruchterman-Reingold layout (see layout_fruchterman_reingold).
  • fr_3d, fr3d, fruchterman_reingold_3d: 3D Fruchterman- Reingold layout (see layout_fruchterman_reingold).
  • grid: regular grid layout in 2D (see layout_grid)
  • grid_3d: regular grid layout in 3D (see layout_grid_3d)
  • graphopt: the graphopt algorithm (see layout_graphopt)
  • kk, kamada_kawai: Kamada-Kawai layout (see layout_kamada_kawai)
  • kk_3d, kk3d, kamada_kawai_3d: 3D Kamada-Kawai layout (see layout_kamada_kawai)
  • lgl, large, large_graph: Large Graph Layout (see layout_lgl)
  • mds: multidimensional scaling layout (see layout_mds)
  • random: random layout (see layout_random)
  • random_3d: random 3D layout (see layout_random)
  • rt, tree, reingold_tilford: Reingold-Tilford tree layout (see layout_reingold_tilford)
  • rt_circular, reingold_tilford_circular: circular Reingold-Tilford tree layout (see layout_reingold_tilford_circular)
  • sphere, spherical, circle_3d, circular_3d: spherical layout (see layout_circle)
  • star: star layout (see layout_star)
  • sugiyama: Sugiyama layout (see layout_sugiyama)
Parameters
layoutthe 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
Returns
a 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).

Parameters
*argsUndocumented
**kwdsUndocumented
dimspecifies whether we would like to obtain a 2D or a 3D layout.
Returns
a 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.

Parameters
layersa 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.
Returns
the 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: newfield
refReference
Unknown Field: ref
K 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 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.

Parameters
sourceUndocumented
targetUndocumented
capacitythe edge capacities (weights). If None, all edges have equal weight. May also be an attribute name.
Returns
a Flow object describing the maximum flow
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.

Parameters
typesvertex 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.
Returns
an instance of Matching.
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.

Parameters
sourcethe 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.
Returns
a Cut object describing the minimum cut
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.

Parameters
membershipa membership list or a VertexClustering object
weightsoptional edge weights or None if all edges are weighed equally. Attribute names are also allowed.
Returns
the modularity score
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 outdegree(self, *args, **kwds):

Returns the out-degrees in a list.

See degree for possible arguments.

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.

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 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.
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 Google PageRank values of the specified vertices.
def path_length_hist(self, directed=True):

Returns the path length histogram of the graph

Parameters
directedwhether to consider directed paths. Ignored for undirected graphs.
Returns
a 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 spanning_tree(self, weights=None, return_tree=True):

Calculates a minimum spanning tree for a graph.

Parameters
weightsa 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.
Returns
the 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: newfield
refReference
Unknown Field: ref
Prim, R.C.: Shortest connection networks and some generalizations. Bell System Technical Journal 36:1389-1401, 1957.
def st_mincut(self, source, target, capacity=None):

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

Parameters
verbosityif 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
Returns
the summary of the graph.
def to_graph_tool(self, graph_attributes=None, vertex_attributes=None, edge_attributes=None):

Converts the graph to graph-tool

Data types: graph-tool only accepts specific data types. See the following web page for a list:

https://graph-tool.skewed.de/static/doc/quickstart.html

Note: because of the restricted data types in graph-tool, vertex and edge attributes require to be type-consistent across all vertices or edges. If you set the property for only some vertices/edges, the other will be tagged as None in python-igraph, so they can only be converted to graph-tool with the type 'object' and any other conversion will fail.

Parameters
graph_attributesdictionary of graph attributes to transfer. Keys are attributes from the graph, values are data types (see below). None means no graph attributes are transferred.
vertex_attributesdictionary of vertex attributes to transfer. Keys are attributes from the vertices, values are data types (see below). None means no vertex attributes are transferred.
edge_attributesdictionary of edge attributes to transfer. Keys are attributes from the edges, values are data types (see below). None means no vertex attributes are transferred.
def to_networkx(self, create_using=None):

Converts the graph to networkx format.

Parameters
create_usingspecifies which NetworkX graph class to use when constructing the graph. None means to let igraph infer the most appropriate class based on whether the graph is directed and whether it has multi-edges.
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.

Parameters
modedefines 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 Also
transitivity_undirected(), transitivity_local_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 triad_census(self, *args, **kwds):

Calculates the triad census of the graph.

Returns
a TriadCensus object.
Unknown Field: newfield
refReference
Unknown Field: ref
Davis, 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 union(self, other, byname='auto'):

Creates the union of two (or more) graphs.

Parameters
othergraph or list of graphs to be united with the current one.
bynamewhether to use vertex names instead of ids. See igraph.union for details.
Returns
the union graph
def write(self, f, format=None, *args, **kwds):

Unified writing function for graphs.

This method tries to identify the format of the graph given in the first parameter (based on extension) and calls the corresponding writer method.

The remaining arguments are passed to the writer method without any changes.

Parameters
fthe file containing the graph to be saved
format

the format of the file (if one wants to override the format determined from the filename extension, or the filename itself is a stream). None means auto-detection. Possible values are:

  • "adjacency": adjacency matrix format
  • "dimacs": DIMACS format
  • "dot", "graphviz": GraphViz DOT format
  • "edgelist", "edges" or "edge": numeric edge list format
  • "gml": GML format
  • "graphml" and "graphmlz": standard and gzipped GraphML format
  • "gw", "leda", "lgr": LEDA native format
  • "lgl": LGL format
  • "ncol": NCOL format
  • "net", "pajek": Pajek format
  • "pickle", "picklez": standard and gzipped Python pickled format
  • "svg": SVG format
*argsUndocumented
**kwdsUndocumented
Raises
IOErrorif the file format can't be identified and none was given.
def write_adjacency(self, f, sep=' ', eol='\n', *args, **kwds):

Writes the adjacency matrix of the graph to the given file

All the remaining arguments not mentioned here are passed intact to Graph.get_adjacency.

Parameters
fthe name of the file to be written.
septhe string that separates the matrix elements in a row
eolthe string that separates the rows of the matrix. Please note that igraph is able to read back the written adjacency matrix if and only if this is a single newline character
*argsUndocumented
**kwdsUndocumented
def write_dimacs(self, f, source=None, target=None, capacity='capacity'):

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. If None, igraph will try to infer it from the source graph attribute.
targetthe target vertex ID. If None, igraph will try to infer it from the target graph attribute.
capacitythe capacities of the edges in a list or the name of an edge attribute that holds the capacities. If there is no such edge attribute, every edge will have a capacity of 1.
def write_graphmlz(self, f, compresslevel=9):

Writes the graph to a zipped GraphML file.

The library uses the gzip compression algorithm, so the resulting file can be unzipped with regular gzip uncompression (like gunzip or zcat from Unix command line) or the Python gzip module.

Uses a temporary file to store intermediate GraphML data, so make sure you have enough free space to store the unzipped GraphML file as well.

Parameters
fthe name of the file to be written.
compresslevelthe level of compression. 1 is fastest and produces the least compression, and 9 is slowest and produces the most compression.
def write_pickle(self, fname=None, version=-1):

Saves the graph in Python pickled format

Parameters
fnamethe name of the file or a stream to save to. If None, saves the graph to a string and returns the string.
versionpickle protocol version to be used. If -1, uses the highest protocol available
Returns
None if the graph was saved successfully to the given file, or a string if fname was None.
def write_picklez(self, fname=None, version=-1):

Saves the graph in Python pickled format, compressed with gzip.

Saving in this format is a bit slower than saving in a Python pickle without compression, but the final file takes up much less space on the hard drive.

Parameters
fnamethe name of the file or a stream to save to.
versionpickle protocol version to be used. If -1, uses the highest protocol available
Returns
None if the graph was saved successfully to the given file.
def write_svg(self, fname, layout='auto', width=None, height=None, labels='label', colors='color', shapes='shape', vertex_size=10, edge_colors='color', edge_stroke_widths='width', font_size=16, *args, **kwds):

Saves the graph as an SVG (Scalable Vector Graphics) file

The file will be Inkscape (http://inkscape.org) compatible. In Inkscape, as nodes are rearranged, the edges auto-update.

Parameters
fnamethe name of the file or a Python file handle
layoutthe layout of the graph. Can be either an explicitly specified layout (using a list of coordinate pairs) or the name of a layout algorithm (which should refer to a method in the Graph object, but without the layout_ prefix.
widththe preferred width in pixels (default: 400)
heightthe preferred height in pixels (default: 400)
labelsthe vertex labels. Either it is the name of a vertex attribute to use, or a list explicitly specifying the labels. It can also be None.
colorsthe vertex colors. Either it is the name of a vertex attribute to use, or a list explicitly specifying the colors. A color can be anything acceptable in an SVG file.
shapesthe vertex shapes. Either it is the name of a vertex attribute to use, or a list explicitly specifying the shapes as integers. Shape 0 means hidden (nothing is drawn), shape 1 is a circle, shape 2 is a rectangle and shape 3 is a rectangle that automatically sizes to the inner text.
vertex_sizevertex size in pixels
edge_colorsthe edge colors. Either it is the name of an edge attribute to use, or a list explicitly specifying the colors. A color can be anything acceptable in an SVG file.
edge_stroke_widthsthe stroke widths of the edges. Either it is the name of an edge attribute to use, or a list explicitly specifying the stroke widths. The stroke width can be anything acceptable in an SVG file.
font_sizefont size. If it is a string, it is written into the SVG file as-is (so you can specify anything which is valid as the value of the font-size style). If it is a number, it is interpreted as pixel size and converted to the proper attribute value accordingly.
*argsUndocumented
**kwdsUndocumented
__hash__ =

Undocumented

__iter__ =

Undocumented

Formula =

Undocumented

@property
es =

The edge sequence of the graph

@property
vs =

The vertex sequence of the graph

@classmethod
def _identify_format(cls, filename):

_identify_format(filename)

Tries to identify the format of the graph stored in the file with the given filename. It identifies most file formats based on the extension of the file (and not on syntactic evaluation). The only exception is the adjacency matrix format and the edge list format: the first few lines of the file are evaluated to decide between the two.

Parameters
filenamethe name of the file or a file object whose name attribute is set.
Returns
the format of the file as a string.
Note
Internal function, should not be called directly.
@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.

_format_mapping: dict =

Undocumented

_layout_mapping: dict[str, str] =

Undocumented

@property
_as_parameter_ =

Undocumented