Movatterモバイル変換


[0]ホーム

URL:


igraph Reference Manual

For using the igraph C library

Search the manual:

Chapter 9. Graph generators

Graph generators create graphs.

Almost all functions which create graph objects are documentedhere. The exceptions areigraph_induced_subgraph() and alike, thesecreate graphs based on another graph.

1. Deterministic graph generators

1.1.igraph_create — Creates a graph with the specified edges.
1.2.igraph_small — Shorthand to create a small graph, giving the edges as arguments.
1.3.igraph_adjacency — Creates a graph from an adjacency matrix.
1.4.igraph_weighted_adjacency — Creates a graph from a weighted adjacency matrix.
1.5.igraph_sparse_adjacency — Creates a graph from a sparse adjacency matrix.
1.6.igraph_sparse_weighted_adjacency — Creates a graph from a weighted sparse adjacency matrix.
1.7.igraph_adjlist — Creates a graph from an adjacency list.
1.8.igraph_star — Creates astar graph, every vertex connects only to the center.
1.9.igraph_wheel — Creates awheel graph, a union of a star and a cycle graph.
1.10.igraph_hypercube — The n-dimensional hypercube graph.
1.11.igraph_square_lattice — Arbitrary dimensional square lattices.
1.12.igraph_triangular_lattice — A triangular lattice with the given shape.
1.13.igraph_hexagonal_lattice — A hexagonal lattice with the given shape.
1.14.igraph_ring — Creates acycle graph or apath graph.
1.15.igraph_path_graph — A path graphP_n.
1.16.igraph_cycle_graph — A cycle graphC_n.
1.17.igraph_kary_tree — Creates a k-ary tree in which almost all vertices have k children.
1.18.igraph_symmetric_tree — Creates a symmetric tree with the specified number of branches at each level.
1.19.igraph_regular_tree — Creates a regular tree.
1.20.igraph_tree_from_parent_vector — Constructs a tree or forest from a vector encoding the parent of each vertex.
1.21.igraph_full — Creates a full graph (complete graph).
1.22.igraph_full_citation — Creates a full citation graph (a complete directed acyclic graph).
1.23.igraph_full_multipartite — Creates a full multipartite graph.
1.24.igraph_turan — Creates a Turán graph.
1.25.igraph_realize_degree_sequence — Generates a graph with the given degree sequence.
1.26.igraph_realize_bipartite_degree_sequence — Generates a bipartite graph with the given bidegree sequence.
1.27.igraph_famous — Create a famous graph by simply providing its name.
1.28.igraph_lcf — Creates a graph from LCF notation.
1.29.igraph_lcf_vector — Creates a graph from LCF notation.
1.30.igraph_mycielski_graph — The Mycielski graph of orderk.
1.31.igraph_from_prufer — Generates a tree from a Prüfer sequence.
1.32.igraph_atlas — Create a small graph from theGraph Atlas.
1.33.igraph_de_bruijn — Generate a de Bruijn graph.
1.34.igraph_kautz — Generate a Kautz graph.
1.35.igraph_circulant — Creates a circulant graph.
1.36.igraph_generalized_petersen — Creates a Generalized Petersen graph.
1.37.igraph_extended_chordal_ring — Create an extended chordal ring.

1.1. igraph_create — Creates a graph with the specified edges.

igraph_error_t igraph_create(igraph_t *graph, const igraph_vector_int_t *edges,                  igraph_integer_t n, igraph_bool_t directed);

Arguments: 

graph:

An uninitialized graph object.

edges:

The edges to add, the first two elements are the first edge, etc.

n:

The number of vertices in the graph, if smaller or equal to the highest vertex ID in theedges vector it will be increased automatically. So it is safe to give 0 here.

directed:

Boolean, whether to create a directed graph or not. If yes, then the first edge points from the first vertex ID inedges to the second, etc.

Returns: 

Error code:IGRAPH_EINVEVECTOR: invalid edges vector (odd number of vertices).IGRAPH_EINVVID: invalid (negative) vertex ID.

Time complexity: O(|V|+|E|),|V| is the number of vertices,|E| the number of edges in thegraph.

Example 9.1.  Fileexamples/simple/igraph_create.c

#include <igraph.h>intmain(void) {    igraph_t g;    igraph_vector_int_t v1, v2;/* simple use */igraph_vector_int_init(&v1, 8);VECTOR(v1)[0] = 0;VECTOR(v1)[1] = 1;VECTOR(v1)[2] = 1;VECTOR(v1)[3] = 2;VECTOR(v1)[4] = 2;VECTOR(v1)[5] = 3;VECTOR(v1)[6] = 2;VECTOR(v1)[7] = 2;igraph_create(&g, &v1, 0, 0);if (igraph_vcount(&g) != 4) {return 1;    }igraph_vector_int_init(&v2, 0);igraph_get_edgelist(&g, &v2, 0);igraph_vector_int_sort(&v1);igraph_vector_int_sort(&v2);if (!igraph_vector_int_all_e(&v1, &v2)) {return 2;    }igraph_destroy(&g);/* higher number of vertices */igraph_create(&g, &v1, 10, 0);if (igraph_vcount(&g) != 10) {return 1;    }igraph_get_edgelist(&g, &v2, 0);igraph_vector_int_sort(&v1);igraph_vector_int_sort(&v2);if (!igraph_vector_int_all_e(&v1, &v2)) {return 3;    }igraph_destroy(&g);igraph_vector_int_destroy(&v1);igraph_vector_int_destroy(&v2);return 0;}


1.2. igraph_small — Shorthand to create a small graph, giving the edges as arguments.

igraph_error_t igraph_small(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed,                            int first, ...);

This function is handy when a relatively small graph needs to be created.Instead of giving the edges as a vector, they are given simply asarguments and a-1 needs to be given after the last meaningfuledge argument.

This function is intended to be used with vertex IDs that are entered asliteral integers. If you use a variable instead of a literal, make surethat it is of typeint, as this is the type that this functionassumes for all variadic arguments. Using a different integer type isundefined behaviour and likely to cause platform-specific issues.

Arguments: 

graph:

Pointer to an uninitialized graph object. The result will be stored here.

n:

The number of vertices in the graph; a non-negative integer.

directed:

Boolean constant; gives whether the graph should be directed. Supported values are:

IGRAPH_DIRECTED

The graph to be created will bedirected.

IGRAPH_UNDIRECTED

The graph to be created will beundirected.

...:

The additional arguments giving the edges of the graph, andmust be of typeint. Don't forget to supply an additional-1 after the last (meaningful) argument. Thefirst parameter is present for technical reasons and represents the first variadic argument.

Returns: 

Error code.

Time complexity: O(|V|+|E|), the number of vertices plus the numberof edges in the graph to create.

Example 9.2.  Fileexamples/simple/igraph_small.c

#include <igraph.h>intmain(void) {    igraph_t g;igraph_small(&g, 0, IGRAPH_DIRECTED, 0, 1, 1, 2, 2, 3, 3, 4, 6, 1, -1);igraph_write_graph_edgelist(&g, stdout);igraph_destroy(&g);return 0;}


1.3. igraph_adjacency — Creates a graph from an adjacency matrix.

igraph_error_t igraph_adjacency(    igraph_t *graph, const igraph_matrix_t *adjmatrix, igraph_adjacency_t mode,    igraph_loops_t loops);

The order of the vertices in the matrix is preserved, i.e. the vertexcorresponding to the first row/column will be vertex with id 0, thenext row is for vertex 1, etc.

Arguments: 

graph:

Pointer to an uninitialized graph object.

adjmatrix:

The adjacency matrix. How it is interpreted depends on themode argument.

mode:

Constant to specify how the given matrix is interpreted as an adjacency matrix. Possible values (A(i,j) is the element in row i and column j in the adjacency matrixadjmatrix):

IGRAPH_ADJ_DIRECTED

The graph will be directed and an element gives the number of edges between two vertices.

IGRAPH_ADJ_UNDIRECTED

The graph will be undirected and an element gives the number of edges between two vertices. If the input matrix is not symmetric, an error is thrown.

IGRAPH_ADJ_MAX

An undirected graph will be created and the number of edges between vertices i and j is max(A(i,j), A(j,i)).

IGRAPH_ADJ_MIN

An undirected graph will be created with min(A(i,j), A(j,i)) edges between vertices i and j.

IGRAPH_ADJ_PLUS

An undirected graph will be created with A(i,j)+A(j,i) edges between vertices i and j.

IGRAPH_ADJ_UPPER

An undirected graph will be created. Only the upper right triangle (including the diagonal) is used for the number of edges.

IGRAPH_ADJ_LOWER

An undirected graph will be created. Only the lower left triangle (including the diagonal) is used for the number of edges.

loops:

Constant to specify how the diagonal of the matrix should be treated when creating loop edges.

IGRAPH_NO_LOOPS

Ignore the diagonal of the input matrix and do not create loops.

IGRAPH_LOOPS_ONCE

Treat the diagonal entries as the number of loop edges incident on the corresponding vertex.

IGRAPH_LOOPS_TWICE

Treat the diagonal entries astwice the number of loop edges incident on the corresponding vertex. Odd numbers in the diagonal will return an error code.

Returns: 

Error code,IGRAPH_NONSQUARE: non-square matrix.IGRAPH_EINVAL: Negative entry was found in adjacency matrix, or an odd number was found in the diagonal withIGRAPH_LOOPS_TWICE

Time complexity: O(|V||V|),|V| is the number of vertices in the graph.

Example 9.3.  Fileexamples/simple/igraph_adjacency.c

#include <igraph.h>intmain(void) {return 0;}


1.4. igraph_weighted_adjacency — Creates a graph from a weighted adjacency matrix.

igraph_error_t igraph_weighted_adjacency(    igraph_t *graph, const igraph_matrix_t *adjmatrix, igraph_adjacency_t mode,    igraph_vector_t *weights, igraph_loops_t loops);

The order of the vertices in the matrix is preserved, i.e. the vertexcorresponding to the first row/column will be vertex with id 0, thenext row is for vertex 1, etc.

Arguments: 

graph:

Pointer to an uninitialized graph object.

adjmatrix:

The weighted adjacency matrix. How it is interpreted depends on themode argument. The common feature is that edges with zero weights are considered nonexistent (however, negative weights are permitted).

mode:

Constant to specify how the given matrix is interpreted as an adjacency matrix. Possible values (A(i,j) is the element in row i and column j in the adjacency matrixadjmatrix):

IGRAPH_ADJ_DIRECTED

the graph will be directed and an element gives the weight of the edge between two vertices.

IGRAPH_ADJ_UNDIRECTED

this is the same asIGRAPH_ADJ_MAX, for convenience.

IGRAPH_ADJ_MAX

undirected graph will be created and the weight of the edge between vertices i and j is max(A(i,j), A(j,i)).

IGRAPH_ADJ_MIN

undirected graph will be created with edge weight min(A(i,j), A(j,i)) between vertices i and j.

IGRAPH_ADJ_PLUS

undirected graph will be created with edge weight A(i,j)+A(j,i) between vertices i and j.

IGRAPH_ADJ_UPPER

undirected graph will be created, only the upper right triangle (including the diagonal) is used for the edge weights.

IGRAPH_ADJ_LOWER

undirected graph will be created, only the lower left triangle (including the diagonal) is used for the edge weights.

weights:

Pointer to an initialized vector, the weights will be stored here.

loops:

Constant to specify how the diagonal of the matrix should be treated when creating loop edges.

IGRAPH_NO_LOOPS

Ignore the diagonal of the input matrix and do not create loops.

IGRAPH_LOOPS_ONCE

Treat the diagonal entries as the weight of the loop edge incident on the corresponding vertex.

IGRAPH_LOOPS_TWICE

Treat the diagonal entries astwice the weight of the loop edge incident on the corresponding vertex.

Returns: 

Error code,IGRAPH_NONSQUARE: non-square matrix.

Time complexity: O(|V||V|),|V| is the number of vertices in the graph.

Example 9.4.  Fileexamples/simple/igraph_weighted_adjacency.c

#include <igraph.h>#include <stdarg.h>intmain(void) {    igraph_matrix_t mat;    igraph_t g;    int m[4][4] = { { 0, 1, 2, 0 }, { 2, 0, 0, 1 }, { 0, 0, 1, 0 }, { 0, 1, 0, 0 } };igraph_vector_t weights;    igraph_vector_int_t el;    igraph_integer_t i, j, n;igraph_vector_int_init(&el, 0);igraph_vector_init(&weights, 0);igraph_matrix_init(&mat, 4, 4);for (i = 0; i < 4; i++)for (j = 0; j < 4; j++) {MATRIX(mat, i, j) = m[i][j];    }igraph_weighted_adjacency(&g, &mat, IGRAPH_ADJ_DIRECTED, &weights, IGRAPH_LOOPS_ONCE);igraph_get_edgelist(&g, &el, 0);    n =igraph_ecount(&g);for (i = 0, j = 0; i < n; i++, j += 2) {printf("%" IGRAPH_PRId " --> %" IGRAPH_PRId ": %g\n",VECTOR(el)[j],VECTOR(el)[j + 1],VECTOR(weights)[i]);    }igraph_matrix_destroy(&mat);igraph_vector_destroy(&weights);igraph_vector_int_destroy(&el);igraph_destroy(&g);}


1.5. igraph_sparse_adjacency — Creates a graph from a sparse adjacency matrix.

igraph_error_t igraph_sparse_adjacency(igraph_t *graph, igraph_sparsemat_t *adjmatrix,        igraph_adjacency_t mode, igraph_loops_t loops);

This has the same functionality asigraph_adjacency(), but usesa column-compressed adjacency matrix.

Time complexity: O(|E|),where |E| is the number of edges in the graph.

1.6. igraph_sparse_weighted_adjacency — Creates a graph from a weighted sparse adjacency matrix.

igraph_error_t igraph_sparse_weighted_adjacency(    igraph_t *graph, igraph_sparsemat_t *adjmatrix, igraph_adjacency_t mode,    igraph_vector_t *weights, igraph_loops_t loops);

This has the same functionality asigraph_weighted_adjacency(), but usesa column-compressed adjacency matrix.

Time complexity: O(|E|),where |E| is the number of edges in the graph.

1.7. igraph_adjlist — Creates a graph from an adjacency list.

igraph_error_t igraph_adjlist(igraph_t *graph, const igraph_adjlist_t *adjlist,                   igraph_neimode_t mode, igraph_bool_t duplicate);

An adjacency list is a list of vectors, containing the neighborsof all vertices. For operations that involve many changes to thegraph structure, it is recommended that you convert the graph intoan adjacency list viaigraph_adjlist_init(), perform themodifications (these are cheap for an adjacency list) and thenrecreate the igraph graph via this function.

Arguments: 

graph:

Pointer to an uninitialized graph object.

adjlist:

The adjacency list.

mode:

Whether or not to create a directed graph.IGRAPH_ALL means an undirected graph,IGRAPH_OUT means a directed graph from an out-adjacency list (i.e. each list contains the successors of the corresponding vertices),IGRAPH_IN means a directed graph from an in-adjacency list

duplicate:

Boolean constant. For undirected graphs this specifies whether each edge is included twice, in the vectors of both adjacent vertices. If this isfalse, then it is assumed that every edge is included only once. This argument is ignored for directed graphs.

Returns: 

Error code.

See also: 

igraph_adjlist_init() for the opposite operation.

Time complexity: O(|V|+|E|).

1.8. igraph_star — Creates astar graph, every vertex connects only to the center.

igraph_error_t igraph_star(igraph_t *graph, igraph_integer_t n, igraph_star_mode_t mode,                igraph_integer_t center);

Arguments: 

graph:

Pointer to an uninitialized graph object, this will be the result.

n:

Integer constant, the number of vertices in the graph.

mode:

Constant, gives the type of the star graph to create. Possible values:

IGRAPH_STAR_OUT

directed star graph, edges pointfrom the center to the other vertices.

IGRAPH_STAR_IN

directed star graph, edges pointto the center from the other vertices.

IGRAPH_STAR_MUTUAL

directed star graph with mutual edges.

IGRAPH_STAR_UNDIRECTED

an undirected star graph is created.

center:

Id of the vertex which will be the center of the graph.

Returns: 

Error code:

IGRAPH_EINVVID

invalid number of vertices.

IGRAPH_EINVAL

invalid center vertex.

IGRAPH_EINVMODE

invalid mode argument.

Time complexity: O(|V|), thenumber of vertices in the graph.

See also: 

Example 9.5.  Fileexamples/simple/igraph_star.c

#include <igraph.h>#include <stdio.h>intmain(void) {    igraph_t graph;/* Create an undirected 6-star, with the 0th node as the centre. */igraph_star(&graph, 7, IGRAPH_STAR_UNDIRECTED, 0);/* Output the edge list of the graph. */igraph_write_graph_edgelist(&graph, stdout);/* Destroy the graph when we are done using it. */igraph_destroy(&graph);return 0;}


1.9. igraph_wheel — Creates awheel graph, a union of a star and a cycle graph.

igraph_error_t igraph_wheel(igraph_t *graph, igraph_integer_t n, igraph_wheel_mode_t mode,                igraph_integer_t center);

A wheel graph onn vertices can be thought of as a wheel withn - 1 spokes. The cycle graph part makes up the rim,while the star graph part adds the spokes.

Note that the two and three-vertex wheel graphs are non-simple:The two-vertex wheel graph contains a self-loop, while the three-vertexwheel graph contains parallel edges (a 1-cycle and a 2-cycle, respectively).

Arguments: 

graph:

Pointer to an uninitialized graph object, this will be the result.

n:

Integer constant, the number of vertices in the graph.

mode:

Constant, gives the type of the star graph to create. Possible values:

IGRAPH_WHEEL_OUT

directed wheel graph, edges pointfrom the center to the other vertices.

IGRAPH_WHEEL_IN

directed wheel graph, edges pointto the center from the other vertices.

IGRAPH_WHEEL_MUTUAL

directed wheel graph with mutual edges.

IGRAPH_WHEEL_UNDIRECTED

an undirected wheel graph is created.

center:

Id of the vertex which will be the center of the graph.

Returns: 

Error code:

IGRAPH_EINVVID

invalid number of vertices.

IGRAPH_EINVAL

invalid center vertex.

IGRAPH_EINVMODE

invalid mode argument.

Time complexity: O(|V|), thenumber of vertices in the graph.

See also: 

1.10. igraph_hypercube — The n-dimensional hypercube graph.

igraph_error_t igraph_hypercube(igraph_t *graph,                                igraph_integer_t n, igraph_bool_t directed);

Warning

This function is experimental and its signature is not considered final yet.We reserve the right to change the function signature without changing themajor version of igraph. Use it at your own risk.

The hypercube graphQ_n has2^n vertices and2^(n-1) n edges. Two vertices are connected when the binaryrepresentations of their zero-based vertex IDs differs in precisely one bit.

Arguments: 

graph:

An uninitialized graph object.

n:

The dimension of the hypercube graph.

directed:

Whether the graph should be directed. Edges will point from lower index vertices towards higher index ones.

Returns: 

Error code.

See also: 

Time complexity: O(2^n)

1.11. igraph_square_lattice — Arbitrary dimensional square lattices.

igraph_error_t igraph_square_lattice(    igraph_t *graph, const igraph_vector_int_t *dimvector, igraph_integer_t nei,    igraph_bool_t directed, igraph_bool_t mutual, const igraph_vector_bool_t *periodic);

Creates d-dimensional square lattices of the given size. Optionally,the lattice can be made periodic, and the neighbors within a givengraph distance can be connected.

In the zero-dimensional case, the singleton graph is returned.

The vertices of the resulting graph are ordered such that theindex of the vertex at position(i_1, i_2, i_3, ..., i_d)in a lattice of size(n_1, n_2, ..., n_d) will bei_1 + n_1 * i_2 + n_1 * n_2 * i_3 + ....

Arguments: 

graph:

An uninitialized graph object.

dimvector:

Vector giving the sizes of the lattice in each of its dimensions. The dimension of the lattice will be the same as the length of this vector.

nei:

Integer value giving the distance (number of steps) within which two vertices will be connected.

directed:

Boolean, whether to create a directed graph. If themutual andcircular arguments are not set to true, edges will be directed from lower-index vertices towards higher-index ones.

mutual:

Boolean, if the graph is directed this gives whether to create all connections as mutual.

periodic:

Boolean vector, defines whether the generated lattice is periodic along each dimension. The length of this vector must match the length ofdimvector. This parameter may also beNULL, which implies that the lattice will not be periodic.

Returns: 

Error code:IGRAPH_EINVAL: invalid (negative) dimension vector or mismatch between the length of the dimension vector and the periodicity vector.

See also: 

igraph_hypercube() to create a hypercube graph;igraph_ring()to create a cycle graph or path graph;igraph_triangular_lattice()andigraph_hexagonal_lattice() to create other types of lattices;igraph_regular_tree() to create a Bethe lattice.

Time complexity: Ifnei is less than two then it is O(|V|+|E|) (asfar as I remember), |V| and |E| are the number of verticesand edges in the generated graph. Otherwise it is O(|V|*d^k+|E|), dis the average degree of the graph, k is thenei argument.

1.12. igraph_triangular_lattice — A triangular lattice with the given shape.

igraph_error_t igraph_triangular_lattice(        igraph_t *graph, const igraph_vector_int_t *dims,        igraph_bool_t directed, igraph_bool_t mutual);

Warning

This function is experimental and its signature is not considered final yet.We reserve the right to change the function signature without changing themajor version of igraph. Use it at your own risk.

Creates a triangular lattice whose vertices have the form (i, j) for non-negativeintegers i and j and (i, j) is generally connected with (i + 1, j), (i, j + 1),and (i - 1, j + 1). The function constructs a planar dual of the graphconstructed byigraph_hexagonal_lattice(). In particular, there a one-to-onecorrespondence between the vertices in the constructed graph and the cycles oflength 6 in the graph constructed byigraph_hexagonal_lattice()with the samedims parameter.

The vertices of the resulting graph are ordered lexicographically with the 2ndcoordinate being more significant, e.g., (i, j) < (i + 1, j) and(i + 1, j) < (i, j + 1)

Arguments: 

graph:

An uninitialized graph object.

dims:

Integer vector, defines the shape of the lattice. Ifdims is of length 1, the resulting lattice has a triangular shape where each side of the triangle containsdims[0] vertices. Ifdims is of length 2, the resulting lattice has a "quasi rectangular" shape with the sides containingdims[0] anddims[1] vertices, respectively. Ifdims is of length 3, the resulting lattice has a hexagonal shape where the sides of the hexagon containdims[0],dims[1] anddims[2] vertices. All dimensions must be non-negative.

directed:

Boolean, whether to create a directed graph. If themutual argument is not set to true, edges will be directed from lower-index vertices towards higher-index ones.

mutual:

Boolean, if the graph is directed this gives whether to create all connections as mutual.

Returns: 

Error code:IGRAPH_EINVAL: The size ofdims must be either 1, 2, or 3 with all the components at least 1.

See also: 

igraph_hexagonal_lattice() andigraph_square_lattice() for creatingother types of lattices;igraph_regular_tree() to create a Bethe lattice.

Time complexity: O(|V|), where |V| is the number of vertices in the generated graph.

1.13. igraph_hexagonal_lattice — A hexagonal lattice with the given shape.

igraph_error_t igraph_hexagonal_lattice(        igraph_t *graph, const igraph_vector_int_t *dims,        igraph_bool_t directed, igraph_bool_t mutual);

Warning

This function is experimental and its signature is not considered final yet.We reserve the right to change the function signature without changing themajor version of igraph. Use it at your own risk.

Creates a hexagonal lattice whose vertices have the form (i, j) for non-negativeintegers i and j and (i, j) is generally connected with (i + 1, j), and if i isodd also with (i - 1, j + 1). The function constructs a planar dual of the graphconstructed byigraph_triangular_lattice(). In particular, there a one-to-onecorrespondence between the cycles of length 6 in the constructed graph and thevertices of the graph constructed byigraph_triangular_lattice() functionwith the samedims parameter.

The vertices of the resulting graph are ordered lexicographically with the 2ndcoordinate being more significant, e.g., (i, j) < (i + 1, j) and(i + 1, j) < (i, j + 1)

Arguments: 

graph:

An uninitialized graph object.

dims:

Integer vector, defines the shape of the lattice. Ifdims is of length 1, the resulting lattice has a triangular shape where each side of the triangle containsdims[0] vertices. Ifdims is of length 2, the resulting lattice has a "quasi rectangular" shape with the sides containingdims[0] anddims[1] vertices, respectively. Ifdims is of length 3, the resulting lattice has a hexagonal shape where the sides of the hexagon containdims[0],dims[1] anddims[2] vertices. All coordinates must be non-negative.

directed:

Boolean, whether to create a directed graph. If themutual argument is not set to true, edges will be directed from lower-index vertices towards higher-index ones.

mutual:

Boolean, if the graph is directed this gives whether to create all connections as mutual.

Returns: 

Error code:IGRAPH_EINVAL: The size ofdims must be either 1, 2, or 3 with all the components at least 1.

See also: 

igraph_triangular_lattice() andigraph_square_lattice() for creatingother types of lattices; ;igraph_regular_tree() to create a Bethe lattice.

Time complexity: O(|V|), where |V| is the number of vertices in the generated graph.

1.14. igraph_ring — Creates acycle graph or apath graph.

igraph_error_t igraph_ring(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed,                igraph_bool_t mutual, igraph_bool_t circular);

A circular ring onn vertices is commonly known in graphtheory as the cycle graph, and often denoted byC_n.Removing a single edge from the cycle graphC_n resultsin the path graphP_n. This function can generate both.

Whenn is 1 or 2, the result may not be a simple graph:the one-cycle contains a self-loop and the undirected or reciprocallyconnected directed two-cycle contains parallel edges.

Arguments: 

graph:

Pointer to an uninitialized graph object.

n:

The number of vertices in the graph.

directed:

Whether to create a directed graph. All edges will be oriented in the same direction along the cycle or path.

mutual:

Whether to create mutual edges in directed graphs. It is ignored for undirected graphs.

circular:

Whether to create a closed ring (a cycle) or an open path.

Returns: 

Error code:IGRAPH_EINVAL: invalid number of vertices.

Time complexity: O(|V|), the number of vertices in the graph.

See also: 

igraph_square_lattice() for generating more general(periodic or non-periodic) lattices.

Example 9.6.  Fileexamples/simple/igraph_ring.c

#include <igraph.h>#include <stdio.h>intmain(void) {    igraph_t graph;/* Create a directed path graph on 10 vertices. */igraph_ring(&graph, 10, IGRAPH_DIRECTED,/* mutual= */ 0,/* circular= */ 0);/* Output the edge list of the graph. */printf("10-path graph:\n");igraph_write_graph_edgelist(&graph, stdout);/* Destroy the graph. */igraph_destroy(&graph);/* Create a 4-cycle graph. */igraph_ring(&graph, 4, IGRAPH_UNDIRECTED,/* mutual= */ 0,/* circular= */ 1);/* Output the edge list of the graph. */printf("\n4-cycle graph:\n");igraph_write_graph_edgelist(&graph, stdout);/* Destroy the graph. */igraph_destroy(&graph);return 0;}


1.15. igraph_path_graph — A path graphP_n.

igraph_error_t igraph_path_graph(        igraph_t *graph, igraph_integer_t n,        igraph_bool_t directed, igraph_bool_t mutual);

Creates the path graphP_n onn vertices.

This is a convenience wrapper toigraph_ring().

Arguments: 

graph:

Pointer to an uninitialized graph object.

n:

The number of vertices in the graph.

directed:

Whether to create a directed graph.

mutual:

Whether to create mutual edges in directed graphs. It is ignored for undirected graphs.

Returns: 

Error code.

Time complexity: O(|V|), the number of vertices in the graph.

1.16. igraph_cycle_graph — A cycle graphC_n.

igraph_error_t igraph_cycle_graph(        igraph_t *graph, igraph_integer_t n,        igraph_bool_t directed, igraph_bool_t mutual);

Creates the cycle graphC_n onn vertices.

Whenn is 1 or 2, the result may not be a simple graph:the one-cycle contains a self-loop and the undirected or reciprocallyconnected directed two-cycle contains parallel edges.

This is a convenience wrapper toigraph_ring().

Arguments: 

graph:

Pointer to an uninitialized graph object.

n:

The number of vertices in the graph.

directed:

Whether to create a directed graph.

mutual:

Whether to create mutual edges in directed graphs. It is ignored for undirected graphs.

Returns: 

Error code.

Time complexity: O(|V|), the number of vertices in the graph.

1.17. igraph_kary_tree — Creates a k-ary tree in which almost all vertices have k children.

igraph_error_t igraph_kary_tree(igraph_t *graph, igraph_integer_t n, igraph_integer_t children,                igraph_tree_mode_t type);

To obtain a completely symmetric tree withl layers, where eachvertex has preciselychildren descendants, usen = (children^(l+1) - 1) / (children - 1).Such trees are often calledk-ary trees, wherek refersto the number of children.

Note that forn=0, the null graph is returned,which is not considered to be a tree byigraph_is_tree().

Arguments: 

graph:

Pointer to an uninitialized graph object.

n:

Integer, the number of vertices in the graph.

children:

Integer, the number of children of a vertex in the tree.

type:

Constant, gives whether to create a directed tree, and if this is the case, also its orientation. Possible values:

IGRAPH_TREE_OUT

directed tree, the edges point from the parents to their children.

IGRAPH_TREE_IN

directed tree, the edges point from the children to their parents.

IGRAPH_TREE_UNDIRECTED

undirected tree.

Returns: 

Error code:IGRAPH_EINVAL: invalid number of vertices.IGRAPH_INVMODE: invalid mode argument.

Time complexity: O(|V|+|E|), thenumber of vertices plus the number of edges in the graph.

See also: 

igraph_regular_tree(),igraph_symmetric_tree() andigraph_star()for creating other regular structures;igraph_from_prufer() andigraph_tree_from_parent_vector() for creating arbitrary trees;igraph_tree_game() for uniform random sampling of trees;igraph_realize_degree_sequence() withIGRAPH_REALIZE_DEGSEQ_SMALLESTto create a tree with given degrees.

Example 9.7.  Fileexamples/simple/igraph_kary_tree.c

#include <igraph.h>intmain(void) {    igraph_t graph;    igraph_bool_t res;/* Create a directed binary tree on 15 nodes,       with edges pointing towards the root. */igraph_kary_tree(&graph, 15, 2, IGRAPH_TREE_IN);igraph_is_tree(&graph, &res, NULL, IGRAPH_IN);printf("Is it an in-tree? %s\n", res ? "Yes" : "No");igraph_is_tree(&graph, &res, NULL, IGRAPH_OUT);printf("Is it an out-tree? %s\n", res ? "Yes" : "No");igraph_destroy(&graph);return 0;}


1.18. igraph_symmetric_tree — Creates a symmetric tree with the specified number of branches at each level.

igraph_error_t igraph_symmetric_tree(igraph_t *graph, const igraph_vector_int_t *branches,                igraph_tree_mode_t type);

This function creates a tree in which all vertices at distanced from theroot havebranching_counts[d] children.

Arguments: 

graph:

Pointer to an uninitialized graph object.

branches:

Vector detailing the number of branches at each level.

type:

Constant, gives whether to create a directed tree, and if this is the case, also its orientation. Possible values:

IGRAPH_TREE_OUT

directed tree, the edges point from the parents to their children.

IGRAPH_TREE_IN

directed tree, the edges point from the children to their parents.

IGRAPH_TREE_UNDIRECTED

undirected tree.

Returns: 

Error code:IGRAPH_INVMODE: invalid mode argument.IGRAPH_EINVAL: invalid number of children.

Time complexity: O(|V|+|E|), thenumber of vertices plus the number of edges in the graph.

See also: 

igraph_kary_tree(),igraph_regular_tree() andigraph_star()for creating other regular tree structures;igraph_from_prufer() for creating arbitrary trees;igraph_tree_game() for uniform random sampling of trees.

Example 9.8.  Fileexamples/simple/igraph_symmetric_tree.c

#include <igraph.h>intmain(void) {    igraph_t graph;    igraph_bool_t res;    igraph_vector_int_t v;igraph_vector_int_init_int(&v, 3, 3, 4, 5);/* Create a directed symmetric tree with 2 levels -       3 children in first and 4 children in second level,       5 children in third level       with edges pointing towards the root. */igraph_symmetric_tree(&graph, &v, IGRAPH_TREE_IN);igraph_is_tree(&graph, &res, NULL, IGRAPH_IN);printf("Is it an in-tree? %s\n", res ? "Yes" : "No");igraph_is_tree(&graph, &res, NULL, IGRAPH_OUT);printf("Is it an out-tree? %s\n", res ? "Yes" : "No");igraph_destroy(&graph);igraph_vector_int_destroy(&v);return 0;}


1.19. igraph_regular_tree — Creates a regular tree.

igraph_error_t igraph_regular_tree(igraph_t *graph, igraph_integer_t h, igraph_integer_t k, igraph_tree_mode_t type);

All vertices of a regular tree, except its leaves, have the same total degreek.This is different from a k-ary tree (igraph_kary_tree()), where allvertices have the same number of children, thus the degre of the root isone less than the degree of the other internal vertices. Regular treesare also referred to as Bethe lattices.

Arguments: 

graph:

Pointer to an uninitialized graph object.

h:

The height of the tree, i.e. the distance between the root and the leaves.

k:

The degree of the regular tree.

type:

Constant, gives whether to create a directed tree, and if this is the case, also its orientation. Possible values:

IGRAPH_TREE_OUT

directed tree, the edges point from the parents to their children.

IGRAPH_TREE_IN

directed tree, the edges point from the children to their parents.

IGRAPH_TREE_UNDIRECTED

undirected tree.

Returns: 

Error code.

Time complexity: O(|V|+|E|), thenumber of vertices plus the number of edges in the graph.

See also: 

igraph_kary_tree() to create k-ary tree where each vertex has the samenumber of children, i.e. out-degree, instead of the same total degree.igraph_symmetric_tree() to use a different number of children at each level.

Example 9.9.  Fileexamples/simple/igraph_regular_tree.c

#include <igraph.h>intmain(void) {    igraph_t tree;igraph_vector_t eccentricity;    igraph_bool_t is_tree;/* Create a Bethe lattice with 5 levels, i.e. height 4. */igraph_regular_tree(&tree, 4, 3, IGRAPH_TREE_UNDIRECTED);/* Bethe lattices are trees. */igraph_is_tree(&tree, &is_tree, NULL, IGRAPH_ALL);printf("Is it a tree? %s\n", is_tree ? "Yes." : "No.");/* Compute and print eccentricities. The root is the most central. */igraph_vector_init(&eccentricity, 0);igraph_eccentricity(&tree, &eccentricity,igraph_vss_all(), IGRAPH_ALL);printf("Vertex eccentricities:\n");igraph_vector_print(&eccentricity);igraph_vector_destroy(&eccentricity);/* Clean up. */igraph_destroy(&tree);return 0;}


1.20. igraph_tree_from_parent_vector — Constructs a tree or forest from a vector encoding the parent of each vertex.

igraph_error_t igraph_tree_from_parent_vector(        igraph_t *graph,        const igraph_vector_int_t *parents,        igraph_tree_mode_t type);

Warning

This function is experimental and its signature is not considered final yet.We reserve the right to change the function signature without changing themajor version of igraph. Use it at your own risk.

Rooted trees and forests are conveniently represented using aparentsvector where the ID of the parent of vertexv is stored inparents[v].This function serves to construct an igraph graph from a parent vector representation.The result is guaranteed to be a forest or a tree. If theparents vectoris found to encode a cycle or a self-loop, an error is raised.

Several igraph functions produce such vectors, such as graph traversalfunctions (igraph_bfs() andigraph_dfs()), shortest path functionsthat construct a shortest path tree, as well as some other specializedfunctions likeigraph_dominator_tree() origraph_cohesive_blocks().Vertices which do not have parents (i.e. roots) get a negative entry in theparents vector.

Useigraph_bfs() origraph_dfs() to convert a forest into a parentvector representation. For trees, i.e. forests with a single root, it ismore convenient to useigraph_bfs_simple().

Arguments: 

graph:

Pointer to an uninitialized graph object.

parents:

The parent vector.parents[v] is the ID of the parent vertex ofv.parents[v] < 0 indicates thatv does not have a parent.

type:

Constant, gives whether to create a directed tree, and if this is the case, also its orientation. Possible values:

IGRAPH_TREE_OUT

directed tree, the edges point from the parents to their children.

IGRAPH_TREE_IN

directed tree, the edges point from the children to their parents.

IGRAPH_TREE_UNDIRECTED undirected tree.

Returns: 

Error code.

See also: 

igraph_bfs(),igraph_bfs_simple() for back-conversion;igraph_from_prufer() for creating trees from Prüfer sequences;igraph_is_tree() andigraph_is_forest() to check if a graphis a tree or forest.

Time complexity: O(n) where n is the length ofparents.

1.21. igraph_full — Creates a full graph (complete graph).

igraph_error_t igraph_full(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed,                igraph_bool_t loops);

In a full graph every possible edge is present: every vertex isconnected to every other vertex.igraph generalizes the usualconcept of complete graphs in graph theory to graphs with self-loopsas well as to directed graphs.

Arguments: 

graph:

Pointer to an uninitialized graph object.

n:

Integer, the number of vertices in the graph.

directed:

Whether to create a directed graph.

loops:

Whether to include self-loops.

Returns: 

Error code:IGRAPH_EINVAL: invalid number of vertices.

Time complexity: O(|V|^2) = O(|E|),where |V| is the number of vertices and |E| is the number of edges.

See also: 

igraph_square_lattice(),igraph_star(),igraph_kary_tree()for creating other regular structures.

Example 9.10.  Fileexamples/simple/igraph_full.c

#include <igraph.h>#include <stdio.h>intmain(void) {    igraph_t graph;    igraph_integer_t n_vertices = 10;/* Create an undirected complete graph. *//* Use IGRAPH_UNDIRECTED and IGRAPH_NO_LOOPS instead of 1/TRUE and 0/FALSE for better readability. */igraph_full(&graph, n_vertices, IGRAPH_UNDIRECTED, IGRAPH_NO_LOOPS);printf("The undirected complete graph on %" IGRAPH_PRId " vertices has %" IGRAPH_PRId " edges.\n",igraph_vcount(&graph),igraph_ecount(&graph));/* Remember to destroy the object at the end. */igraph_destroy(&graph);/* Create a directed complete graph. */igraph_full(&graph, n_vertices, IGRAPH_DIRECTED, IGRAPH_NO_LOOPS);printf("The directed complete graph on %" IGRAPH_PRId " vertices has %" IGRAPH_PRId " edges.\n",igraph_vcount(&graph),igraph_ecount(&graph));igraph_destroy(&graph);/* Create an undirected complete graph with self-loops. */igraph_full(&graph, n_vertices, IGRAPH_UNDIRECTED, IGRAPH_LOOPS);printf("The undirected complete graph on %" IGRAPH_PRId " vertices with self-loops has %" IGRAPH_PRId " edges.\n",igraph_vcount(&graph),igraph_ecount(&graph));igraph_destroy(&graph);/* Create a directed graph with self-loops. */igraph_full(&graph, n_vertices, IGRAPH_DIRECTED, IGRAPH_LOOPS);printf("The directed complete graph on %" IGRAPH_PRId " vertices with self-loops has %" IGRAPH_PRId " edges.\n",igraph_vcount(&graph),igraph_ecount(&graph));igraph_destroy(&graph);return 0;}


1.22. igraph_full_citation — Creates a full citation graph (a complete directed acyclic graph).

igraph_error_t igraph_full_citation(igraph_t *graph, igraph_integer_t n,                         igraph_bool_t directed);

This is a directed graph, where everyi->j edge ispresent if and only ifj<i.If thedirected argument is false then an undirected graph iscreated, and it is just a complete graph.

Arguments: 

graph:

Pointer to an uninitialized graph object, the result is stored here.

n:

The number of vertices.

directed:

Whether to created a directed graph. If false an undirected graph is created.

Returns: 

Error code.

See also: 

Time complexity: O(|V|^2) = O(|E|),where |V| is the number of vertices and |E| is the number of edges.

1.23. igraph_full_multipartite — Creates a full multipartite graph.

igraph_error_t igraph_full_multipartite(igraph_t *graph,                          igraph_vector_int_t *types,                          const igraph_vector_int_t *n,                          igraph_bool_t directed,                          igraph_neimode_t mode);

A multipartite graph contains two or more types of vertices and connectionsare only possible between two vertices of different types. This functioncreates a complete multipartite graph.

Arguments: 

graph:

Pointer to an uninitialized graph object, the graph will be created here.

types:

Pointer to an integer vector. If not a null pointer, the type of each vertex will be stored here.

n:

Pointer to an integer vector, the number of vertices of each type.

directed:

Boolean, whether to create a directed graph.

mode:

A constant that gives the type of connections for directed graphs. IfIGRAPH_OUT, then edges point from vertices of low-index vertices to high-index vertices; ifIGRAPH_IN, then the opposite direction is realized;IGRAPH_ALL, then mutual edges will be created.

Returns: 

Error code.

Time complexity: O(|V|+|E|), linear in the number of vertices andedges.

See also: 

igraph_full_bipartite() for complete bipartite graphs,igraph_turan() for Turán graphs.

1.24. igraph_turan — Creates a Turán graph.

igraph_error_t igraph_turan(igraph_t *graph,                            igraph_vector_int_t *types,                            igraph_integer_t n,                            igraph_integer_t r);

Turán graphs are complete multipartite graphs with the propertythat the sizes of the partitions are as close to equal as possible.

The Turán graph withn vertices andr partitions is the densestgraph onn vertices that does not contain a clique of sizer+1.

This function generates undirected graphs. The null graph isreturned when the number of vertices is zero. A complete graph isreturned if the number of partitions is greater than the number ofvertices.

Arguments: 

graph:

Pointer to an igraph_t object, the graph will be created here.

types:

Pointer to an integer vector. If not a null pointer, the type (partition index) of each vertex will be stored here.

n:

Integer, the number of vertices in the graph.

r:

Integer, the number of partitions of the graph, must be positive.

Returns: 

Error code.

Time complexity: O(|V|+|E|), linear in the number of vertices andedges.

See also: 

igraph_full_multipartite() for full multipartite graphs.

1.25. igraph_realize_degree_sequence — Generates a graph with the given degree sequence.

igraph_error_t igraph_realize_degree_sequence(        igraph_t *graph,        const igraph_vector_int_t *outdeg, const igraph_vector_int_t *indeg,        igraph_edge_type_sw_t allowed_edge_types,        igraph_realize_degseq_t method);

This function generates an undirected graph that realizes a given degreesequence, or a directed graph that realizes a given pair of out- andin-degree sequences.

Simple undirected graphs are constructed using the Havel-Hakimi algorithm(undirected case), or the analogous Kleitman-Wang algorithm (directed case).These algorithms work by choosing an arbitrary vertex and connecting all itsstubs to other vertices of highest degree. In the directed case, the"highest" (in, out) degree pairs are determined based on lexicographicordering. This step is repeated until all degrees have been connected up.

Loopless multigraphs are generated using an analogous algorithm: an arbitraryvertex is chosen, and it is connected with a single connection to a highestremaining degee vertex. If self-loops are also allowed, the same algorithmis used, but if a non-zero vertex remains at the end of the procedure, thegraph is completed by adding self-loops to it. Thus, the result will containat most one vertex with self-loops.

Themethod parameter controls the order in which the vertices to beconnected are chosen. In the undirected case,IGRAPH_REALIZE_DEGSEQ_SMALLESTproduces a connected graph when one exists. This makes this method suitablefor constructing trees with a given degree sequence.

For a undirected simple graph, the time complexity is O(V + alpha(V) * E).For an undirected multi graph, the time complexity is O(V * E + V log V).For a directed graph, the time complexity is O(E + V^2 log V).

References:

V. Havel:Poznámka o existenci konečných grafů (A remark on the existence of finite graphs),Časopis pro pěstování matematiky 80, 477-480 (1955).http://eudml.org/doc/19050

S. L. Hakimi:On Realizability of a Set of Integers as Degrees of the Vertices of a Linear Graph,Journal of the SIAM 10, 3 (1962).https://www.jstor.org/stable/2098770

D. J. Kleitman and D. L. Wang:Algorithms for Constructing Graphs and Digraphs with Given Valences and Factors,Discrete Mathematics 6, 1 (1973).https://doi.org/10.1016/0012-365X%2873%2990037-XP. L. Erdős, I. Miklós, Z. Toroczkai:A simple Havel-Hakimi type algorithm to realize graphical degree sequences of directed graphs,The Electronic Journal of Combinatorics 17.1 (2010).http://eudml.org/doc/227072

Sz. Horvát and C. D. Modes:Connectedness matters: construction and exact random sampling of connected networks (2021).https://doi.org/10.1088/2632-072X/abced5

Arguments: 

graph:

Pointer to an uninitialized graph object.

outdeg:

The degree sequence of an undirected graph (ifindeg is NULL), or the out-degree sequence of a directed graph (ifindeg is given).

indeg:

The in-degree sequence of a directed graph. PassNULL to generate an undirected graph.

allowed_edge_types:

The types of edges to allow in the graph. For directed graphs, onlyIGRAPH_SIMPLE_SW is implemented at this moment. For undirected graphs, the following values are valid:

IGRAPH_SIMPLE_SW

simple graphs (i.e. no self-loops or multi-edges allowed).

IGRAPH_LOOPS_SW

single self-loops are allowed, but not multi-edges; currently not implemented.

IGRAPH_MULTI_SW

multi-edges are allowed, but not self-loops.

IGRAPH_LOOPS_SW | IGRAPH_MULTI_SW

both self-loops and multi-edges are allowed.

method:

The method to generate the graph. Possible values:

IGRAPH_REALIZE_DEGSEQ_SMALLEST

The vertex with smallest remaining degree is selected first. The result is usually a graph with high negative degree assortativity. In the undirected case, this method is guaranteed to generate a connected graph, regardless of whether multi-edges are allowed, provided that a connected realization exists (see Horvát and Modes, 2021, as well ashttp://szhorvat.net/pelican/hh-connected-graphs.html). This method can be used to construct a tree from its degrees. In the directed case it tends to generate weakly connected graphs, but this is not guaranteed.

IGRAPH_REALIZE_DEGSEQ_LARGEST

The vertex with the largest remaining degree is selected first. The result is usually a graph with high positive degree assortativity, and is often disconnected.

IGRAPH_REALIZE_DEGSEQ_INDEX

The vertices are selected in order of their index (i.e. their position in the degree vector). Note that sorting the degree vector and using theINDEX method is not equivalent to theSMALLEST method above, asSMALLEST uses the smallestremaining degree for selecting vertices, not the smallestinitial degree.

Returns: 

Error code:

IGRAPH_UNIMPLEMENTED

The requested method is not implemented.

IGRAPH_ENOMEM

There is not enough memory to perform the operation.

IGRAPH_EINVAL

Invalid method parameter, or invalid in- and/or out-degree vectors. The degree vectors should be non-negative, the length and sum ofoutdeg andindeg should match for directed graphs.

See also: 

igraph_is_graphical() to test graphicality without generating a graph;igraph_realize_bipartite_degree_sequence() to create bipartite graphs from two degree sequence;igraph_degree_sequence_game() to generate random graphs with a given degree sequence;igraph_k_regular_game() to generate random regular graphs;igraph_rewire() to randomly rewire the edges of a graph while preserving its degree sequence.

Example 9.11.  Fileexamples/simple/igraph_realize_degree_sequence.c

#include <igraph.h>#include <stdio.h>intmain(void){    igraph_t g1, g2, g3;    igraph_integer_t nodes = 500, A = 0, power = 1, m = 1;    igraph_real_t assortativity;igraph_rng_seed(igraph_rng_default(), 42);printf("Demonstration of difference in assortativities of graphs with the same degree sequence but different linkages:\n\nInitial graph based on the Barabasi-Albert model with %" IGRAPH_PRId " nodes.\n", nodes);/* Graph 1 generated by a randomized graph generator */igraph_barabasi_game(&g1, nodes, power, m, NULL,/* outpref */ 0, A, IGRAPH_UNDIRECTED, IGRAPH_BARABASI_PSUMTREE,/* start from */ NULL);    igraph_vector_int_t degree;igraph_vector_int_init(&degree, nodes);igraph_degree(&g1, &degree,igraph_vss_all(), IGRAPH_ALL, IGRAPH_NO_LOOPS);/* Measuring assortativity of the first graph */igraph_assortativity_degree(&g1, &assortativity, IGRAPH_UNDIRECTED);printf("Assortativity of initial graph = %g\n\n", assortativity);igraph_destroy(&g1);/* Graph 2 (with the same degree sequence) generated by selecting vertices with the smallest degree first */igraph_realize_degree_sequence(&g2, &degree, NULL, IGRAPH_SIMPLE_SW, IGRAPH_REALIZE_DEGSEQ_SMALLEST);igraph_assortativity_degree(&g2, &assortativity, IGRAPH_UNDIRECTED);printf("Assortativity after choosing vertices with the smallest degrees first = %g\n\n", assortativity);igraph_destroy(&g2);/* Graph 3 (with the same degree sequence) generated by selecting vertices with the largest degree first */igraph_realize_degree_sequence(&g3, &degree, NULL, IGRAPH_SIMPLE_SW, IGRAPH_REALIZE_DEGSEQ_LARGEST);igraph_assortativity_degree(&g3, &assortativity, IGRAPH_UNDIRECTED);printf("Assortativity after choosing vertices with the largest degrees first = %g\n", assortativity);igraph_destroy(&g3);igraph_vector_int_destroy(&degree);return 0;}


1.26. igraph_realize_bipartite_degree_sequence — Generates a bipartite graph with the given bidegree sequence.

igraph_error_t igraph_realize_bipartite_degree_sequence(    igraph_t *graph,    const igraph_vector_int_t *degrees1, const igraph_vector_int_t *degrees2,    const igraph_edge_type_sw_t allowed_edge_types, const igraph_realize_degseq_t method);

Warning

This function is experimental and its signature is not considered final yet.We reserve the right to change the function signature without changing themajor version of igraph. Use it at your own risk.

This function generates a bipartite graph with the given bidegree sequence,using a Havel-Hakimi-like construction algorithm. The order in which verticesare connected up is controlled by themethod parameter. When using theIGRAPH_REALIZE_DEGSEQ_SMALLEST method, it is ensured that the graph will beconnected if and only if the given bidegree sequence is potentially connected.

The vertices of the graph will be ordered so that those havingdegrees1come first, followed bydegrees2.

Arguments: 

graph:

Pointer to an uninitialized graph object.

degrees1:

The degree sequence of the first partition.

degrees2:

The degree sequence of the second partition.

allowed_edge_types:

The types of edges to allow in the graph.

IGRAPH_SIMPLE_SW

simple graph (i.e. no multi-edges allowed).

IGRAPH_MULTI_SW

multi-edges are allowed

method:

Controls the order in which vertices are selected for connection. Possible values:

IGRAPH_REALIZE_DEGSEQ_SMALLEST

The vertex with smallest remaining degree is selected first, from either partition. The result is usually a graph with high negative degree assortativity. This method is guaranteed to generate a connected graph, if one exists.

IGRAPH_REALIZE_DEGSEQ_LARGEST

The vertex with the largest remaining degree is selected first, from either parition. The result is usually a graph with high positive degree assortativity, and is often disconnected.

IGRAPH_REALIZE_DEGSEQ_INDEX

The vertices are selected in order of their index.

Returns: 

Error code.

See also: 

igraph_is_bigraphical() to test bigraphicality without generating a graph.

1.27. igraph_famous — Create a famous graph by simply providing its name.

igraph_error_t igraph_famous(igraph_t *graph, const char *name);

The name of the graph can be simply supplied as a string.Note that this function creates graphs which don't take any parameters,there are separate functions for graphs with parameters, e.g.igraph_full() for creating a full graph.

The following graphs are supported:

Bull

The bull graph, 5 vertices, 5 edges, resembles the head of a bull if drawn properly.

Chvatal

This is the smallest triangle-free graph that is both 4-chromatic and 4-regular. According to the Grunbaum conjecture there exists an m-regular, m-chromatic graph with n vertices for every m>1 and n>2. The Chvatal graph is an example for m=4 and n=12. It has 24 edges.

Coxeter

A non-Hamiltonian cubic symmetric graph with 28 vertices and 42 edges.

Cubical

The Platonic graph of the cube. A convex regular polyhedron with 8 vertices and 12 edges.

Diamond

A graph with 4 vertices and 5 edges, resembles a schematic diamond if drawn properly.

Dodecahedral, Dodecahedron

Another Platonic solid with 20 vertices and 30 edges.

Folkman

The semisymmetric graph with minimum number of vertices, 20 and 40 edges. A semisymmetric graph is regular, edge transitive and not vertex transitive.

Franklin

This is a graph whose embedding to the Klein bottle can be colored with six colors, it is a counterexample to the necessity of the Heawood conjecture on a Klein bottle. It has 12 vertices and 18 edges.

Frucht

The Frucht Graph is the smallest cubical graph whose automorphism group consists only of the identity element. It has 12 vertices and 18 edges.

Grotzsch, Groetzsch

The Grötzsch graph is a triangle-free graph with 11 vertices, 20 edges, and chromatic number 4. It is named after German mathematician Herbert Grötzsch, and its existence demonstrates that the assumption of planarity is necessary in Grötzsch's theorem that every triangle-free planar graph is 3-colorable.

Heawood

The Heawood graph is an undirected graph with 14 vertices and 21 edges. The graph is cubic, and all cycles in the graph have six or more edges. Every smaller cubic graph has shorter cycles, so this graph is the 6-cage, the smallest cubic graph of girth 6.

Herschel

The Herschel graph is the smallest nonhamiltonian polyhedral graph. It is the unique such graph on 11 nodes, and has 18 edges.

House

The house graph is a 5-vertex, 6-edge graph, the schematic draw of a house if drawn properly, basically a triangle on top of a square.

HouseX

The same as the house graph with an X in the square. 5 vertices and 8 edges.

Icosahedral, Icosahedron

A Platonic solid with 12 vertices and 30 edges.

Krackhardt_Kite

A social network with 10 vertices and 18 edges. Krackhardt, D. Assessing the Political Landscape: Structure, Cognition, and Power in Organizations. Admin. Sci. Quart. 35, 342-369, 1990.

Levi

The graph is a 4-arc transitive cubic graph, it has 30 vertices and 45 edges.

McGee

The McGee graph is the unique 3-regular 7-cage graph, it has 24 vertices and 36 edges.

Meredith

The Meredith graph is a quartic graph on 70 nodes and 140 edges that is a counterexample to the conjecture that every 4-regular 4-connected graph is Hamiltonian.

Noperfectmatching

A connected graph with 16 vertices and 27 edges containing no perfect matching. A matching in a graph is a set of pairwise non-incident edges; that is, no two edges share a common vertex. A perfect matching is a matching which covers all vertices of the graph.

Nonline

A graph whose connected components are the 9 graphs whose presence as a vertex-induced subgraph in a graph makes a nonline graph. It has 50 vertices and 72 edges.

Octahedral, Octahedron

Platonic solid with 6 vertices and 12 edges.

Petersen

A 3-regular graph with 10 vertices and 15 edges. It is the smallest hypohamiltonian graph, i.e. it is non-hamiltonian but removing any single vertex from it makes it Hamiltonian.

Robertson

The unique (4,5)-cage graph, i.e. a 4-regular graph of girth 5. It has 19 vertices and 38 edges.

Smallestcyclicgroup

A smallest nontrivial graph whose automorphism group is cyclic. It has 9 vertices and 15 edges.

Tetrahedral, Tetrahedron

Platonic solid with 4 vertices and 6 edges.

Thomassen

The smallest hypotraceable graph, on 34 vertices and 52 edges. A hypotracable graph does not contain a Hamiltonian path but after removing any single vertex from it the remainder always contains a Hamiltonian path. A graph containing a Hamiltonian path is called traceable.

Tutte

Tait's Hamiltonian graph conjecture states that every 3-connected 3-regular planar graph is Hamiltonian. This graph is a counterexample. It has 46 vertices and 69 edges.

Uniquely3colorable

Returns a 12-vertex, triangle-free graph with chromatic number 3 that is uniquely 3-colorable.

Walther

An identity graph with 25 vertices and 31 edges. An identity graph has a single graph automorphism, the trivial one.

Zachary

Social network of friendships between 34 members of a karate club at a US university in the 1970s. See W. W. Zachary, An information flow model for conflict and fission in small groups, Journal of Anthropological Research 33, 452-473 (1977).

Arguments: 

graph:

Pointer to an uninitialized graph object.

name:

Character constant, the name of the graph to be created, it is case insensitive.

Returns: 

Error code,IGRAPH_EINVAL if there is no graph with the given name.

See also: 

Other functions for creating graph structures:igraph_ring(),igraph_kary_tree(),igraph_square_lattice(),igraph_full().

Time complexity: O(|V|+|E|), the number of vertices plus the numberof edges in the graph.

1.28. igraph_lcf — Creates a graph from LCF notation.

igraph_error_t igraph_lcf(igraph_t *graph, igraph_integer_t n, ...);

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

Arguments: 

graph:

Pointer to an uninitialized graph object.

n:

Integer, the number of vertices in the graph.

...:

The shifts and the number of repeats for the shifts, plus an additional 0 to mark the end of the arguments.

Returns: 

Error code.

See also: 

Seeigraph_lcf_vector() for a similar function using anigraph_vector_t instead of the variable length argument list;igraph_circulant() to create circulant graphs.

Time complexity: O(|V|+|E|), the number of vertices plus the numberof edges.

Example 9.12.  Fileexamples/simple/igraph_lcf.c

#include <igraph.h>intmain(void) {    igraph_t g, g2;    igraph_bool_t iso;// Franklin graphigraph_lcf(&g, 12, 5, -5, 6, 0);igraph_famous(&g2, "franklin");igraph_isomorphic_vf2(&g, &g2,/*vertex.color1=*/ 0,/*vertex.color2=*/ 0,/*edge.color1=*/ 0,/*edge.color2=*/ 0,                          &iso, 0, 0, 0, 0, 0);if (!iso) {printf("Failure: Franklin\n");return 1;    }igraph_destroy(&g);igraph_destroy(&g2);// [3, -2]^4, n=8igraph_lcf(&g, 8, 3, -2, 4, 0);if (igraph_ecount(&g) != 16) {printf("Failure: [3, -2]^4, n=8\n");return 1;    }igraph_destroy(&g);// [2, -2]^2, n=2igraph_lcf(&g, 2, 2, -2, 2, 0);if (igraph_ecount(&g) != 1) {printf("Failure: [2, -2]^2, n=2\n");return 1;    }igraph_destroy(&g);// [2]^2, n=2igraph_lcf(&g, 2, 2, 2, 0);if (igraph_ecount(&g) != 1) {printf("Failure: [2]^2, n=2\n");return 1;    }igraph_destroy(&g);// Regression test for bug #996igraph_lcf(&g, 0, 0);if (igraph_vcount(&g) != 0 ||igraph_ecount(&g) != 0) {printf("Failure: regression test for #996\n");return 1;    }igraph_destroy(&g);return 0;}


1.29. igraph_lcf_vector — Creates a graph from LCF notation.

igraph_error_t igraph_lcf_vector(igraph_t *graph, igraph_integer_t n,                      const igraph_vector_int_t *shifts,                      igraph_integer_t repeats);

This function is essentially the same asigraph_lcf(), onlythe way for giving the arguments is different. Seeigraph_lcf() for details.

Arguments: 

graph:

Pointer to an uninitialized graph object.

n:

Integer constant giving the number of vertices.

shifts:

A vector giving the shifts.

repeats:

An integer constant giving the number of repeats for the shifts.

Returns: 

Error code.

See also: 

Time complexity: O(|V|+|E|), linear in the number of vertices plusthe number of edges.

1.30. igraph_mycielski_graph — The Mycielski graph of orderk.

igraph_error_t igraph_mycielski_graph(igraph_t *graph, igraph_integer_t k);

The Mycielski graph of orderk, denotedM_k, is a triangle-free graph onk vertices with chromatic numberk. It is defined through the Mycielskiconstruction described in the documentation ofigraph_mycielskian().

Some authors define Mycielski graphs only fork > 1.igraph extends this to allk >= 0.The first few Mycielski graphs are:

  1. M_0: Null graph

  2. M_1: Single vertex

  3. M_2: Path graph with 2 vertices

  4. M_3: Cycle graph with 5 vertices

  5. M_4: Grötzsch graph (a triangle-free graph with chromatic number 4)

The vertex count ofM_k isn_k = 3 * 2^(k-2) - 1 fork > 1 andk otherwise.The edge count ism_k = (7 * 3^(k-2) + 1) / 2 - 3 * 2^(k - 2) fork > 1and 0 otherwise.

Arguments: 

graph:

Pointer to an uninitialized graph object. The generated Mycielski graph will be stored here.

k:

Integer, the order of the Mycielski graph (must be non-negative).

Returns: 

Error code.

See also: 

Time complexity: O(3^k), i.e. exponential ink.

1.31. igraph_from_prufer — Generates a tree from a Prüfer sequence.

igraph_error_t igraph_from_prufer(igraph_t *graph, const igraph_vector_int_t *prufer);

A Prüfer sequence is a unique sequence of integers associatedwith a labelled tree. A tree onn vertices can be representedby a sequence ofn-2 integers, each between0 andn-1 (inclusive).The algorithm used by this function is based onPaulius Micikevičius, Saverio Caminiti, Narsingh Deo:Linear-time Algorithms for Encoding Trees as Sequences of Node Labels

Arguments: 

graph:

Pointer to an uninitialized graph object.

prufer:

The Prüfer sequence

Returns: 

Error code:

IGRAPH_ENOMEM

there is not enough memory to perform the operation.

IGRAPH_EINVAL

invalid Prüfer sequence given

See also: 

Time complexity: O(|V|), where |V| is the number of vertices in the tree.

1.32. igraph_atlas — Create a small graph from theGraph Atlas.

igraph_error_t igraph_atlas(igraph_t *graph, igraph_integer_t number);

The graph atlas contains all simple undirected unlabeled graphs on between0 and 7 vertices. The number of the graph is given as a parameter.The graphs are listed:

  1. in increasing order of number of vertices;

  2. for a fixed number of vertices, in increasing order of the number of edges;

  3. for fixed numbers of vertices and edges, in lexicographically increasing order of the degree sequence, for example 111223 < 112222;

  4. for fixed degree sequence, in increasing number of automorphisms.

The data was converted from the NetworkX software package,seehttps://networkx.org/.

See An Atlas of Graphs by Ronald C. Read and Robin J. Wilson,Oxford University Press, 1998.

Arguments: 

graph:

Pointer to an uninitialized graph object.

number:

The number of the graph to generate. Must be between 0 and 1252 (inclusive). Graphs on 0-7 vertices start at numbers 0, 1, 2, 4, 8, 19, 53, and 209, respectively.

Returns: 

Error code.

Added in version 0.2.

Time complexity: O(|V|+|E|), the number of vertices plus the number ofedges.

Example 9.13.  Fileexamples/simple/igraph_atlas.c

#include <igraph.h>intmain(void) {    igraph_t g;igraph_atlas(&g, 45);igraph_write_graph_edgelist(&g, stdout);printf("\n");igraph_destroy(&g);igraph_atlas(&g, 0);igraph_write_graph_edgelist(&g, stdout);printf("\n");igraph_destroy(&g);igraph_atlas(&g, 1252);igraph_write_graph_edgelist(&g, stdout);printf("\n");igraph_destroy(&g);return 0;}


1.33. igraph_de_bruijn — Generate a de Bruijn graph.

igraph_error_t igraph_de_bruijn(igraph_t *graph, igraph_integer_t m, igraph_integer_t n);

A de Bruijn graph represents relationships between strings. An alphabetofm letters are used and strings of lengthn are considered.A vertex corresponds to every possible string and there is a directed edgefrom vertexv to vertexw if the string ofv can be transformed intothe string ofw by removing its first letter and appending a letter to it.

Please note that the graph will havem to the powern vertices andeven more edges, so probably you don't want to supply too big numbers form andn.

De Bruijn graphs have some interesting properties, please see another source,e.g. Wikipedia for details.

Arguments: 

graph:

Pointer to an uninitialized graph object, the result will be stored here.

m:

Integer, the number of letters in the alphabet.

n:

Integer, the length of the strings.

Returns: 

Error code.

See also: 

Time complexity: O(|V|+|E|), the number of vertices plus the number of edges.

1.34. igraph_kautz — Generate a Kautz graph.

igraph_error_t igraph_kautz(igraph_t *graph, igraph_integer_t m, igraph_integer_t n);

A Kautz graph is a labeled graph, vertices are labeled by stringsof lengthn+1 above an alphabet withm+1 letters, withthe restriction that every two consecutive letters in the stringmust be different. There is a directed edge from a vertexv toanother vertexw if it is possible to transform the string ofv into the string ofw by removing the first letter andappending a letter to it. For string length 1 the new lettercannot equal the old letter, so there are no loops.

Kautz graphs have some interesting properties, see e.g. Wikipediafor details.

Vincent Matossian wrote the first version of this function in R,thanks.

Arguments: 

graph:

Pointer to an uninitialized graph object, the resultwill be stored here.

m:

Integer,m+1 is the number of letters in the alphabet.

n:

Integer,n+1 is the length of the strings.

Returns: 

Error code.

See also: 

Time complexity: O(|V|* [(m+1)/m]^n +|E|), in practice it is morelike O(|V|+|E|). |V| is the number of vertices, |E| is the numberof edges andm andn are the corresponding arguments.

1.35. igraph_circulant — Creates a circulant graph.

igraph_error_t igraph_circulant(igraph_t *graph, igraph_integer_t n, const igraph_vector_int_t *shifts, igraph_bool_t directed);

A circulant graphG(n, shifts) consists ofn verticesv_0, ...,v_(n-1) such that for eachs_i in the list of offsetsshifts,v_j isconnected tov_((j + s_i) mod n) for all j.

The function can generate either directed or undirected graphs. It does not generatemulti-edges or self-loops.

Arguments: 

graph:

Pointer to an uninitialized graph object, the result will be stored here.

n:

Integer, the number of vertices in the circulant graph.

shifts:

Integer vector, a list of the offsets within the circulant graph.

directed:

Boolean, whether to create a directed graph.

Returns: 

Error code.

See also: 

Time complexity: O(|V| |shifts|), the number of vertices in the graph times the numberof shifts.

1.36. igraph_generalized_petersen — Creates a Generalized Petersen graph.

igraph_error_t igraph_generalized_petersen(igraph_t *graph, igraph_integer_t n, igraph_integer_t k);

The generalized Petersen graphG(n, k) consists ofn verticesv_0, ...,v_n forming an "outer" cycle graph, andn additional verticesu_0, ...,u_n forming an "inner" circulant graph whereu_iis connected tou_(i + k mod n). Additionally, allv_i areconnected tou_i.

G(n, k) has2n vertices and3n edges. The Petersen graphitself isG(5, 2).

Reference:

M. E. Watkins,A Theorem on Tait Colorings with an Application to the Generalized Petersen Graphs,Journal of Combinatorial Theory 6, 152-164 (1969).https://doi.org/10.1016%2FS0021-9800%2869%2980116-X

Arguments: 

graph:

Pointer to an uninitialized graph object, the result willbe stored here.

n:

Integer,n is the number of vertices in the inner and outercycle/circulant graphs. It must be at least 3.

k:

Integer,k is the shift of the circulant graph. It must bepositive and less thann/2.

Returns: 

Error code.

See also: 

igraph_famous() for the original Petersen graph.

Time complexity: O(|V|), the number of vertices in the graph.

1.37. igraph_extended_chordal_ring — Create an extended chordal ring.

igraph_error_t igraph_extended_chordal_ring(    igraph_t *graph, igraph_integer_t nodes, const igraph_matrix_int_t *W,    igraph_bool_t directed);

An extended chordal ring is a cycle graph with additional chordsconnecting its vertices.Each rowL of the matrixW specifies a set of chords to beinserted, in the following way: vertexi will connect to a vertexL[(i mod p)] steps ahead of it along the cycle, wherep is the length ofL.In other words, vertexi will be connected to vertex(i + L[(i mod p)]) mod nodes. If multiple edges aredefined in this way, this will output a non-simple graph. The resultcan be simplified usingigraph_simplify().

See also Kotsis, G: Interconnection Topologies for Parallel ProcessingSystems, PARS Mitteilungen 11, 1-6, 1993. The igraph extended chordalrings are not identical to the ones in the paper. In igraphthe matrix specifies which edges to add. In the paper, a condition isspecified which should simultaneously hold between two endpoints andthe reverse endpoints.

Arguments: 

graph:

Pointer to an uninitialized graph object, the result will be stored here.

nodes:

Integer constant, the number of vertices in the graph. It must be at least 3.

W:

The matrix specifying the extra edges. The number of columns should divide the number of total vertices. The elements are allowed to be negative.

directed:

Whether the graph should be directed.

Returns: 

Error code.

See also: 

Time complexity: O(|V|+|E|), the number of vertices plus the numberof edges.

2. Games: Randomized graph generators

2.1.igraph_grg_game — Generates a geometric random graph.
2.2.igraph_barabasi_game — Generates a graph based on the Barabási-Albert model.
2.3.igraph_erdos_renyi_game_gnm — Generates a random (Erdős-Rényi) graph with a fixed number of edges.
2.4.igraph_erdos_renyi_game_gnp — Generates a random (Erdős-Rényi) graph with fixed edge probabilities.
2.5.igraph_watts_strogatz_game — The Watts-Strogatz small-world model.
2.6.igraph_rewire_edges — Rewires the edges of a graph with constant probability.
2.7.igraph_rewire_directed_edges — Rewires the chosen endpoint of directed edges.
2.8.igraph_degree_sequence_game — Generates a random graph with a given degree sequence.
2.9.igraph_k_regular_game — Generates a random graph where each vertex has the same degree.
2.10.igraph_static_fitness_game — Non-growing random graph with edge probabilities proportional to node fitness scores.
2.11.igraph_static_power_law_game — Generates a non-growing random graph with expected power-law degree distributions.
2.12.igraph_chung_lu_game — Samples graphs from the Chung-Lu model.
2.13.igraph_forest_fire_game — Generates a network according to theforest fire game.
2.14.igraph_rewire — Randomly rewires a graph while preserving its degree sequence.
2.15.igraph_growing_random_game — Generates a growing random graph.
2.16.igraph_callaway_traits_game — Simulates a growing network with vertex types.
2.17.igraph_establishment_game — Generates a graph with a simple growing model with vertex types.
2.18.igraph_preference_game — Generates a graph with vertex types and connection preferences.
2.19.igraph_asymmetric_preference_game — Generates a graph with asymmetric vertex types and connection preferences.
2.20.igraph_recent_degree_game — Stochastic graph generator based on the number of incident edges a node has gained recently.
2.21.igraph_barabasi_aging_game — Preferential attachment with aging of vertices.
2.22.igraph_recent_degree_aging_game — Preferential attachment based on the number of edges gained recently, with aging of vertices.
2.23.igraph_lastcit_game — Simulates a citation network, based on time passed since the last citation.
2.24.igraph_cited_type_game — Simulates a citation based on vertex types.
2.25.igraph_citing_cited_type_game — Simulates a citation network based on vertex types.
2.26.igraph_sbm_game — Sample from a stochastic block model.
2.27.igraph_hsbm_game — Hierarchical stochastic block model.
2.28.igraph_hsbm_list_game — Hierarchical stochastic block model, more general version.
2.29.igraph_dot_product_game — Generates a random dot product graph.
2.30.igraph_tree_game — Generates a random tree with the given number of nodes.
2.31.igraph_correlated_game — Generates a random graph correlated to an existing graph.
2.32.igraph_correlated_pair_game — Generates pairs of correlated random graphs.
2.33.igraph_simple_interconnected_islands_game — Generates a random graph made of several interconnected islands, each island being a random graph.

Games are random graph generators, i.e. they generate a differentgraph every time they are called. igraph includes many such generators.Some implement stochastic graph construction processes inspired by real-worldmechanics, such as preferential attachment, while others are designed toproduce graphs with certain used properties (e.g. fixed number of edges,fixed degrees, etc.)

2.1. igraph_grg_game — Generates a geometric random graph.

igraph_error_t igraph_grg_game(igraph_t *graph, igraph_integer_t nodes,                    igraph_real_t radius, igraph_bool_t torus,                    igraph_vector_t *x, igraph_vector_t *y);

A geometric random graph is created by dropping points (i.e. vertices)randomly on the unit square and then connecting all those pairswhich are strictly less thanradius apart in Euclidean distance.

Original code contributed by Keith Briggs, thanks Keith.

Arguments: 

graph:

Pointer to an uninitialized graph object.

nodes:

The number of vertices in the graph.

radius:

The radius within which the vertices will be connected.

torus:

Boolean constant. If true, periodic boundary conditions will be used, i.e. the vertices are assumed to be on a torus instead of a square.

x:

An initialized vector orNULL. If notNULL, the points' x coordinates will be returned here.

y:

An initialized vector orNULL. If notNULL, the points' y coordinates will be returned here.

Returns: 

Error code.

Time complexity: TODO, less than O(|V|^2+|E|).

Example 9.14.  Fileexamples/simple/igraph_grg_game.c

#include <igraph.h>#include <math.h>intmain(void) {    igraph_t graph;igraph_vector_t x, y;igraph_vector_t weights;    igraph_eit_t eit;    igraph_real_t avg_dist;/* Set random seed for reproducible results */igraph_rng_seed(igraph_rng_default(), 42);/* Create a random geometric graph and retrieve vertex coordinates */igraph_vector_init(&x, 0);igraph_vector_init(&y, 0);igraph_grg_game(&graph, 200, 0.1,/* torus */ 0, &x, &y);/* Compute edge weights as geometric distance */igraph_vector_init(&weights,igraph_ecount(&graph));igraph_eit_create(&graph,igraph_ess_all(IGRAPH_EDGEORDER_ID), &eit);for (; !IGRAPH_EIT_END(eit);IGRAPH_EIT_NEXT(eit)) {        igraph_integer_t e =IGRAPH_EIT_GET(eit);        igraph_integer_t u =IGRAPH_FROM(&graph, e);        igraph_integer_t v =IGRAPH_TO(&graph, e);VECTOR(weights)[e] =hypot(VECTOR(x)[u] -VECTOR(x)[v],VECTOR(y)[u] -VECTOR(y)[v]);    }igraph_eit_destroy(&eit);/* Compute average path length */igraph_average_path_length_dijkstra(&graph, &avg_dist, NULL, &weights, IGRAPH_UNDIRECTED,/* unconn */ 1);printf("Average distance in the geometric graph: %g.\n", avg_dist);/* Destroy data structures when no longer needed */igraph_vector_destroy(&weights);igraph_destroy(&graph);igraph_vector_destroy(&x);igraph_vector_destroy(&y);return 0;}


2.2. igraph_barabasi_game — Generates a graph based on the Barabási-Albert model.

igraph_error_t igraph_barabasi_game(igraph_t *graph, igraph_integer_t n,                         igraph_real_t power,                         igraph_integer_t m,                         const igraph_vector_int_t *outseq,                         igraph_bool_t outpref,                         igraph_real_t A,                         igraph_bool_t directed,                         igraph_barabasi_algorithm_t algo,                         const igraph_t *start_from);

This function implements several variants of the preferential attachmentprocess, including linear and non-linear varieties of the Barabási-Albertand Price models. The graph construction starts with a single vertex,or an existing graph given by thestart_from parameter. Then new verticesare added one at a time. Each new vertex connects tom existing vertices,choosing them with probabilities proportional to

d^power + A,

whered is the in- or total degree of the existing vertex (controlledby theoutpref argument), whilepower andA are given byparameters. Theconstant attractivenessAis used to ensure that vertices with zero in-degree can also beconnected to with non-zero probability.

Barabási, A.-L. and Albert R. 1999. Emergence of scaling inrandom networks, Science, 286 509--512.https://doi.org/10.1126/science.286.5439.509

de Solla Price, D. J. 1965. Networks of Scientific Papers, Science,149 510--515.https://doi.org/10.1126/science.149.3683.510

Arguments: 

graph:

An uninitialized graph object.

n:

The number of vertices in the graph.

power:

Power of the preferential attachment. In the classic preferential attachment modelpower=1. Other values allow for sampling from a non-linear preferential attachment model. Negative values are only allowed when no zero-degree vertices are present during the construction process, i.e. when the starting graph has no isolated vertices andoutpref is set totrue.

m:

The number of outgoing edges generated for each vertex. Only used whenoutseq isNULL.

outseq:

Gives the (out-)degrees of the vertices. If this is constant, this can be aNULL pointer or an empty vector. In this casem contains the constant out-degree. The very first vertex has by definition no outgoing edges, so the first number in this vector is ignored.

outpref:

Boolean, if true not only the in- but also the out-degree of a vertex increases its citation probability. I.e., the citation probability is determined by the total degree of the vertices. Ignored and assumed to be true if the graph being generated is undirected.

A:

The constant attractiveness of vertices. Whenoutpref is set tofalse, it should be positive to ensure that zero in-degree vertices can be connected to as well.

directed:

Boolean, whether to generate a directed graph. When set tofalse, outpref is assumed to betrue.

algo:

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

IGRAPH_BARABASI_BAG

This is the algorithm that was previously (before version 0.6) solely implemented in igraph. It works by putting the IDs of the vertices into a bag (multiset, really), exactly as many times as their (in-)degree, plus once more. Then the required number of cited vertices are drawn from the bag, with replacement. This method might generate multiple edges. It only works if power=1 and A=1.

IGRAPH_BARABASI_PSUMTREE

This algorithm uses a partial prefix-sum tree to generate the graph. It does not generate multiple edges and works for any power and A values.

IGRAPH_BARABASI_PSUMTREE_MULTIPLE

This algorithm also uses a partial prefix-sum tree to generate the graph. The difference is, that now multiple edges are allowed. This method was implemented under the nameigraph_nonlinear_barabasi_game before version 0.6.

start_from:

Either aNULL pointer, or a graph. In the former case, the starting configuration is a clique of sizem. In the latter case, the graph is a starting configuration. The graph must be non-empty, i.e. it must have at least one vertex. If a graph is supplied here and theoutseq argument is also given, thenoutseq should only contain information on the vertices that are not in thestart_from graph.

Returns: 

Error code:IGRAPH_EINVAL: invalidn,m,A oroutseq parameter.

Time complexity: O(|V|+|E|), thenumber of vertices plus the number of edges.

Example 9.15.  Fileexamples/simple/igraph_barabasi_game.c

#include <igraph.h>intmain(void) {    igraph_t g;    igraph_vector_int_t v;    igraph_vector_int_t v2, v3;igraph_barabasi_game(&g, 10,/*power=*/ 1, 2, 0, 0,/*A=*/ 1, 1,                         IGRAPH_BARABASI_BAG,/*start_from=*/ 0);if (igraph_ecount(&g) != 18) {return 1;    }if (igraph_vcount(&g) != 10) {return 2;    }if (!igraph_is_directed(&g)) {return 3;    }igraph_vector_int_init(&v, 0);igraph_get_edgelist(&g, &v, 0);for (igraph_integer_t i = 0; i <igraph_ecount(&g); i++) {if (VECTOR(v)[2 * i] <=VECTOR(v)[2 * i + 1]) {return 4;        }    }igraph_vector_int_destroy(&v);igraph_destroy(&g);/* out-degree sequence */igraph_vector_int_init_int(&v3, 10, 0, 1, 3, 3, 4, 5, 6, 7, 8, 9);igraph_barabasi_game(&g, 10,/*power=*/ 1, 0, &v3, 0,/*A=*/ 1, 1,                         IGRAPH_BARABASI_BAG,/*start_from=*/ 0);if (igraph_ecount(&g) !=igraph_vector_int_sum(&v3)) {return 5;    }igraph_vector_int_init(&v2, 0);igraph_degree(&g, &v2,igraph_vss_all(), IGRAPH_OUT, 1);for (igraph_integer_t i = 0; i <igraph_vcount(&g); i++) {if (VECTOR(v3)[i] !=VECTOR(v2)[i]) {igraph_vector_int_print(&v3);printf("\n");igraph_vector_int_print(&v2);return 6;        }    }igraph_vector_int_destroy(&v3);igraph_vector_int_destroy(&v2);igraph_destroy(&g);/* outpref, we cannot really test this quantitatively,       would need to set random seed */igraph_barabasi_game(&g, 10,/*power=*/ 1, 2, 0, 1,/*A=*/ 1, 1,                         IGRAPH_BARABASI_BAG,/*start_from=*/ 0);igraph_vector_int_init(&v, 0);igraph_get_edgelist(&g, &v, 0);for (igraph_integer_t i = 0; i <igraph_ecount(&g); i++) {if (VECTOR(v)[2 * i] <=VECTOR(v)[2 * i + 1]) {return 7;        }    }if (!igraph_is_directed(&g)) {return 8;    }igraph_vector_int_destroy(&v);igraph_destroy(&g);return 0;}


Example 9.16.  Fileexamples/simple/igraph_barabasi_game2.c

#include <igraph.h>#include <stdio.h>intmain(void) {    igraph_t g;    igraph_bool_t simple;igraph_barabasi_game(/* graph=    */ &g,/* n=        */ 100,/* power=    */ 1.0,/* m=        */ 2,/* outseq=   */ 0,/* outpref=  */ 0,/* A=        */ 1.0,/* directed= */ IGRAPH_DIRECTED,/* algo=     */ IGRAPH_BARABASI_PSUMTREE,/* start_from= */ 0);if (igraph_ecount(&g) != 197) {return 1;    }if (igraph_vcount(&g) != 100) {return 2;    }igraph_is_simple(&g, &simple);if (!simple) {return 3;    }igraph_destroy(&g);/* ============================== */igraph_barabasi_game(/* graph=    */ &g,/* n=        */ 100,/* power=    */ 1.0,/* m=        */ 2,/* outseq=   */ 0,/* outpref=  */ 0,/* A=        */ 1.0,/* directed= */ IGRAPH_DIRECTED,/* algo=     */ IGRAPH_BARABASI_PSUMTREE_MULTIPLE,/* start_from= */ 0);if (igraph_ecount(&g) != 198) {return 4;    }if (igraph_vcount(&g) != 100) {return 5;    }igraph_is_simple(&g, &simple);if (simple) {return 6;    }igraph_destroy(&g);/* ============================== */igraph_barabasi_game(/* graph=    */ &g,/* n=        */ 100,/* power=    */ 1.0,/* m=        */ 2,/* outseq=   */ 0,/* outpref=  */ 0,/* A=        */ 1.0,/* directed= */ IGRAPH_DIRECTED,/* algo=     */ IGRAPH_BARABASI_BAG,/* start_from= */ 0);if (igraph_ecount(&g) != 198) {return 7;    }if (igraph_vcount(&g) != 100) {return 8;    }igraph_is_simple(&g, &simple);if (simple) {return 9;    }igraph_destroy(&g);return 0;}


2.3. igraph_erdos_renyi_game_gnm — Generates a random (Erdős-Rényi) graph with a fixed number of edges.

igraph_error_t igraph_erdos_renyi_game_gnm(    igraph_t *graph, igraph_integer_t n, igraph_integer_t m,    igraph_bool_t directed, igraph_bool_t loops);

In theG(n, m) Erdős-Rényi model, a graph withn verticesandm edges is generated uniformly at random.

Arguments: 

graph:

Pointer to an uninitialized graph object.

n:

The number of vertices in the graph.

m:

The number of edges in the graph.

directed:

Whether to generate a directed graph.

loops:

Whether to generate self-loops.

Returns: 

Error code:IGRAPH_EINVAL: invalidn orm parameter.IGRAPH_ENOMEM: there is not enough memory for the operation.

Time complexity: O(|V|+|E|), thenumber of vertices plus the number of edges in the graph.

See also: 

igraph_erdos_renyi_game_gnp() to sample from the relatedG(n, p) model, which constrains theexpected edge count;igraph_degree_sequence_game() to constrain the degree sequence;igraph_bipartite_game_gnm() for the bipartite version of this model;igraph_barabasi_game() andigraph_growing_random_game() for othercommonly used random graph models.

Example 9.17.  Fileexamples/simple/igraph_erdos_renyi_game_gnm.c

#include <igraph.h>intmain(void) {    igraph_t graph;    igraph_vector_int_t component_sizes;igraph_rng_seed(igraph_rng_default(), 42);/* make program deterministic *//* Sample a graph from the Erdős-Rényi G(n,m) model */igraph_erdos_renyi_game_gnm(        &graph,/* n= */ 100,/* m= */ 100,        IGRAPH_UNDIRECTED, IGRAPH_NO_LOOPS    );/* Compute the fraction of vertices contained within the largest connected component */igraph_vector_int_init(&component_sizes, 0);igraph_connected_components(&graph, NULL, &component_sizes, NULL, IGRAPH_STRONG);printf(        "Fraction of vertices in giant component: %g\n",        ((double)igraph_vector_int_max(&component_sizes)) /igraph_vcount(&graph)    );/* Clean up data structures when no longer needed */igraph_vector_int_destroy(&component_sizes);igraph_destroy(&graph);return 0;}


2.4. igraph_erdos_renyi_game_gnp — Generates a random (Erdős-Rényi) graph with fixed edge probabilities.

igraph_error_t igraph_erdos_renyi_game_gnp(    igraph_t *graph, igraph_integer_t n, igraph_real_t p,    igraph_bool_t directed, igraph_bool_t loops);

In theG(n, p) Erdős-Rényi model, also known as the Gilbert model,or Bernoulli random graph, a graph withn vertices is generated such thatevery possible edge is included in the graph independently with probabilityp. This is equivalent to a maximum entropy random graph model model witha constraint on theexpected edge count. Settingp = 1/2generates all graphs onn vertices with the same probability.

The expected mean degree of the graph is approximatelyp n;setp = k/n when a mean degree of approximatelyk isdesired. More precisely, the expected mean degree isp(n-1)in (undirected or directed) graphs without self-loops,p(n+1) in undirected graphs with self-loops, andp n in directed graphs with self-loops.

Arguments: 

graph:

Pointer to an uninitialized graph object.

n:

The number of vertices in the graph.

p:

The probability of the existence of an edge in the graph.

directed:

Whether to generate a directed graph.

loops:

Whether to generate self-loops.

Returns: 

Error code:IGRAPH_EINVAL: invalidn orp parameter.IGRAPH_ENOMEM: there is not enough memory for the operation.

Time complexity: O(|V|+|E|), thenumber of vertices plus the number of edges in the graph.

See also: 

igraph_erdos_renyi_game_gnm() to generate random graphs witha sharply fixed edge count;igraph_chung_lu_game() andigraph_static_fitness_game() to generate random graphs with afixed expected degree sequence;igraph_bipartite_game_gnm() for thebipartite version of this model;igraph_barabasi_game() andigraph_growing_random_game() for other commonly used random graph models.

Example 9.18.  Fileexamples/simple/igraph_erdos_renyi_game_gnp.c

#include <igraph.h>intmain(void) {    igraph_t graph;    igraph_vector_int_t component_sizes;igraph_rng_seed(igraph_rng_default(), 42);/* make program deterministic *//* Sample a graph from the Erdős-Rényi G(n,p) model */igraph_erdos_renyi_game_gnp(        &graph,/* n= */ 100,/* p= */ 0.01,        IGRAPH_UNDIRECTED, IGRAPH_NO_LOOPS    );/* Compute the fraction of vertices contained within the largest connected component */igraph_vector_int_init(&component_sizes, 0);igraph_connected_components(&graph, NULL, &component_sizes, NULL, IGRAPH_STRONG);printf(        "Fraction of vertices in giant component: %g\n",        ((double)igraph_vector_int_max(&component_sizes)) /igraph_vcount(&graph)    );/* Clean up data structures when no longer needed */igraph_vector_int_destroy(&component_sizes);igraph_destroy(&graph);return 0;}


2.5. igraph_watts_strogatz_game — The Watts-Strogatz small-world model.

igraph_error_t igraph_watts_strogatz_game(igraph_t *graph, igraph_integer_t dim,                               igraph_integer_t size, igraph_integer_t nei,                               igraph_real_t p, igraph_bool_t loops,                               igraph_bool_t multiple);

This function generates networks with the small-world propertybased on a variant of the Watts-Strogatz model. The network is obtainedby first creating a periodic undirected lattice, then rewiring bothendpoints of each edge with probabilityp, while avoiding thecreation of multi-edges.

This process differs from the original model of Watts and Strogatz(see reference) in that it rewiresboth endpoints of edges. Thus inthe limit ofp=1, we obtain a G(n,m) random graph with thesame number of vertices and edges as the original lattice. In comparison,the original Watts-Strogatz model only rewires a single endpoint of each edge,thus the network does not become fully random even forp=1.For appropriate choices ofp, both models exhibit the property ofsimultaneously having short path lengths and high clustering.

Reference:

Duncan J Watts and Steven H Strogatz:Collective dynamics ofsmall world networks,Nature 393, 440-442, 1998.https://doi.org/10.1038/30918

Arguments: 

graph:

The graph to initialize.

dim:

The dimension of the lattice.

size:

The size of the lattice along each dimension.

nei:

The size of the neighborhood for each vertex. This is the same as theorder argument ofigraph_connect_neighborhood().

p:

The rewiring probability. A real number between zero and one (inclusive).

loops:

Whether to generate loop edges.

multiple:

Whether to allow multiple edges in the generated graph.

Returns: 

Error code.

See also: 

igraph_square_lattice(),igraph_connect_neighborhood() andigraph_rewire_edges() can be used if more flexibility isneeded, e.g. a different type of lattice.

Time complexity: O(|V|*d^o+|E|), |V| and |E| are the number ofvertices and edges, d is the average degree, o is theneiargument.

2.6. igraph_rewire_edges — Rewires the edges of a graph with constant probability.

igraph_error_t igraph_rewire_edges(igraph_t *graph, igraph_real_t prob,                        igraph_bool_t loops, igraph_bool_t multiple);

This function rewires the edges of a graph with a constantprobability. More precisely each end point of each edge is rewiredto a uniformly randomly chosen vertex with constant probabilityprob.

Note that this function modifies the inputgraph,calligraph_copy() if you want to keep it.

Arguments: 

graph:

The input graph, this will be rewired, it can be directed or undirected.

prob:

The rewiring probability a constant between zero and one (inclusive).

loops:

Boolean, whether loop edges are allowed in the new graph, or not.

multiple:

Boolean, whether multiple edges are allowed in the new graph.

Returns: 

Error code.

See also: 

igraph_watts_strogatz_game() uses this function for therewiring.

Time complexity: O(|V|+|E|).

2.7. igraph_rewire_directed_edges — Rewires the chosen endpoint of directed edges.

igraph_error_t igraph_rewire_directed_edges(igraph_t *graph, igraph_real_t prob,                                 igraph_bool_t loops, igraph_neimode_t mode);

This function rewires either the start or end of directed edges in a graphwith a constant probability. Correspondingly, either the in-degree sequenceor the out-degree sequence of the graph will be preserved.

Note that this function modifies the inputgraph,calligraph_copy() if you want to keep it.

This function can produce multiple edges between two vertices.

Arguments: 

graph:

The input graph, this will be rewired, it can be directed or undirected. If it is undirected ormode is set to IGRAPH_ALL,igraph_rewire_edges() will be called.

prob:

The rewiring probability, a constant between zero and one (inclusive).

loops:

Boolean, whether loop edges are allowed in the new graph, or not.

mode:

The endpoints of directed edges to rewire. It is ignored for undirected graphs. Possible values:

IGRAPH_OUT

rewire the end of each directed edge

IGRAPH_IN

rewire the start of each directed edge

IGRAPH_ALL

rewire both endpoints of each edge

Returns: 

Error code.

See also: 

Time complexity: O(|E|).

2.8. igraph_degree_sequence_game — Generates a random graph with a given degree sequence.

igraph_error_t igraph_degree_sequence_game(        igraph_t *graph,        const igraph_vector_int_t *out_deg,        const igraph_vector_int_t *in_deg,        igraph_degseq_t method);

This function generates random graphs with a prescribed degree sequence.Several sampling methods are available, which respect different constraints(simple graph or multigraphs, connected graphs, etc.), and provide differenttradeoffs between performance and unbiased sampling. See Section 2.1 ofHorvát and Modes (2021) for an overview of sampling techniques for graphswith fixed degrees.

References:

Fabien Viger, and Matthieu Latapy:Efficient and Simple Generation of Random Simple Connected Graphs with Prescribed Degree Sequence,Journal of Complex Networks 4, no. 1, pp. 15–37 (2015).https://doi.org/10.1093/comnet/cnv013.

Szabolcs Horvát, and Carl D Modes:Connectedness Matters: Construction and Exact Random Sampling of Connected Networks,Journal of Physics: Complexity 2, no. 1, pp. 015008 (2021).https://doi.org/10.1088/2632-072x/abced5.

Arguments: 

graph:

Pointer to an uninitialized graph object.

out_deg:

The degree sequence for an undirected graph (ifin_seq isNULL or of length zero), or the out-degree sequence of a directed graph (ifin_deq is not of length zero).

in_deg:

It is either a zero-length vector orNULL (if an undirected graph is generated), or the in-degree sequence.

method:

The method to generate the graph. Possible values:

IGRAPH_DEGSEQ_CONFIGURATION

This method implements the configuration model. For undirected graphs, it puts all vertex IDs in a bag such that the multiplicity of a vertex in the bag is the same as its degree. Then it draws pairs from the bag until the bag becomes empty. This method may generate both loop (self) edges and multiple edges. For directed graphs, the algorithm is basically the same, but two separate bags are used for the in- and out-degrees. Undirected graphs are generated with probability proportional to(\prod_{i<j} A_{ij} ! \prod_i A_{ii} !!)^{-1}, whereA denotes the adjacency matrix and!! denotes the double factorial. HereA is assumed to have twice the number of self-loops on its diagonal. The corresponding expression for directed graphs is(\prod_{i,j} A_{ij}!)^{-1}. Thus the probability of all simple graphs (which only have 0s and 1s in the adjacency matrix) is the same, while that of non-simple ones depends on their edge and self-loop multiplicities.

IGRAPH_DEGSEQ_CONFIGURATION_SIMPLE

This method is identical toIGRAPH_DEGSEQ_CONFIGURATION, but if the generated graph is not simple, it rejects it and re-starts the generation. It generates all simple graphs with the same probability.

IGRAPH_DEGSEQ_FAST_HEUR_SIMPLE

This method generates simple graphs. It is similar toIGRAPH_DEGSEQ_CONFIGURATION but tries to avoid multiple and loop edges and restarts the generation from scratch if it gets stuck. It can generate all simple realizations of a degree sequence, but it is not guaranteed to sample them uniformly. This method is relatively fast and it will eventually succeed if the provided degree sequence is graphical, but there is no upper bound on the number of iterations.

IGRAPH_DEGSEQ_EDGE_SWITCHING_SIMPLE

This is an MCMC sampler based on degree-preserving edge switches. It generates simple undirected or directed graphs. It usesigraph_realize_degree_sequence() to construct an initial graph, then rewires it usingigraph_rewire().

IGRAPH_DEGSEQ_VL

This method samples undirectedconnected graphs approximately uniformly. It is a Monte Carlo method based on degree-preserving edge switches. This generator should be favoured if undirected and connected graphs are to be generated and execution time is not a concern. igraph uses the original implementation of Fabien Viger; for the algorithm, seehttps://www-complexnetworks.lip6.fr/~latapy/FV/generation.html and the paperhttps://arxiv.org/abs/cs/0502085

Returns: 

Error code:IGRAPH_ENOMEM: there is not enough memory to perform the operation.IGRAPH_EINVAL: invalid method parameter, or invalid in- and/or out-degree vectors. The degree vectors should be non-negative,out_deg should sum up to an even integer for undirected graphs; the length and sum ofout_deg andin_deg should match for directed graphs.

Time complexity: O(|V|+|E|), the number of vertices plus the number of edgesforIGRAPH_DEGSEQ_CONFIGURATION andIGRAPH_DEGSEQ_EDGE_SWITCHING_SIMPLE.The time complexity of the other modes is not known.

See also: 

igraph_is_graphical() to determine if there exist graphs with a certaindegree sequence;igraph_erdos_renyi_game_gnm() to generate graphs with afixed number of edges, without any degree constraints;igraph_chung_lu_game()andigraph_static_fitness_game() to sample random graphs with a prescribedexpected degree sequence (but variable actual degrees);igraph_realize_degree_sequence() andigraph_realize_bipartite_degree_sequence()to generate a single (non-random) graph with given degrees.

Example 9.19.  Fileexamples/simple/igraph_degree_sequence_game.c

#include <igraph.h>intmain(void) {    igraph_t g;    igraph_vector_int_t outdeg, indeg;    igraph_vector_int_t vec;    igraph_bool_t is_simple;/* Set random seed for reproducibility */igraph_rng_seed(igraph_rng_default(), 42);igraph_vector_int_init_int(&outdeg, 10, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3);igraph_vector_int_init_int(&indeg, 10, 4, 4, 2, 2, 4, 4, 2, 2, 3, 3);igraph_vector_int_init(&vec, 0);/* checking the configuration model, undirected graphs */igraph_degree_sequence_game(&g, &outdeg, 0, IGRAPH_DEGSEQ_CONFIGURATION);if (igraph_is_directed(&g) ||igraph_vcount(&g) != 10) {return 1;    }if (igraph_degree(&g, &vec,igraph_vss_all(), IGRAPH_OUT, 1)) {return 2;    }igraph_vector_int_print(&vec);igraph_destroy(&g);/* checking the Viger-Latapy method, undirected graphs */igraph_degree_sequence_game(&g, &outdeg, 0, IGRAPH_DEGSEQ_VL);if (igraph_is_directed(&g) ||igraph_vcount(&g) != 10) {return 3;    }if (igraph_is_simple(&g, &is_simple) || !is_simple) {return 4;    }if (igraph_degree(&g, &vec,igraph_vss_all(), IGRAPH_OUT, 0)) {return 5;    }igraph_vector_int_print(&vec);igraph_destroy(&g);/* checking the configuration model, directed graphs */igraph_degree_sequence_game(&g, &outdeg, &indeg, IGRAPH_DEGSEQ_CONFIGURATION);if (!igraph_is_directed(&g) ||igraph_vcount(&g) != 10) {return 6;    }if (igraph_degree(&g, &vec,igraph_vss_all(), IGRAPH_OUT, 1)) {return 7;    }igraph_vector_int_print(&vec);if (igraph_degree(&g, &vec,igraph_vss_all(), IGRAPH_IN, 1)) {return 8;    }igraph_vector_int_print(&vec);igraph_destroy(&g);/* checking the fast heuristic method, undirected graphs */igraph_degree_sequence_game(&g, &outdeg, 0, IGRAPH_DEGSEQ_FAST_HEUR_SIMPLE);if (igraph_is_directed(&g) ||igraph_vcount(&g) != 10) {return 9;    }if (igraph_is_simple(&g, &is_simple) || !is_simple) {return 10;    }if (igraph_degree(&g, &vec,igraph_vss_all(), IGRAPH_OUT, 1)) {return 11;    }igraph_vector_int_print(&vec);igraph_destroy(&g);/* checking the fast heuristic method, directed graphs */igraph_degree_sequence_game(&g, &outdeg, &indeg, IGRAPH_DEGSEQ_FAST_HEUR_SIMPLE);if (!igraph_is_directed(&g) ||igraph_vcount(&g) != 10) {return 12;    }if (igraph_is_simple(&g, &is_simple) || !is_simple) {return 13;    }if (igraph_degree(&g, &vec,igraph_vss_all(), IGRAPH_OUT, 1)) {return 14;    }igraph_vector_int_print(&vec);if (igraph_degree(&g, &vec,igraph_vss_all(), IGRAPH_IN, 1)) {return 15;    }igraph_vector_int_print(&vec);igraph_destroy(&g);igraph_vector_int_destroy(&vec);igraph_vector_int_destroy(&outdeg);igraph_vector_int_destroy(&indeg);return 0;}


2.9. igraph_k_regular_game — Generates a random graph where each vertex has the same degree.

igraph_error_t igraph_k_regular_game(igraph_t *graph,                          igraph_integer_t no_of_nodes, igraph_integer_t k,                          igraph_bool_t directed, igraph_bool_t multiple);

This game generates a directed or undirected random graph where thedegrees of vertices are equal to a predefined constant k. For undirectedgraphs, at least one of k and the number of vertices must be even.

Currently, this game simply usesigraph_degree_sequence_game withtheIGRAPH_DEGSEQ_CONFIGURATION or theIGRAPH_DEGSEQ_FAST_SIMPLEmethod and appropriately constructed degree sequences.Thefore, it does not sample uniformly: while it can generate all k-regulargraphs with the given number of vertices, it does not generate each one withthe same probability.

Arguments: 

graph:

Pointer to an uninitialized graph object.

no_of_nodes:

The number of nodes in the generated graph.

k:

The degree of each vertex in an undirected graph, or the out-degree and in-degree of each vertex in a directed graph.

directed:

Whether the generated graph will be directed.

multiple:

Whether to allow multiple edges in the generated graph.

Returns: 

Error code:IGRAPH_EINVAL: invalid parameter; e.g., negative number of nodes, or odd number of nodes and odd k for undirected graphs.IGRAPH_ENOMEM: there is not enough memory for the operation.

Time complexity: O(|V|+|E|) ifmultiple is true, otherwise not known.

2.10. igraph_static_fitness_game — Non-growing random graph with edge probabilities proportional to node fitness scores.

igraph_error_t igraph_static_fitness_game(igraph_t *graph, igraph_integer_t no_of_edges,                               const igraph_vector_t *fitness_out, const igraph_vector_t *fitness_in,                               igraph_bool_t loops, igraph_bool_t multiple);

This game generates a directed or undirected random graph where theprobability of an edge between verticesi andj depends on the fitnessscores of the two vertices involved. For undirected graphs, each vertexhas a single fitness score. For directed graphs, each vertex has an out-and an in-fitness, and the probability of an edge fromi toj depends onthe out-fitness of vertexi and the in-fitness of vertexj.

The generation process goes as follows. We start fromN disconnected nodes(whereN is given by the length of the fitness vector). Then we randomlyselect two verticesi andj, with probabilities proportional to theirfitnesses. (When the generated graph is directed,i is selected according tothe out-fitnesses andj is selected according to the in-fitnesses). If thevertices are not connected yet (or if multiple edges are allowed), weconnect them; otherwise we select a new pair. This is repeated until thedesired number of links are created.

Theexpected degree (though not the actual degree) of each vertex will beproportional to its fitness. This is exactly true when self-loops and multi-edgesare allowed, and approximately true otherwise. If you need to generate a graphwith an exact degree sequence, considerigraph_degree_sequence_game() andigraph_realize_degree_sequence() instead.

To generate random undirected graphs with a given expected degree sequence, setfitness_out (and in the directed casefitness_out) to the desired expecteddegrees, andno_of_edges to the corresponding edge count, i.e. half the sum ofexpected degrees in the undirected case, and the sum of out- or in-degrees in thedirected case.

This model is similar to the better-known Chung-Lu model, implemented in igraphasigraph_chung_lu_game(), but with a sharply fixed edge count.

This model is commonly used to generate static scale-free networks. Toachieve this, you have to draw the fitness scores from the desired power-lawdistribution. Alternatively, you may useigraph_static_power_law_game()which generates the fitnesses for you with a given exponent.

Reference:

Goh K-I, Kahng B, Kim D: Universal behaviour of load distributionin scale-free networks. Phys Rev Lett 87(27):278701, 2001https://doi.org/10.1103/PhysRevLett.87.278701.

Arguments: 

graph:

Pointer to an uninitialized graph object.

no_of_edges:

The number of edges in the generated graph.

fitness_out:

A numeric vector containing the fitness of each vertex. For directed graphs, this specifies the out-fitness of each vertex.

fitness_in:

IfNULL, the generated graph will be undirected. If notNULL, this argument specifies the in-fitness of each vertex.

loops:

Whether to allow loop edges in the generated graph.

multiple:

Whether to allow multiple edges in the generated graph.

Returns: 

Error code:IGRAPH_EINVAL: invalid parameterIGRAPH_ENOMEM: there is not enough memory for the operation.

See also: 

Time complexity: O(|V| + |E| log |E|).

2.11. igraph_static_power_law_game — Generates a non-growing random graph with expected power-law degree distributions.

igraph_error_t igraph_static_power_law_game(igraph_t *graph,                                 igraph_integer_t no_of_nodes, igraph_integer_t no_of_edges,                                 igraph_real_t exponent_out, igraph_real_t exponent_in,                                 igraph_bool_t loops, igraph_bool_t multiple,                                 igraph_bool_t finite_size_correction);

This game generates a directed or undirected random graph where thedegrees of vertices follow power-law distributions with prescribedexponents. For directed graphs, the exponents of the in- and out-degreedistributions may be specified separately.

The game simply usesigraph_static_fitness_game() with appropriatelyconstructed fitness vectors. In particular, the fitness of vertexiisi^(-alpha), wherealpha = 1/(gamma-1)andgamma is the exponent given in the arguments.

To remove correlations between in- and out-degrees in case of directedgraphs, the in-fitness vector will be shuffled after it has been set upand beforeigraph_static_fitness_game() is called.

Note that significant finite size effects may be observed for exponentssmaller than 3 in the original formulation of the game. This functionprovides an argument that lets you remove the finite size effects byassuming that the fitness of vertexi is(i+i0-1)^(-alpha),wherei0 is a constant chosen appropriately to ensure that the maximumdegree is less than the square root of the number of edges times theaverage degree; see the paper of Chung and Lu, and Cho et al for moredetails.

References:

Goh K-I, Kahng B, Kim D: Universal behaviour of load distributionin scale-free networks. Phys Rev Lett 87(27):278701, 2001.https://doi.org/10.1103/PhysRevLett.87.278701

Chung F and Lu L: Connected components in a random graph with givendegree sequences. Annals of Combinatorics 6, 125-145, 2002.https://doi.org/10.1007/PL00012580

Cho YS, Kim JS, Park J, Kahng B, Kim D: Percolation transitions inscale-free networks under the Achlioptas process. Phys Rev Lett103:135702, 2009.https://doi.org/10.1103/PhysRevLett.103.135702

Arguments: 

graph:

Pointer to an uninitialized graph object.

no_of_nodes:

The number of nodes in the generated graph.

no_of_edges:

The number of edges in the generated graph.

exponent_out:

The power law exponent of the degree distribution. For directed graphs, this specifies the exponent of the out-degree distribution. It must be greater than or equal to 2. If you passIGRAPH_INFINITY here, you will get back an Erdős-Rényi random network.

exponent_in:

If negative, the generated graph will be undirected. If greater than or equal to 2, this argument specifies the exponent of the in-degree distribution. If non-negative but less than 2, an error will be generated.

loops:

Whether to allow loop edges in the generated graph.

multiple:

Whether to allow multiple edges in the generated graph.

finite_size_correction:

Whether to use the proposed finite size correction of Cho et al.

Returns: 

Error code:IGRAPH_EINVAL: invalid parameterIGRAPH_ENOMEM: there is not enough memory for the operation.

Time complexity: O(|V| + |E| log |E|).

2.12. igraph_chung_lu_game — Samples graphs from the Chung-Lu model.

igraph_error_t igraph_chung_lu_game(igraph_t *graph,                                    const igraph_vector_t *out_weights,                                    const igraph_vector_t *in_weights,                                    igraph_bool_t loops,                                    igraph_chung_lu_t variant);

Warning

This function is experimental and its signature is not considered final yet.We reserve the right to change the function signature without changing themajor version of igraph. Use it at your own risk.

The Chung-Lu model is useful for generating random graphs with fixedexpected degrees. This function implements both the original model of Chungand Lu, as well as some additional variants with useful properties.

In the original Chung-Lu model, each pair of verticesi andj isconnected with independent probabilityp_ij = w_i w_j / S,wherew_i is a weight associated with vertexi andS = sum_k w_k is the sum of weights. In the directed variant,vertices have both out-weights,w^out, and in-weights,w^in, with equal sums,S = sum_k w^out_k = sum_k w^in_k.The connection probability betweeni andj isp_ij = w^out_i w^in_j / S.

This model is commonly used to create random graphs with a fixedexpecteddegree sequence. The expected degree of vertexi is approximately equalto the weightw_i. Specifically, if the graph is directed and self-loopsare allowed, then the expected out- and in-degrees are preciselyw^out andw^in. If self-loops are disallowed,then the expected out- and in-degrees arew^out (S - w^in) / Sandw^in (S - w^out) / S, respectively. If the graph isundirected, then the expected degrees with and without self-loops arew (S + w) / S andw (S - w) / S, respectively.

A limitation of the original Chung-Lu model is that when some of theweights are large, the formula forp_ij yields values larger than 1.Chung and Lu's original paper excludes the use of such weights. Whenp_ij > 1, this function simply issues a warning and createsa connection betweeni andj. However, in this case the expected degreeswill no longer relate to the weights in the manner stated above. Thus theoriginal Chung-Lu model cannot produce certain (large) expected degrees.

The overcome this limitation, this function implements additional variants ofthe model, with modified expressions for the connection probabilityp_ijbetween verticesi andj. Letq_ij = w_i w_j / S, orq_ij = w^out_i w^in_j / S in the directed case. All modelvariants become equivalent in the limit of sparse graphs whereq_ijapproaches zero. In the original Chung-Lu model, selectable by settingvariant toIGRAPH_CHUNG_LU_ORIGINAL,p_ij = min(q_ij, 1).TheIGRAPH_CHUNG_LU_MAXENT variant, sometiems referred to a the generalizedrandom graph, usesp_ij = q_ij / (1 + q_ij), and is equivalentto a maximum entropy model (i.e. exponential random graph model) witha constraint on expected degrees; see Park and Newman (2004), Section B,settingexp(-Theta_ij) = w_i w_j / S. This model is alsodiscussed by Britton, Deijfen and Martin-Löf (2006). By virtue of beinga degree-constrained maximum entropy model, it produces graphs with thesame degree sequence with the same probability.A third variant can be requested withIGRAPH_CHUNG_LU_NR, and usesp_ij = 1 - exp(-q_ij). This is the underlying simple graphof a multigraph model introduced by Norros and Reittu (2006).For a discussion of these three model variants, see Section 16.4 ofBollobás, Janson, Riordan (2007), as well as Van Der Hofstad (2013).

References:

Chung F and Lu L: Connected components in a random graph with givendegree sequences. Annals of Combinatorics 6, 125-145 (2002).https://doi.org/10.1007/PL00012580

Miller JC and Hagberg A:Efficient Generation of Networks with Given Expected Degrees (2011).https://doi.org/10.1007/978-3-642-21286-4_10

Park J and Newman MEJ: Statistical mechanics of networks.Physical Review E 70, 066117 (2004).https://doi.org/10.1103/PhysRevE.70.066117

Britton T, Deijfen M, Martin-Löf A:Generating Simple Random Graphs with Prescribed Degree Distribution.J Stat Phys 124, 1377–1397 (2006).https://doi.org/10.1007/s10955-006-9168-x

Norros I and Reittu H: On a conditionally Poissonian graph process.Advances in Applied Probability 38, 59–75 (2006).https://doi.org/10.1239/aap/1143936140

Bollobás B, Janson S, Riordan O:The phase transition in inhomogeneous random graphs.Random Struct Algorithms 31, 3–122 (2007).https://doi.org/10.1002/rsa.20168

Van Der Hofstad R: Critical behavior in inhomogeneous random graphs.Random Struct Algorithms 42, 480–508 (2013).https://doi.org/10.1002/rsa.20450

Arguments: 

graph:

Pointer to an uninitialized graph object.

out_weights:

A vector of non-negative vertex weights (or out-weights). In sparse graphs these will be approximately equal to the expected (out-)degrees.

in_weights:

A vector of non-negative in-weights, approximately equal to the expected in-degrees in sparse graphs. May be set toNULL, in which case undirected graphs are generated.

loops:

Whether to allow the creation of self-loops. Since vertex pairs are connected independently, setting this to false is equivalent to simply discarding self-loops from an existing loopy Chung-Lu graph.

variant:

The model variant to sample from, with different definitions of the connection probability between verticesi andj. Givenq_ij = w_i w_j / S, the following formulations are available:

IGRAPH_CHUNG_LU_ORIGINAL

the original Chung-Lu model,p_ij = min(q_ij, 1).

IGRAPH_CHUNG_LU_MAXENT

maximum entropy model with fixed expected degrees,p_ij = q_ij / (1 + q_ij).

IGRAPH_CHUNG_LU_NR

Norros and Reittu's model,p_ij = 1 - exp(-q_ij).

Returns: 

Error code.

See also: 

igraph_static_fitness_game() implements a similar model witha sharp constraint on the number of edges;igraph_degree_sequence_game() samples random graphs with sharplyspecified degrees;igraph_erdos_renyi_game_gnp() creates randomgraphs with a fixed connection probabilityp between all vertex pairs.

Time complexity: O(|E| + |V|), linear in the number of edges.

2.13. igraph_forest_fire_game — Generates a network according to theforest fire game.

igraph_error_t igraph_forest_fire_game(igraph_t *graph, igraph_integer_t nodes,                            igraph_real_t fw_prob, igraph_real_t bw_factor,                            igraph_integer_t pambs, igraph_bool_t directed);

The forest fire model intends to reproduce the following networkcharacteristics, observed in real networks:

  • Heavy-tailed in- and out-degree distributions.

  • Community structure.

  • Densification power-law. The network is densifying in time, according to a power-law rule.

  • Shrinking diameter. The diameter of the network decreases in time.

The network is generated in the following way. One vertex is added ata time. This vertex connects to (cites)ambs vertices alreadypresent in the network, chosen uniformly random. Now, for each citedvertexv we do the following procedure:

  1. We generate two random numbers,x andy, that are geometrically distributed with meansp/(1-p) andrp(1-rp). (p isfw_prob,r isbw_factor.) The new vertex citesx outgoing neighbors andy incoming neighbors ofv, from those which are not yet cited by the new vertex. If there are less thanx ory such vertices available then we cite all of them.

  2. The same procedure is applied to all the newly cited vertices.

See also:Jure Leskovec, Jon Kleinberg and Christos Faloutsos. Graphs over time:densification laws, shrinking diameters and possible explanations. KDD '05: Proceeding of the eleventh ACM SIGKDD internationalconference on Knowledge discovery in data mining, 177--187, 2005.

Note however, that the version of the model in the published paper is incorrectin the sense that it cannot generate the kind of graphs the authorsclaim. A corrected version is available fromhttps://www.cs.cmu.edu/~jure/pubs/powergrowth-tkdd.pdf, ourimplementation is based on this.

Arguments: 

graph:

Pointer to an uninitialized graph object.

nodes:

The number of vertices in the graph.

fw_prob:

The forward burning probability.

bw_factor:

The backward burning ratio. The backward burning probability is calculated asbw_factor * fw_prob.

pambs:

The number of ambassador vertices.

directed:

Whether to create a directed graph.

Returns: 

Error code.

Time complexity: TODO.

2.14. igraph_rewire — Randomly rewires a graph while preserving its degree sequence.

igraph_error_t igraph_rewire(igraph_t *graph, igraph_integer_t n, igraph_rewiring_t mode);

This function generates a new graph based on the original one by randomly"rewriting" edges while preserving the original graph's degree sequence.The rewiring is done "in place", so no new graph will be allocated. If youwould like to keep the original graph intact, useigraph_copy()beforehand. All graph attributes will be lost.

The rewiring is performed with degree-preserving edge switches:Two arbitrary edges are picked uniformly at random, namely(a, b) and(c, d), then they are replacedby(a, d) and(b, c) if this preserves theconstraints specified bymode.

Arguments: 

graph:

The graph object to be rewired.

n:

Number of rewiring trials to perform.

mode:

The rewiring algorithm to be used. It can be one of the following flags:

IGRAPH_REWIRING_SIMPLE

This method does not create or destroy self-loops, and does not create multi-edges.

IGRAPH_REWIRING_SIMPLE_LOOPS

This method allows the creation or destruction of self-loops. Self-loops are created by switching edges that have a single common endpoint.

Returns: 

Error code:

IGRAPH_EINVMODE

Invalid rewiring mode.

IGRAPH_ENOMEM

Not enough memory for temporary data.

Time complexity: TODO.

2.15. igraph_growing_random_game — Generates a growing random graph.

igraph_error_t igraph_growing_random_game(igraph_t *graph, igraph_integer_t n,                               igraph_integer_t m, igraph_bool_t directed,                               igraph_bool_t citation);

This function simulates a growing random graph. We start out withone vertex. In each step a new vertex is added and a number of newedges are also added. These graphs are known to be differentfrom standard (not growing) random graphs.

Arguments: 

graph:

Uninitialized graph object.

n:

The number of vertices in the graph.

m:

The number of edges to add in a time step (i.e. after adding a vertex).

directed:

Boolean, whether to generate a directed graph.

citation:

Boolean, iftrue, the edges always originate from the most recently added vertex and are connected to a previous vertex.

Returns: 

Error code:IGRAPH_EINVAL: invalidn orm parameter.

Time complexity: O(|V|+|E|), thenumber of vertices plus the number of edges.

2.16. igraph_callaway_traits_game — Simulates a growing network with vertex types.

igraph_error_t igraph_callaway_traits_game(igraph_t *graph, igraph_integer_t nodes,                                igraph_integer_t types, igraph_integer_t edges_per_step,                                const igraph_vector_t *type_dist,                                const igraph_matrix_t *pref_matrix,                                igraph_bool_t directed,                                igraph_vector_int_t *node_type_vec);

The different types of vertices prefer to connect other types ofvertices with a given probability.

The simulation goes like this: in each discrete time step a newvertex is added to the graph. The type of this vertex is generatedbased ontype_dist. Then two vertices are selected uniformlyrandomly from the graph. The probability that they will beconnected depends on the types of these vertices and is taken frompref_matrix. Then another two vertices are selected and this isrepeatededges_per_step times in each time step.

References:

D. S. Callaway, J. E. Hopcroft, J. M. Kleinberg, M. E. J. Newman, and S. H. Strogatz,Are randomly grown graphs really random?Phys. Rev. E 64, 041902 (2001).https://doi.org/10.1103/PhysRevE.64.041902

Arguments: 

graph:

Pointer to an uninitialized graph.

nodes:

The number of nodes in the graph.

types:

Number of node types.

edges_per_step:

The number of connections tried in each time step.

type_dist:

Vector giving the distribution of the vertex types. IfNULL, the distribution is assumed to be uniform.

pref_matrix:

Matrix giving the connection probabilities for the vertex types.

directed:

Whether to generate a directed graph.

node_type_vec:

An initialized vector orNULL. If notNULL, the type of each node will be stored here.

Returns: 

Error code.

Added in version 0.2.

Time complexity: O(|V|*k*log(|V|)), |V| is the number of vertices,k isedges_per_step.

2.17. igraph_establishment_game — Generates a graph with a simple growing model with vertex types.

igraph_error_t igraph_establishment_game(igraph_t *graph, igraph_integer_t nodes,                              igraph_integer_t types, igraph_integer_t k,                              const igraph_vector_t *type_dist,                              const igraph_matrix_t *pref_matrix,                              igraph_bool_t directed,                              igraph_vector_int_t *node_type_vec);

The simulation goes like this: a single vertex is added at eachtime step. This new vertex tries to connect tok vertices in thegraph. The probability that such a connection is realized dependson the types of the vertices involved.

Arguments: 

graph:

Pointer to an uninitialized graph.

nodes:

The number of vertices in the graph.

types:

The number of vertex types.

k:

The number of connections tried in each time step.

type_dist:

Vector giving the distribution of vertex types.IfNULL, the distribution is assumed to be uniform.

pref_matrix:

Matrix giving the connection probabilities fordifferent vertex types.

directed:

Whether to generate a directed graph.

node_type_vec:

An initialized vector orNULL.If notNULL, the type of each node will be stored here.

Returns: 

Error code.

Added in version 0.2.

Time complexity: O(|V|*k*log(|V|)), |V| is the number of verticesand k is thek parameter.

2.18. igraph_preference_game — Generates a graph with vertex types and connection preferences.

igraph_error_t igraph_preference_game(igraph_t *graph, igraph_integer_t nodes,                           igraph_integer_t types,                           const igraph_vector_t *type_dist,                           igraph_bool_t fixed_sizes,                           const igraph_matrix_t *pref_matrix,                           igraph_vector_int_t *node_type_vec,                           igraph_bool_t directed,                           igraph_bool_t loops);

This is practically the nongrowing variant ofigraph_establishment_game(). A given number of vertices aregenerated. Every vertex is assigned to a vertex type according tothe given type probabilities. Finally, everyvertex pair is evaluated and an edge is created between them with aprobability depending on the types of the vertices involved.

In other words, this function generates a graph according to ablock-model. Vertices are divided into groups (or blocks), andthe probability the two vertices are connected depends on theirgroups only.

Arguments: 

graph:

Pointer to an uninitialized graph.

nodes:

The number of vertices in the graph.

types:

The number of vertex types.

type_dist:

Vector giving the distribution of vertex types. IfNULL, all vertex types will have equal probability. See also thefixed_sizes argument.

fixed_sizes:

Boolean. If true, then the number of vertices with a given vertex type is fixed and thetype_dist argument gives these numbers for each vertex type. If true, andtype_dist isNULL, then the function tries to make vertex groups of the same size. If this is not possible, then some groups will have an extra vertex.

pref_matrix:

Matrix giving the connection probabilities for different vertex types. This should be symmetric if the requested graph is undirected.

node_type_vec:

A vector where the individual generated vertex types will be stored. IfNULL, the vertex types won't be saved.

directed:

Whether to generate a directed graph. If undirected graphs are requested, only the lower left triangle of the preference matrix is considered.

loops:

Whether loop edges are allowed.

Returns: 

Error code.

Added in version 0.3.

Time complexity: O(|V|+|E|), thenumber of vertices plus the number of edges in the graph.

See also: 

2.19. igraph_asymmetric_preference_game — Generates a graph with asymmetric vertex types and connection preferences.

igraph_error_t igraph_asymmetric_preference_game(igraph_t *graph, igraph_integer_t nodes,                                      igraph_integer_t no_out_types,                                      igraph_integer_t no_in_types,                                      const igraph_matrix_t *type_dist_matrix,                                      const igraph_matrix_t *pref_matrix,                                      igraph_vector_int_t *node_type_out_vec,                                      igraph_vector_int_t *node_type_in_vec,                                      igraph_bool_t loops);

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

Arguments: 

graph:

Pointer to an uninitialized graph.

nodes:

The number of vertices in the graph.

no_out_types:

The number of vertex out-types.

no_in_types:

The number of vertex in-types.

type_dist_matrix:

Matrix of sizeout_types * in_types, giving the joint distribution of vertex types. IfNULL, incoming and outgoing vertex types are independent and uniformly distributed.

pref_matrix:

Matrix of sizeout_types * in_types, giving the connection probabilities for different vertex types.

node_type_out_vec:

A vector where the individual generated "outgoing" vertex types will be stored. IfNULL, the vertex types won't be saved.

node_type_in_vec:

A vector where the individual generated "incoming" vertex types will be stored. IfNULL, the vertex types won't be saved.

loops:

Whether loop edges are allowed.

Returns: 

Error code.

Added in version 0.3.

Time complexity: O(|V|+|E|), thenumber of vertices plus the number of edges in the graph.

See also: 

2.20. igraph_recent_degree_game — Stochastic graph generator based on the number of incident edges a node has gained recently.

igraph_error_t igraph_recent_degree_game(igraph_t *graph, igraph_integer_t nodes,                              igraph_real_t power,                              igraph_integer_t time_window,                              igraph_integer_t m,                              const igraph_vector_int_t *outseq,                              igraph_bool_t outpref,                              igraph_real_t zero_appeal,                              igraph_bool_t directed);

Arguments: 

graph:

Pointer to an uninitialized graph object.

nodes:

The number of vertices in the graph, this is the same as the number of time steps.

power:

The exponent, the probability that a node gains a new edge is proportional to the number of edges it has gained recently (in the lastwindow time steps) topower.

time_window:

Integer constant, the size of the time window to use to count the number of recent edges.

m:

Integer constant, the number of edges to add per time step if theoutseq parameter is a null pointer or a zero-length vector.

outseq:

The number of edges to add in each time step. This argument is ignored if it is a null pointer or a zero length vector. In this case the constantm parameter is used.

outpref:

Boolean constant, if true the edges originated by a vertex also count as recent incident edges. For most applications it is reasonable to set it to false.

zero_appeal:

Constant giving the attractiveness of the vertices which haven't gained any edge recently.

directed:

Boolean constant, whether to generate a directed graph.

Returns: 

Error code.

Time complexity: O(|V|*log(|V|)+|E|), |V| is the number ofvertices, |E| is the number of edges in the graph.

2.21. igraph_barabasi_aging_game — Preferential attachment with aging of vertices.

igraph_error_t igraph_barabasi_aging_game(igraph_t *graph,                               igraph_integer_t nodes,                               igraph_integer_t m,                               const igraph_vector_int_t *outseq,                               igraph_bool_t outpref,                               igraph_real_t pa_exp,                               igraph_real_t aging_exp,                               igraph_integer_t aging_bins,                               igraph_real_t zero_deg_appeal,                               igraph_real_t zero_age_appeal,                               igraph_real_t deg_coef,                               igraph_real_t age_coef,                               igraph_bool_t directed);

This game starts with one vertex (ifnodes > 0). In each stepa new node is added, and it is connected tom existing nodes.Existing nodes to connect to are chosen with probability dependenton their (in-)degree (k) and age (l).The degree-dependent part isdeg_coef * k^pa_exp + zero_deg_appeal,while the age-dependent part isage_coef * l^aging_exp + zero_age_appeal,which are multiplied to obtain the final weight.

The agel is based on the number of vertices in thenetwork and theaging_bins argument: the age of a nodeis incremented by 1 after eachfloor(nodes / aging_bins) + 1time steps.

Arguments: 

graph:

Pointer to an uninitialized graph object.

nodes:

The number of vertices in the graph.

m:

The number of edges to add in each time step. Ignored ifoutseq is a non-zero length vector.

outseq:

The number of edges to add in each time step. If it isNULL or a zero-length vector then it is ignored and them argument is used instead.

outpref:

Boolean constant, whether the edges initiated by a vertex contribute to the probability to gain a new edge.

pa_exp:

The exponent of the preferential attachment, a small positive number usually, the value 1 yields the classic linear preferential attachment.

aging_exp:

The exponent of the aging, this is a negative number usually.

aging_bins:

Integer constant, the number of age bins to use.

zero_deg_appeal:

The degree dependent part of the attractiveness of the zero degree vertices.

zero_age_appeal:

The age dependent part of the attractiveness of the vertices of age zero. This parameter is usually zero.

deg_coef:

The coefficient for the degree.

age_coef:

The coefficient for the age.

directed:

Boolean constant, whether to generate a directed graph.

Returns: 

Error code.

Time complexity: O((|V|+|V|/aging_bins)*log(|V|)+|E|). |V| is the numberof vertices, |E| the number of edges.

2.22. igraph_recent_degree_aging_game — Preferential attachment based on the number of edges gained recently, with aging of vertices.

igraph_error_t igraph_recent_degree_aging_game(igraph_t *graph,                                    igraph_integer_t nodes,                                    igraph_integer_t m,                                    const igraph_vector_int_t *outseq,                                    igraph_bool_t outpref,                                    igraph_real_t pa_exp,                                    igraph_real_t aging_exp,                                    igraph_integer_t aging_bins,                                    igraph_integer_t time_window,                                    igraph_real_t zero_appeal,                                    igraph_bool_t directed);

This game is very similar toigraph_barabasi_aging_game(),except that instead of the total number of incident edges thenumber of edges gained in the lasttime_window time steps arecounted.

The degree dependent part of the attractiveness isgiven by k to the power ofpa_exp pluszero_appeal; the agedependent part is l to the power toaging_exp.k is the number of edges gained in the lasttime_window timesteps, l is the age of the vertex.

Arguments: 

graph:

Pointer to an uninitialized graph object.

nodes:

The number of vertices in the graph.

m:

The number of edges to add in each time step. If theoutseq argument is not a null vector or a zero-length vector then it is ignored.

outseq:

Vector giving the number of edges to add in each time step. If it is a null pointer or a zero-length vector then it is ignored and them argument is used.

outpref:

Boolean constant, if true the edges initiated by a vertex are also counted. Normally it is false.

pa_exp:

The exponent for the preferential attachment.

aging_exp:

The exponent for the aging, normally it is negative: old vertices gain edges with less probability.

aging_bins:

Integer constant, the number of age bins to use.

time_window:

The time window to use to count the number of incident edges for the vertices.

zero_appeal:

The degree dependent part of the attractiveness for zero degree vertices.

directed:

Boolean constant, whether to create a directed graph.

Returns: 

Error code.

Time complexity: O((|V|+|V|/aging_bins)*log(|V|)+|E|). |V| is the numberof vertices, |E| the number of edges.

2.23. igraph_lastcit_game — Simulates a citation network, based on time passed since the last citation.

igraph_error_t igraph_lastcit_game(igraph_t *graph,                        igraph_integer_t nodes, igraph_integer_t edges_per_node,                        igraph_integer_t agebins,                        const igraph_vector_t *preference,                        igraph_bool_t directed);

This is a quite special stochastic graph generator, it models anevolving graph. In each time step a single vertex is added to thenetwork and it cites a number of other vertices (as specified bytheedges_per_step argument). The cited vertices are selectedbased on the last time they were cited. Time is measured by theaddition of vertices and it is binned intoagebins bins.So if the current time step ist and the last citation to agiveni vertex was made in time stept0, then(t-t0) / binwidthis calculated where binwidth isnodes/agebins + 1,in the last expression '/' denotes integer division, so thefraction part is omitted.

Thepreference argument specifies the preferences for thecitation lags, i.e. its first elements contains the attractivityof the very recently cited vertices, etc. The last element isspecial, it contains the attractivity of the vertices which werenever cited. This element should be bigger than zero.

Note that this function generates networks with multiple edges ifedges_per_step is bigger than one, calligraph_simplify()on the result to get rid of these edges.

Arguments: 

graph:

Pointer to an uninitialized graph object, the result will be stored here.

nodes:

The number of vertices in the network.

edges_per_node:

The number of edges to add in each time step.

agebins:

The number of age bins to use.

preference:

Pointer to an initialized vector of lengthagebins + 1. This contains the "attractivity" of the various age bins, the last element is the attractivity of the vertices which were never cited, and it should be greater than zero. It is a good idea to have all positive values in this vector. Preferences cannot be negative.

directed:

Boolean constant, whether to create directed networks.

Returns: 

Error code.

See also: 

Time complexity: O(|V|*a+|E|*log|V|), |V| is the number of vertices,|E| is the total number of edges, a is theagebins parameter.

2.24. igraph_cited_type_game — Simulates a citation based on vertex types.

igraph_error_t igraph_cited_type_game(igraph_t *graph, igraph_integer_t nodes,                           const igraph_vector_int_t *types,                           const igraph_vector_t *pref,                           igraph_integer_t edges_per_step,                           igraph_bool_t directed);

Function to create a network based on some vertex categories. Thisfunction creates a citation network: in each step a single vertexandedges_per_step citing edges are added. Nodes withdifferent categories may have different probabilities to getcited, as given by thepref vector.

Note that this function might generate networks with multiple edgesifedges_per_step is greater than one. You might want to calligraph_simplify() on the result to remove multiple edges.

Arguments: 

graph:

Pointer to an uninitialized graph object.

nodes:

The number of vertices in the network.

types:

Numeric vector giving the categories of the vertices, so it should containnodes non-negative integer numbers. Types are numbered from zero.

pref:

The attractivity of the different vertex categories in a vector. Its length should be the maximum element intypes plus one (types are numbered from zero).

edges_per_step:

Integer constant, the number of edges to add in each time step.

directed:

Boolean constant, whether to create a directed network.

Returns: 

Error code.

See also: 

igraph_citing_cited_type_game() for a bit more generalgame.

Time complexity: O((|V|+|E|)log|V|), |V| and |E| are number ofvertices and edges, respectively.

2.25. igraph_citing_cited_type_game — Simulates a citation network based on vertex types.

igraph_error_t igraph_citing_cited_type_game(igraph_t *graph, igraph_integer_t nodes,                                  const igraph_vector_int_t *types,                                  const igraph_matrix_t *pref,                                  igraph_integer_t edges_per_step,                                  igraph_bool_t directed);

This game is similar toigraph_cited_type_game() but here thecategory of the citing vertex is also considered.

An evolving citation network is modeled here, a single vertex anditsedges_per_step citation are added in each time step. Theodds the a given vertex is cited by the new vertex depends on thecategory of both the citing and the cited vertex and is given inthepref matrix. The categories of the citing vertex correspondto the rows, the categories of the cited vertex to the columns ofthis matrix. I.e. the element in rowi and columnj gives theprobability that aj vertex is cited, if the category of theciting vertex isi.

Note that this function might generate networks with multiple edgesifedges_per_step is greater than one. You might want to calligraph_simplify() on the result to remove multiple edges.

Arguments: 

graph:

Pointer to an uninitialized graph object.

nodes:

The number of vertices in the network.

types:

A numeric vector of lengthnodes, containing the categories of the vertices. The categories are numbered from zero.

pref:

The preference matrix, a square matrix is required, both the number of rows and columns should be the maximum element intypes plus one (types are numbered from zero).

edges_per_step:

Integer constant, the number of edges to add in each time step.

directed:

Boolean constant, whether to create a directed network.

Returns: 

Error code.

Time complexity: O((|V|+|E|)log|V|), |V| and |E| are number ofvertices and edges, respectively.

2.26. igraph_sbm_game — Sample from a stochastic block model.

igraph_error_t igraph_sbm_game(igraph_t *graph, igraph_integer_t n,                    const igraph_matrix_t *pref_matrix,                    const igraph_vector_int_t *block_sizes,                    igraph_bool_t directed, igraph_bool_t loops);

This function samples graphs from a stochastic blockmodel by (doing the equivalent of) Bernoullitrials for each potential edge with the probabilitiesgiven by the Bernoulli rate matrix,pref_matrix.See Faust, K., & Wasserman, S. (1992a). Blockmodels:Interpretation and evaluation. Social Networks, 14, 5-–61.

The order of the vertex IDs in the generated graph corresponds totheblock_sizes argument.

Arguments: 

graph:

The output graph. This should be a pointer to an uninitialized graph.

n:

Number of vertices.

pref_matrix:

The matrix giving the Bernoulli rates. This is a KxK matrix, where K is the number of groups. The probability of creating an edge between vertices from groups i and j is given by element (i,j).

block_sizes:

An integer vector giving the number of vertices in each group.

directed:

Boolean, whether to create a directed graph. If this argument is false, thenpref_matrix must be symmetric.

loops:

Boolean, whether to create self-loops.

Returns: 

Error code.

Time complexity: O(|V|+|E|+K^2), where |V| is the number ofvertices, |E| is the number of edges, and K is the number ofgroups.

See also: 

igraph_erdos_renyi_game_gnp() for a simple Bernoulli graph.

2.27. igraph_hsbm_game — Hierarchical stochastic block model.

igraph_error_t igraph_hsbm_game(igraph_t *graph, igraph_integer_t n,                     igraph_integer_t m, const igraph_vector_t *rho,                     const igraph_matrix_t *C, igraph_real_t p);

The function generates a random graph according to the hierarchicalstochastic block model.

Arguments: 

graph:

The generated graph is stored here.

n:

The number of vertices in the graph.

m:

The number of vertices per block. n/m must be integer.

rho:

The fraction of vertices per cluster, within a block. Must sum up to 1, and rho * m must be integer for all elements of rho.

C:

A square, symmetric numeric matrix, the Bernoulli rates for the clusters within a block. Its size must mach the size of therho vector.

p:

The Bernoulli rate of connections between vertices in different blocks.

Returns: 

Error code.

See also: 

igraph_sbm_game() for the classic stochastic block model,igraph_hsbm_list_game() for a more general version.

2.28. igraph_hsbm_list_game — Hierarchical stochastic block model, more general version.

igraph_error_t igraph_hsbm_list_game(igraph_t *graph, igraph_integer_t n,                          const igraph_vector_int_t *mlist,                          const igraph_vector_list_t *rholist,                          const igraph_matrix_list_t *Clist,                          igraph_real_t p);

The function generates a random graph according to the hierarchicalstochastic block model.

Arguments: 

graph:

The generated graph is stored here.

n:

The number of vertices in the graph.

mlist:

An integer vector of block sizes.

rholist:

A list of rho vectors (igraph_vector_t objects), one for each block.

Clist:

A list of square matrices (igraph_matrix_t objects), one for each block, specifying the Bernoulli rates of connections within the block.

p:

The Bernoulli rate of connections between vertices in different blocks.

Returns: 

Error code.

See also: 

igraph_sbm_game() for the classic stochastic block model,igraph_hsbm_game() for a simpler general version.

2.29. igraph_dot_product_game — Generates a random dot product graph.

igraph_error_t igraph_dot_product_game(igraph_t *graph, const igraph_matrix_t *vecs,                            igraph_bool_t directed);

In this model, each vertex is represented by a latentposition vector. Probability of an edge between two vertices are givenby the dot product of their latent position vectors.

See also Christine Leigh Myers Nickel: Random dot product graphs, amodel for social networks. Dissertation, Johns Hopkins University,Maryland, USA, 2006.

Arguments: 

graph:

The output graph is stored here.

vecs:

A matrix in which each latent position vector is a column. The dot product of the latent position vectors should be in the [0,1] interval, otherwise a warning is given. For negative dot products, no edges are added; dot products that are larger than one always add an edge.

directed:

Should the generated graph be directed?

Returns: 

Error code.

Time complexity: O(n*n*m), where n is the number of vertices,and m is the length of the latent vectors.

See also: 

2.30. igraph_tree_game — Generates a random tree with the given number of nodes.

igraph_error_t igraph_tree_game(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed, igraph_random_tree_t method);

This function samples uniformly from the set of labelled trees,i.e. it generates each labelled tree with the same probability.

Note that forn=0, the null graph is returned,which is not considered to be a tree byigraph_is_tree().

Arguments: 

graph:

Pointer to an uninitialized graph object.

n:

The number of nodes in the tree.

directed:

Whether to create a directed tree. The edges are oriented away from the root.

method:

The algorithm to use to generate the tree. Possible values:

IGRAPH_RANDOM_TREE_PRUFER

This algorithm samples Prüfer sequences uniformly, then converts them to trees. Directed trees are not currently supported.

IGRAPH_RANDOM_LERW

This algorithm effectively performs a loop-erased random walk on the complete graph to uniformly sample its spanning trees (Wilson's algorithm).

Returns: 

Error code:IGRAPH_ENOMEM: there is not enough memory to perform the operation.IGRAPH_EINVAL: invalid tree size

See also: 

2.31. igraph_correlated_game — Generates a random graph correlated to an existing graph.

igraph_error_t igraph_correlated_game(const igraph_t *old_graph, igraph_t *new_graph,                           igraph_real_t corr, igraph_real_t p,                           const igraph_vector_int_t *permutation);

Sample a new graph by perturbing the adjacency matrix of agiven simple graph and shuffling its vertices.

Arguments: 

old_graph:

The original graph, it must be simple.

new_graph:

The new graph will be stored here.

corr:

A value in the unit interval [0,1], the target Pearson correlation between the adjacency matrices of the original and the generated graph (the adjacency matrix being used as a vector).

p:

The probability of an edge between two vertices. It must in the open (0,1) interval. Typically, the density ofold_graph.

permutation:

A permutation to apply to the vertices of the generated graph. It can also be a null pointer, in which case the vertices will not be permuted.

Returns: 

Error code

See also: 

igraph_correlated_pair_game() for generating a pairof correlated random graphs in one go.

2.32. igraph_correlated_pair_game — Generates pairs of correlated random graphs.

igraph_error_t igraph_correlated_pair_game(igraph_t *graph1, igraph_t *graph2,                                igraph_integer_t n, igraph_real_t corr, igraph_real_t p,                                igraph_bool_t directed,                                const igraph_vector_int_t *permutation);

Sample two random graphs, with given correlation.

Arguments: 

graph1:

The first graph will be stored here.

graph2:

The second graph will be stored here.

n:

The number of vertices in both graphs.

corr:

A scalar in the unit interval, the target Pearson correlation between the adjacency matrices of the original the generated graph (the adjacency matrix being used as a vector).

p:

A numeric scalar, the probability of an edge between two vertices, it must in the open (0,1) interval.

directed:

Whether to generate directed graphs.

permutation:

A permutation to apply to the vertices of the second graph. It can also be a null pointer, in which case the vertices will not be permuted.

Returns: 

Error code

See also: 

igraph_correlated_game() for generating a correlated pairto a given graph.

2.33. igraph_simple_interconnected_islands_game — Generates a random graph made of several interconnected islands, each island being a random graph.

igraph_error_t igraph_simple_interconnected_islands_game(        igraph_t *graph,        igraph_integer_t islands_n,        igraph_integer_t islands_size,        igraph_real_t islands_pin,        igraph_integer_t n_inter);

All islands are of the same size. Within an island, each edge is generatedwith the same probability. A fixed number of additional edges are thengenerated for each unordered pair of islands to connect them. The generatedgraph is guaranteed to be simple.

Arguments: 

graph:

Pointer to an uninitialized graph object.

islands_n:

The number of islands in the graph.

islands_size:

The size of islands in the graph.

islands_pin:

The probability to create each possible edge within islands.

n_inter:

The number of edges to create between two islands. It may be larger thanislands_size squared, but in this case it is assumed to beislands_size squared.

Returns: 

Error code:IGRAPH_EINVAL: invalid parameterIGRAPH_ENOMEM: there is not enough memory for the operation.

Time complexity: O(|V|+|E|), thenumber of vertices plus the number of edges in the graph.

3. Deprecated functions

3.1. igraph_erdos_renyi_game — Generates a random (Erdős-Rényi) graph.

igraph_error_t igraph_erdos_renyi_game(igraph_t *graph, igraph_erdos_renyi_t type,                            igraph_integer_t n, igraph_real_t p_or_m,                            igraph_bool_t directed, igraph_bool_t loops);

This function is deprecated; useigraph_erdos_renyi_game_gnm() origraph_erdos_renyi_game_gnp() instead.

Arguments: 

graph:

Pointer to an uninitialized graph object.

type:

The type of the random graph, possible values:

IGRAPH_ERDOS_RENYI_GNM

G(n,m) graph, m edges are selected uniformly randomly in a graph with n vertices.

IGRAPH_ERDOS_RENYI_GNP

G(n,p) graph, every possible edge is included in the graph with probability p.

n:

The number of vertices in the graph.

p_or_m:

This is the p parameter for G(n,p) graphs and the m parameter for G(n,m) graphs.

directed:

Whether to generate a directed graph.

loops:

Whether to generate loops (self) edges.

Returns: 

Error code:IGRAPH_EINVAL: invalidtype,n,p orm parameter.IGRAPH_ENOMEM: there is not enough memory for the operation.

Time complexity: O(|V|+|E|), thenumber of vertices plus the number of edges in the graph.

See also: 

3.2. igraph_lattice — Arbitrary dimensional square lattices (deprecated).

igraph_error_t igraph_lattice(igraph_t *graph, const igraph_vector_int_t *dimvector,                   igraph_integer_t nei, igraph_bool_t directed, igraph_bool_t mutual,                   igraph_bool_t circular);

Warning

Deprecated since version 0.10.0. Please do not use this function in newcode; useigraph_square_lattice()instead.

3.3. igraph_tree — Creates a k-ary tree in which almost all vertices have k children (deprecated alias).

igraph_error_t igraph_tree(igraph_t *graph, igraph_integer_t n, igraph_integer_t children,                igraph_tree_mode_t type);

Warning

Deprecated since version 0.10.0. Please do not use this function in newcode; useigraph_kary_tree()instead.

← Chapter 8. Random numbersChapter 10. Games on graphs →

© 2003 – 2025 The igraph core team. • Code licensed under GNU GPL 2 or later, documentation underGNU FDL.


[8]ページ先頭

©2009-2025 Movatter.jp