Source code for graph_tool.generation.named

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_tool -- a general graph manipulation python module
#
# Copyright (C) 2006-2026 Tiago de Paula Peixoto <tiago@skewed.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.s

"""Named graphs and deterministic graph families (see named_graph())."""

import math

import numpy

from .. import Graph
from ..dl_import import dl_import
dl_import("from . import libgraph_tool_generation")

__all__ = ["named_graph"]

# Construction helpers
# ====================

_orients = {"undirected": 0, "out": 0, "in": 1, "mutual": 2}

def _gen(name, *params, seq=(), directed=False, orient=0):
    """Graph generated by the C++ construction ``name`` with the integer
    parameters ``params`` and the integer sequence ``seq``; the edges are as
    given (``orient=0``), reversed (``1``), or in both directions (``2``)."""
    N, es = libgraph_tool_generation.named_graph_edges(
        name, numpy.asarray(params, dtype="int64").reshape(-1),
        numpy.asarray(seq, dtype="int64").reshape(-1), orient)
    g = Graph(directed=directed)
    if N > 0:
        g.add_vertex(N)
    es = es.reshape(-1, 2)
    if len(es) > 0:
        g.add_edge_list(es, parallel=False)
    return g

def _orient(name, *params, directed=False, mutual=False):
    """Edges from the first to the second endpoint if ``directed``, in both
    directions if also ``mutual``."""
    return _gen(name, *params, directed=directed,
                orient=2 if directed and mutual else 0)

def _mode(name, *params, mode="undirected"):
    """Edges for the modes "undirected", "out" (as given), "in" (reversed) and
    "mutual" (both directions)."""
    if mode not in _orients:
        raise ValueError(f"invalid mode: {mode!r}; must be one of "
                         "'undirected', 'out', 'in' or 'mutual'")
    return _gen(name, *params, directed=mode != "undirected",
                orient=_orients[mode])

def _int(x, name, lo=0):
    if int(x) != x or x < lo:
        raise ValueError(f"{name} must be an integer >= {lo}, not {x!r}")
    return int(x)

def _is_prime(p):
    return p >= 2 and all(p % q != 0 for q in range(2, math.isqrt(p) + 1))

# Triad types in the M-A-N notation of Holland and Leinhardt.
_triads = ["003", "012", "102", "021D", "021U", "021C", "111D", "111U",
           "030T", "030C", "201", "120D", "120U", "120C", "210", "300"]

# Families
# ========

_registry = {}

def _named(*names):
    def wrap(f):
        for name in names:
            _registry[name] = f
        return f
    return wrap

def _complete(N, self_loops=False, directed=False):
    from . import complete_graph
    return complete_graph(N, self_loops=self_loops, directed=directed)

def _circular(N, k=1, self_loops=False, directed=False):
    from . import circular_graph
    return circular_graph(N, k=k, self_loops=self_loops, directed=directed)

def _lattice(shape, periodic=False):
    from . import lattice
    return lattice(shape, periodic=periodic)

_registry["complete"] = _complete
_registry["circular"] = _circular
_registry["lattice"] = _lattice

@_named("empty")
def _empty(N, directed=False):
    g = Graph(directed=directed)
    g.add_vertex(_int(N, "N"))
    return g

@_named("path")
def _path(N, directed=False, mutual=False):
    return _orient("path", _int(N, "N"), directed=directed, mutual=mutual)

@_named("cycle")
def _cycle(N, directed=False, mutual=False):
    return _orient("cycle", _int(N, "N", 3), directed=directed, mutual=mutual)

@_named("star")
def _star(N, mode="undirected"):
    return _mode("star", _int(N, "N", 1), mode=mode)

@_named("wheel")
def _wheel(N):
    return _gen("wheel", _int(N, "N", 4))

@_named("circulant")
def _circulant(N, offsets):
    return _gen("circulant", _int(N, "N", 1),
                seq=numpy.atleast_1d(numpy.asarray(offsets, dtype="int64")))

@_named("transitive_tournament")
def _transitive_tournament(N):
    return _gen("transitive_tournament", _int(N, "N"), directed=True)

@_named("complete_bipartite")
def _complete_bipartite(N1, N2, mode="undirected"):
    return _mode("complete_bipartite", _int(N1, "N1"), _int(N2, "N2"),
                 mode=mode)

@_named("complete_multipartite")
def _complete_multipartite(*sizes):
    return _gen("complete_multipartite",
                seq=[_int(s, "part size") for s in sizes])

@_named("turan")
def _turan(N, r):
    N = _int(N, "N")
    r = _int(r, "r", 1)
    return _complete_multipartite(*([N // r + 1] * (N % r) +
                                    [N // r] * (r - N % r)))

@_named("ladder")
def _ladder(n):
    return _gen("ladder", _int(n, "n", 1))

@_named("circular_ladder")
def _circular_ladder(n):
    return _generalized_petersen(n, 1)

@_named("moebius_ladder")
def _moebius_ladder(n):
    return _gen("moebius_ladder", _int(n, "n", 2))

@_named("barbell")
def _barbell(m1, m2):
    return _gen("barbell", _int(m1, "m1", 2), _int(m2, "m2"))

@_named("lollipop")
def _lollipop(m, n):
    return _gen("lollipop", _int(m, "m", 2), _int(n, "n"))

@_named("tadpole")
def _tadpole(m, n):
    return _gen("tadpole", _int(m, "m", 3), _int(n, "n"))

@_named("tree")
def _tree(N, k=2, mode="undirected"):
    return _mode("tree", _int(N, "N"), _int(k, "k", 1), mode=mode)

@_named("balanced_tree")
def _balanced_tree(r, h, mode="undirected"):
    return _mode("balanced_tree", _int(r, "r", 1), _int(h, "h"), mode=mode)

@_named("symmetric_tree")
def _symmetric_tree(branches, mode="undirected"):
    branches = [_int(b, "branches", 1) for b in branches]
    if mode not in _orients:
        raise ValueError(f"invalid mode: {mode!r}; must be one of "
                         "'undirected', 'out', 'in' or 'mutual'")
    return _gen("symmetric_tree", seq=branches,
                directed=mode != "undirected", orient=_orients[mode])

@_named("regular_tree")
def _regular_tree(h, k, mode="undirected"):
    return _mode("regular_tree", _int(h, "h"), _int(k, "k", 1), mode=mode)

@_named("extended_chordal_ring")
def _extended_chordal_ring(N, W, directed=False):
    N = _int(N, "N", 3)
    W = numpy.atleast_2d(numpy.asarray(W, dtype="int64"))
    if W.ndim != 2 or W.shape[1] == 0 or N % W.shape[1] != 0:
        raise ValueError("W must be a matrix whose number of columns " +
                         "divides N")
    return _gen("extended_chordal_ring", N, W.shape[1], seq=W,
                directed=directed)

@_named("prefix_tree")
def _prefix_tree(paths, mode="undirected"):
    if mode not in _orients:
        raise ValueError(f"invalid mode: {mode!r}; must be one of "
                         "'undirected', 'out', 'in' or 'mutual'")
    # the symbols are mapped to integers in the order of their first
    # occurrence
    symbols = {}
    seq = []
    for path in paths:
        path = list(path)
        seq.append(len(path))
        for x in path:
            seq.append(symbols.setdefault(x, len(symbols)))
    N, es, label, end = libgraph_tool_generation.prefix_tree(
        numpy.asarray(seq, dtype="int64"))
    es = es.reshape(-1, 2)
    if _orients[mode] == 1:
        es = es[:, ::-1]
    elif _orients[mode] == 2:
        es = numpy.concatenate((es, es[:, ::-1]))
    g = Graph(directed=mode != "undirected")
    g.add_vertex(N)
    g.add_edge_list(es, parallel=False)
    inv = list(symbols.keys())
    g.vp.label = g.new_vp("object", vals=[None] + [inv[x] for x in label[1:]])
    g.vp.count = g.new_vp("int", vals=end)
    return g

@_named("binomial_tree")
def _binomial_tree(n, mode="undirected"):
    return _mode("binomial_tree", _int(n, "n"), mode=mode)

@_named("dorogovtsev_goltsev_mendes")
def _dgm(n):
    return _gen("dorogovtsev_goltsev_mendes", _int(n, "n"))

@_named("hypercube")
def _hypercube(n, directed=False):
    return _gen("hypercube", _int(n, "n"), directed=directed)

@_named("folded_cube")
def _folded_cube(n):
    return _gen("folded_cube", _int(n, "n", 2))

@_named("hamming")
def _hamming(d, q):
    return _gen("hamming", _int(d, "d"), _int(q, "q", 1))

@_named("kneser")
def _kneser(n, k):
    n = _int(n, "n", 1)
    k = _int(k, "k", 1)
    if k > n:
        raise ValueError(f"k must be <= n, not {k} > {n}")
    return _gen("kneser", n, k)

@_named("johnson")
def _johnson(n, k):
    n = _int(n, "n", 1)
    k = _int(k, "k", 1)
    if k > n:
        raise ValueError(f"k must be <= n, not {k} > {n}")
    return _gen("johnson", n, k)

@_named("generalized_petersen")
def _generalized_petersen(n, k):
    n = _int(n, "n", 3)
    k = _int(k, "k", 1)
    if k > (n - 1) // 2:
        raise ValueError(f"k must satisfy 1 <= k <= (n-1)/2, not k = {k} " +
                         f"for n = {n}")
    return _gen("generalized_petersen", n, k)

@_named("lcf")
def _lcf(N, shifts, repeats=1):
    return _gen("lcf", _int(N, "N", 3), _int(repeats, "repeats"),
                seq=numpy.asarray(shifts, dtype="int64").ravel())

@_named("triangular_lattice")
def _triangular_lattice(m, n, periodic=False):
    m = _int(m, "m")
    n = _int(n, "n")
    if periodic and m > 0 and n > 0 and (n < 5 or m < 3):
        raise ValueError("a periodic triangular lattice requires m > 2 and " +
                         f"n > 4, not m = {m}, n = {n}")
    return _gen("triangular_lattice", m, n, bool(periodic))

@_named("hexagonal_lattice")
def _hexagonal_lattice(m, n, periodic=False):
    m = _int(m, "m")
    n = _int(n, "n")
    if periodic and m > 0 and n > 0 and (n % 2 == 1 or m < 2 or n < 2):
        raise ValueError("a periodic hexagonal lattice requires m > 1 and " +
                         f"an even n > 1, not m = {m}, n = {n}")
    return _gen("hexagonal_lattice", m, n, bool(periodic))

@_named("margulis_gabber_galil")
def _margulis_gabber_galil(n):
    return _gen("margulis_gabber_galil", _int(n, "n", 1))

@_named("chordal_cycle")
def _chordal_cycle(p):
    p = _int(p, "p", 2)
    if not _is_prime(p):
        raise ValueError(f"p must be a prime number, not {p}")
    return _gen("chordal_cycle", p)

@_named("paley")
def _paley(p):
    p = _int(p, "p", 2)
    if not _is_prime(p) or p == 2:
        raise ValueError(f"p must be an odd prime number, not {p}")
    return _gen("paley", p, directed=p % 4 == 3)

@_named("hkn_harary")
def _hkn_harary(k, n):
    k = _int(k, "k", 1)
    return _gen("hkn_harary", k, _int(n, "n", k + 1))

@_named("hnm_harary")
def _hnm_harary(n, m):
    n = _int(n, "n", 1)
    m = _int(m, "m", n - 1)
    if m > n * (n - 1) // 2:
        raise ValueError(f"m must be <= n(n-1)/2, not {m}")
    return _gen("hnm_harary", n, m)

@_named("mycielski")
def _mycielski(n):
    return _gen("mycielski", _int(n, "n", 1))

@_named("sudoku")
def _sudoku(n=3):
    return _gen("sudoku", _int(n, "n"))

@_named("triad")
def _triad(name):
    if name not in _triads:
        raise ValueError(f"invalid triad name: {name!r}; must be one of " +
                         ", ".join(_triads))
    return _gen("triad_" + name, directed=True)

@_named("caveman")
def _caveman(l, k):
    return _gen("caveman", _int(l, "l"), _int(k, "k", 1))

@_named("connected_caveman")
def _connected_caveman(l, k):
    return _gen("connected_caveman", _int(l, "l", 1), _int(k, "k", 2))

@_named("ring_of_cliques")
def _ring_of_cliques(n, k):
    return _gen("ring_of_cliques", _int(n, "n", 2), _int(k, "k", 2))

@_named("windmill")
def _windmill(n, k):
    return _gen("windmill", _int(n, "n", 2), _int(k, "k", 2))

@_named("de_bruijn")
def _de_bruijn(m, n):
    return _gen("de_bruijn", _int(m, "m"), _int(n, "n"), directed=True)

@_named("kautz")
def _kautz(m, n):
    m = _int(m, "m")
    n = _int(n, "n")
    if m == 0:
        g = Graph(directed=True)
        g.add_vertex(1 if n == 0 else 0)
        return g
    if n == 0:
        return _complete(m + 1, directed=True)
    return _gen("kautz", m, n, directed=True)

# Fixed graphs

def _fixed(name):
    return lambda: _gen(name)

def _member(f, *params):
    return lambda: f(*params)

for _name in ["bull", "diamond", "house", "house_x", "tetrahedral",
              "icosahedral", "truncated_tetrahedron", "truncated_cube",
              "shrikhande", "hoffman_singleton", "coxeter", "folkman",
              "herschel", "chvatal", "robertson", "meredith", "tutte",
              "smallest_cyclic_group", "beineke", "krackhardt_kite",
              "sedgewick_maze"]:
    _registry[_name] = _fixed(_name)

for _name, (_f, _params) in {"octahedral": (_turan, (6, 3)),
                             "cubical": (_hypercube, (3,)),
                             "dodecahedral": (_generalized_petersen, (10, 2)),
                             "petersen": (_generalized_petersen, (5, 2)),
                             "desargues": (_generalized_petersen, (10, 3)),
                             "moebius_kantor": (_generalized_petersen, (8, 3)),
                             "durer": (_generalized_petersen, (6, 2)),
                             "nauru": (_generalized_petersen, (12, 5)),
                             "heawood": (_lcf, (14, [5, -5], 7)),
                             "franklin": (_lcf, (12, [5, -5], 6)),
                             "frucht": (_lcf, (12, [-5, -2, -4, 2, 5, -2, 2,
                                                    5, -2, -5, 4, 2], 1)),
                             "pappus": (_lcf, (18, [5, 7, -7, 7, -7, -5], 3)),
                             "mcgee": (_lcf, (24, [12, 7, -7], 8)),
                             "tutte_coxeter": (_lcf, (30, [-13, -9, 7, -7, 9,
                                                           13], 5)),
                             "grotzsch": (_mycielski, (4,)),
                             "clebsch": (_folded_cube, (5,))}.items():
    _registry[_name] = _member(_f, *_params)

[docs] def named_graph(name, *params, **kwargs): r"""Return a named graph, or a member of a deterministic family of graphs. Parameters ---------- name : ``str`` Name of the graph or family, as given in the table below. Upper and lower case, hyphens, spaces, and underscores are treated as equal. *params : Parameters of the family, in the order given in the table below. **kwargs : Optional parameters of the family, as given in the table below. Returns ------- g : :class:`~graph_tool.Graph` The generated graph. See Also -------- complete_graph: Complete graph circular_graph: Circular graph lattice: Square lattice graph_tool.collection.data: Empirical networks Notes ----- The supported names are the following, where the optional parameters are shown with their default values, and :math:`N` is always the number of vertices. .. csv-table:: :header: Name | Parameters | Description :widths: 3, 3, 8 :delim: | ``"empty"`` | ``N, directed=False`` | Graph with :math:`N` vertices and no edges. ``"complete"`` | ``N, self_loops=False, directed=False`` | `Complete graph <https://en.wikipedia.org/wiki/Complete_graph>`_ :math:`K_N` (see :func:`~graph_tool.generation.complete_graph`). ``"transitive_tournament"`` | ``N`` | Directed graph with edges :math:`i\to j` for all :math:`j < i`, i.e. the full citation graph, which is the transitive `tournament <https://en.wikipedia.org/wiki/Tournament_(graph_theory)>`_. ``"complete_bipartite"`` | ``N1, N2, mode="undirected"`` | `Complete bipartite graph <https://en.wikipedia.org/wiki/Complete_bipartite_graph>`_ :math:`K_{N_1,N_2}`, with the parts :math:`\{0,\dots,N_1-1\}` and :math:`\{N_1,\dots,N_1+N_2-1\}`. ``"complete_multipartite"`` | ``N1, N2, ...`` | Complete `multipartite graph <https://en.wikipedia.org/wiki/Multipartite_graph>`_ with parts of sizes :math:`N_1, N_2, \dots`, whose vertices are numbered consecutively part by part, and every pair of vertices of different parts is adjacent. ``"turan"`` | ``N, r`` | `Turán graph <https://en.wikipedia.org/wiki/Tur%C3%A1n_graph>`_, the complete :math:`r`-partite graph with :math:`N \bmod r` parts of size :math:`\lfloor N/r\rfloor + 1` followed by :math:`r - (N \bmod r)` parts of size :math:`\lfloor N/r\rfloor`. ``"path"`` | ``N, directed=False, mutual=False`` | `Path graph <https://en.wikipedia.org/wiki/Path_graph>`_ :math:`P_N`, with the edges :math:`(i, i+1)` for :math:`i = 0,\dots,N-2`. ``"cycle"`` | ``N, directed=False, mutual=False`` | `Cycle graph <https://en.wikipedia.org/wiki/Cycle_graph>`_ :math:`C_N`, with the edges :math:`(i, i+1 \bmod N)` for :math:`i = 0,\dots,N-1`. ``"circular"`` | ``N, k=1, self_loops=False, directed=False`` | Cycle with every vertex adjacent to its :math:`k` nearest neighbors on each side (see :func:`~graph_tool.generation.circular_graph`). ``"circulant"`` | ``N, offsets`` | `Circulant graph <https://en.wikipedia.org/wiki/Circulant_graph>`_, with vertex :math:`i` adjacent to :math:`i \pm o \bmod N` for every offset :math:`o`, without parallel edges, and with a self-loop at every vertex if an offset is a multiple of :math:`N`. ``"extended_chordal_ring"`` | ``N, W, directed=False`` | Cycle :math:`C_N` with the chords :math:`(i, i + W_{j,i \bmod p} \bmod N)` for every row :math:`j` of the matrix :math:`W` with :math:`p` columns, where :math:`p` divides :math:`N` (with parallel edges or self-loops if the chords coincide). ``"star"`` | ``N, mode="undirected"`` | `Star <https://en.wikipedia.org/wiki/Star_(graph_theory)>`_ with a center (vertex 0) and :math:`N-1` leaves. ``"wheel"`` | ``N`` | `Wheel <https://en.wikipedia.org/wiki/Wheel_graph>`_, the cycle :math:`1, 2, \dots, N-1` with all its vertices adjacent to the center, vertex 0. ``"ladder"`` | ``n`` | `Ladder <https://en.wikipedia.org/wiki/Ladder_graph>`_, the cartesian product :math:`P_n \times P_2`: the paths :math:`0,\dots,n-1` and :math:`n,\dots,2n-1`, with the rungs :math:`(i, i+n)`. ``"circular_ladder"`` | ``n`` | Circular ladder or `prism graph <https://en.wikipedia.org/wiki/Prism_graph>`_ :math:`C_n \times P_2`, i.e. :math:`GP(n,1)`. ``"moebius_ladder"`` | ``n`` | `Möbius ladder <https://en.wikipedia.org/wiki/M%C3%B6bius_ladder>`_, the cycle :math:`C_{2n}` with the edges :math:`(i, i + n)` for :math:`i = 0,\dots,n-1` (without parallel edges, so that it is :math:`K_4` for :math:`n=2`). ``"barbell"`` | ``m1, m2`` | Two complete graphs :math:`K_{m_1}`, on the vertices :math:`0,\dots,m_1-1` and :math:`m_1+m_2,\dots,2m_1+m_2-1`, joined by the path :math:`m_1-1, m_1, \dots, m_1+m_2`, whose :math:`m_2` inner vertices belong to no clique. ``"lollipop"`` | ``m, n`` | `Lollipop graph <https://en.wikipedia.org/wiki/Lollipop_graph>`_: complete graph :math:`K_m` on the vertices :math:`0,\dots,m-1`, joined to a path of :math:`n` further vertices, as the path :math:`m-1, m, \dots, m+n-1`. ``"tadpole"`` | ``m, n`` | `Tadpole graph <https://en.wikipedia.org/wiki/Tadpole_graph>`_: cycle :math:`C_m` on the vertices :math:`0,\dots,m-1`, joined to a path of :math:`n` further vertices, as the path :math:`m-1, m, \dots, m+n-1`. ``"tree"`` | ``N, k=2, mode="undirected"`` | Tree in which the parent of vertex :math:`i \ge 1` is :math:`\lfloor (i-1)/k\rfloor`, so that every vertex but the last ones has :math:`k` children, numbered in breadth-first order. ``"balanced_tree"`` | ``r, h, mode="undirected"`` | Complete :math:`r`-ary tree (`m-ary tree <https://en.wikipedia.org/wiki/M-ary_tree>`_) of height :math:`h`, i.e. the ``"tree"`` with :math:`N = \sum_{l=0}^hr^l` and :math:`k = r`. ``"binomial_tree"`` | ``n, mode="undirected"`` | Binomial tree of order :math:`n`, with :math:`2^n` vertices, where the parent of vertex :math:`i \ge 1` is :math:`i` with its lowest nonzero binary digit set to zero. ``"symmetric_tree"`` | ``branches, mode="undirected"`` | Tree in which every vertex at distance :math:`d` from the root has ``branches[d]`` children, numbered in breadth-first order. ``"regular_tree"`` | ``h, k, mode="undirected"`` | Tree of height :math:`h` in which every vertex but the leaves has degree :math:`k`, i.e. a finite `Bethe lattice <https://en.wikipedia.org/wiki/Bethe_lattice>`_: the ``"symmetric_tree"`` with ``branches=[k, k-1, ..., k-1]`` (of length :math:`h`). ``"prefix_tree"`` | ``paths, mode="undirected"`` | Prefix tree (`trie <https://en.wikipedia.org/wiki/Trie>`_) of the sequences in ``paths``, with the root 0, and a vertex for every distinct prefix, adjacent to the vertex of the prefix one symbol shorter. The vertex property maps ``label`` and ``count`` hold the last symbol of the prefix and the number of sequences equal to it. ``"hypercube"`` | ``n, directed=False`` | `Hypercube graph <https://en.wikipedia.org/wiki/Hypercube_graph>`_ :math:`Q_n`, with :math:`2^n` vertices, where :math:`u` and :math:`v` are adjacent if their binary representations differ in a single digit. ``"folded_cube"`` | ``n`` | `Folded cube graph <https://en.wikipedia.org/wiki/Folded_cube_graph>`_, :math:`Q_{n-1}` with the edges :math:`(v, v \oplus (2^{n-1}-1))` between antipodal vertices, where :math:`\oplus` is the bitwise exclusive or (without parallel edges, so that it is :math:`K_2` for :math:`n=2`). ``"hamming"`` | ``d, q`` | `Hamming graph <https://en.wikipedia.org/wiki/Hamming_graph>`_ :math:`H(d,q)`, the words of length :math:`d` over :math:`q` letters, adjacent if they differ in one letter, where the vertex :math:`v` is the word of the digits of :math:`v` in base :math:`q`. ``"kneser"`` | ``n, k`` | `Kneser graph <https://en.wikipedia.org/wiki/Kneser_graph>`_ :math:`K(n,k)`, the :math:`k`-subsets of :math:`n` elements, adjacent if they are disjoint. ``"johnson"`` | ``n, k`` | `Johnson graph <https://en.wikipedia.org/wiki/Johnson_graph>`_ :math:`J(n,k)`, the :math:`k`-subsets of :math:`n` elements, adjacent if their intersection has :math:`k-1` elements. ``"generalized_petersen"`` | ``n, k`` | `Generalized Petersen graph <https://en.wikipedia.org/wiki/Generalized_Petersen_graph>`_ :math:`GP(n,k)`, with :math:`1 \le k \le (n-1)/2`: the outer cycle :math:`(i, i+1 \bmod n)`, the spokes :math:`(i, n+i)`, and the inner edges :math:`(n+i, n + (i+k \bmod n))`, for :math:`i = 0,\dots,n-1`. ``"lcf"`` | ``N, shifts, repeats=1`` | Cubic Hamiltonian graph in `LCF notation <https://en.wikipedia.org/wiki/LCF_notation>`_ :math:`[\text{shifts}]^\text{repeats}` [frucht-canonical-1977]_: the cycle :math:`C_N` with the chords :math:`(i \bmod N, i + s_{i \bmod L} \bmod N)` for :math:`i = 0,\dots,L\,\text{repeats}-1`, where :math:`s` are the :math:`L` shifts, without parallel edges and self-loops. ``"lattice"`` | ``shape, periodic=False`` | Square lattice of any dimension (see :func:`~graph_tool.generation.lattice`). ``"triangular_lattice"`` | ``m, n, periodic=False`` | Triangular lattice with :math:`m` rows and :math:`n` columns of triangles. ``"hexagonal_lattice"`` | ``m, n, periodic=False`` | Hexagonal lattice with :math:`m` rows and :math:`n` columns of hexagons. ``"dorogovtsev_goltsev_mendes"`` | ``n`` | Pseudofractal scale-free graph of generation :math:`n` [dorogovtsev-pseudofractal-2002]_: starting from the edge :math:`(0, 1)`, every generation adds, for every edge, a new vertex adjacent to both of its endpoints. ``"mycielski"`` | ``n`` | Mycielski graph of order :math:`n`, the :math:`(n-2)`-th `Mycielskian <https://en.wikipedia.org/wiki/Mycielskian>`_ of :math:`K_2` (see :func:`~graph_tool.generation.mycielskian`), or :math:`K_1` for :math:`n=1` [mycielski-coloriage-1955]_. ``"hkn_harary"`` | ``k, n`` | Harary graph :math:`H_{k,n}`, the :math:`k`-connected graph with :math:`n` vertices and the fewest edges [harary-maximum-1962]_: the path :math:`P_n` for :math:`k=1`, and otherwise the circulant graph with the offsets :math:`1,\dots,\lfloor k/2\rfloor`, plus, for odd :math:`k`, the edges :math:`(i, i + \lfloor n/2\rfloor \bmod n)` for :math:`i = 0,\dots,\lceil n/2\rceil - 1`. ``"hnm_harary"`` | ``n, m`` | Harary graph with :math:`n` vertices and :math:`m` edges and the largest connectivity [harary-maximum-1962]_. With :math:`d = \lfloor 2m/n\rfloor` and :math:`o = \lfloor d/2\rfloor`, it is the circulant graph with the offsets :math:`1,\dots,o`, plus, if :math:`n` or :math:`d` is even, the edges :math:`(i, i + n/2)` for :math:`i < n/2` if :math:`d` is odd, and :math:`(i, i + o + 1 \bmod n)` for :math:`i < \lfloor (2m \bmod n)/2\rfloor`, and otherwise the edges :math:`(i, i + \lfloor n/2\rfloor \bmod n)` for :math:`i < m - no`, all without parallel edges. ``"margulis_gabber_galil"`` | ``n`` | Margulis–Gabber–Galil 8-regular `expander <https://en.wikipedia.org/wiki/Expander_graph>`__ multigraph on :math:`\mathbb{Z}_n^2` [gabber-explicit-1981]_, with the four edges from every :math:`(x, y)` to :math:`(x + 2y, y)`, :math:`(x + 2y + 1, y)`, :math:`(x, y + 2x)`, and :math:`(x, y + 2x + 1)`, modulo :math:`n`. ``"chordal_cycle"`` | ``p`` | 3-regular `expander <https://en.wikipedia.org/wiki/Expander_graph>`__ on :math:`\mathbb{Z}_p`, for a prime :math:`p`, with :math:`x` adjacent to :math:`x\pm 1` and :math:`x^{-1}` (with :math:`0^{-1} = 0`), as the multigraph with the three edges :math:`(x, x-1)`, :math:`(x, x+1)`, and :math:`(x, x^{-1})` for every :math:`x`, so that every edge between distinct vertices appears twice, and the vertices with :math:`x = x^{-1}` have a self-loop. ``"paley"`` | ``p`` | `Paley graph <https://en.wikipedia.org/wiki/Paley_graph>`_ of an odd prime :math:`p`, with :math:`x\to y` if :math:`y-x` is a nonzero square modulo :math:`p`, undirected if :math:`p \equiv 1 \pmod 4`, and a tournament otherwise. ``"de_bruijn"`` | ``m, n`` | Directed `de Bruijn graph <https://en.wikipedia.org/wiki/De_Bruijn_graph>`_ of the words of length :math:`n` over :math:`m` letters, where the vertex :math:`v` is the word of its digits in base :math:`m`, with the edges :math:`v \to (mv + a) \bmod m^n` for every letter :math:`a`, i.e. from every word to its shifts by one letter, including self-loops. ``"kautz"`` | ``m, n`` | Directed `Kautz graph <https://en.wikipedia.org/wiki/Kautz_graph>`_ of the words :math:`s_0s_1\cdots s_n` of length :math:`n+1` over :math:`m+1` letters, without equal consecutive letters, with the edges :math:`s_0s_1\cdots s_n \to s_1\cdots s_na` for every letter :math:`a \ne s_n`. ``"sudoku"`` | ``n=3`` | `Sudoku graph <https://en.wikipedia.org/wiki/Sudoku_graph>`_ of an :math:`n^2\times n^2` grid, with cells adjacent if they share a row, column, or :math:`n\times n` box, where the cell in row :math:`r` and column :math:`c` has the index :math:`rn^2 + c`. ``"caveman"`` | ``l, k`` | :math:`l` disjoint complete graphs :math:`K_k`, the :math:`c`-th on the vertices :math:`ck,\dots,ck+k-1` [watts-networks-1999]_. ``"connected_caveman"`` | ``l, k`` | Caveman graph in which the edge :math:`(ck, ck+1)` of every complete graph :math:`c` is replaced by :math:`(ck, ck - 1 \bmod lk)`, which connects it to the last vertex of the previous one [watts-networks-1999]_. ``"ring_of_cliques"`` | ``n, k`` | :math:`n` complete graphs :math:`K_k`, the :math:`c`-th on the vertices :math:`ck,\dots,ck+k-1`, joined in a ring by the edges :math:`(ck + 1, (c+1 \bmod n)k)`. ``"windmill"`` | ``n, k`` | `Windmill graph <https://en.wikipedia.org/wiki/Windmill_graph>`_: :math:`n` complete graphs :math:`K_k` sharing the single vertex 0, the :math:`a`-th on the vertices 0 and :math:`a(k-1)+1,\dots,a(k-1)+k-1`. ``"triad"`` | ``name`` | Directed graph of 3 vertices with the given triad type, from ``"003"`` to ``"300"`` [holland-method-1970]_. ``"tetrahedral"`` | | Graph of the tetrahedron, :math:`K_4`. ``"cubical"`` | | Graph of the cube, :math:`Q_3`. ``"octahedral"`` | | Graph of the octahedron, :math:`K_{2,2,2}`. ``"dodecahedral"`` | | Graph of the dodecahedron, :math:`GP(10,2)`. ``"icosahedral"`` | | Graph of the icosahedron. ``"truncated_tetrahedron"`` | | Graph of the `truncated tetrahedron <https://en.wikipedia.org/wiki/Truncated_tetrahedron>`_. ``"truncated_cube"`` | | Graph of the `truncated cube <https://en.wikipedia.org/wiki/Truncated_cube>`_. ``"petersen"`` | | `Petersen graph <https://en.wikipedia.org/wiki/Petersen_graph>`_, :math:`GP(5,2)`, and the Kneser graph :math:`K(5,2)`. ``"durer"`` | | `Dürer graph <https://en.wikipedia.org/wiki/D%C3%BCrer_graph>`_, :math:`GP(6,2)`. ``"moebius_kantor"`` | | `Möbius–Kantor graph <https://en.wikipedia.org/wiki/M%C3%B6bius%E2%80%93Kantor_graph>`_, :math:`GP(8,3)`. ``"desargues"`` | | `Desargues graph <https://en.wikipedia.org/wiki/Desargues_graph>`_, :math:`GP(10,3)`. ``"nauru"`` | | `Nauru graph <https://en.wikipedia.org/wiki/Nauru_graph>`_, :math:`GP(12,5)`. ``"franklin"`` | | `Franklin graph <https://en.wikipedia.org/wiki/Franklin_graph>`_, :math:`[5,-5]^6`. ``"frucht"`` | | `Frucht graph <https://en.wikipedia.org/wiki/Frucht_graph>`_, :math:`[-5,-2,-4,2,5,-2,2,5,-2,-5,4,2]`. ``"heawood"`` | | `Heawood graph <https://en.wikipedia.org/wiki/Heawood_graph>`_, the (3,6)-cage, :math:`[5,-5]^7`. ``"pappus"`` | | `Pappus graph <https://en.wikipedia.org/wiki/Pappus_graph>`_, :math:`[5,7,-7,7,-7,-5]^3`. ``"mcgee"`` | | `McGee graph <https://en.wikipedia.org/wiki/McGee_graph>`_, the (3,7)-cage, :math:`[12,7,-7]^8`. ``"tutte_coxeter"`` | | `Tutte–Coxeter graph <https://en.wikipedia.org/wiki/Tutte%E2%80%93Coxeter_graph>`_ or Levi graph, the (3,8)-cage, :math:`[-13,-9,7,-7,9,13]^5`. ``"coxeter"`` | | `Coxeter graph <https://en.wikipedia.org/wiki/Coxeter_graph>`_, :math:`K(7,3)` without the seven lines of a Fano plane [brouwer-distance-regular-1989]_. ``"tutte"`` | | `Tutte graph <https://en.wikipedia.org/wiki/Tutte_graph>`_, three Tutte fragments joined to a vertex and in a ring [tutte-hamiltonian-1946]_. ``"robertson"`` | | `Robertson graph <https://en.wikipedia.org/wiki/Robertson_graph>`_, the (4,5)-cage [robertson-smallest-1964]_. ``"hoffman_singleton"`` | | `Hoffman–Singleton graph <https://en.wikipedia.org/wiki/Hoffman%E2%80%93Singleton_graph>`_, the (7,5)-cage [hoffman-moore-1960]_. ``"shrikhande"`` | | `Shrikhande graph <https://en.wikipedia.org/wiki/Shrikhande_graph>`_, the Cayley graph of :math:`\mathbb{Z}_4^2` with generators :math:`\pm(1,0)`, :math:`\pm(0,1)`, :math:`\pm(1,1)`. ``"clebsch"`` | | `Clebsch graph <https://en.wikipedia.org/wiki/Clebsch_graph>`_, the folded cube of dimension 5. ``"chvatal"`` | | `Chvátal graph <https://en.wikipedia.org/wiki/Chv%C3%A1tal_graph>`_, the smallest triangle-free 4-regular 4-chromatic graph [chvatal-smallest-1970]_. ``"grotzsch"`` | | `Grötzsch graph <https://en.wikipedia.org/wiki/Gr%C3%B6tzsch_graph>`_, the Mycielski graph of order 4. ``"folkman"`` | | `Folkman graph <https://en.wikipedia.org/wiki/Folkman_graph>`_, the smallest semisymmetric graph [folkman-regular-1967]_. ``"meredith"`` | | `Meredith graph <https://en.wikipedia.org/wiki/Meredith_graph>`_, 4-regular and 4-connected, but not Hamiltonian [meredith-regular-1973]_. ``"herschel"`` | | `Herschel graph <https://en.wikipedia.org/wiki/Herschel_graph>`_, the graph of the enneahedron, the smallest non-Hamiltonian polyhedral graph. ``"beineke"`` | | The nine minimal graphs that are not line graphs, as connected components [beineke-characterizations-1970]_. ``"smallest_cyclic_group"`` | | The smallest graph whose automorphism group is cyclic, of order 3, with 9 vertices and 15 edges. ``"bull"`` | | `Bull graph <https://en.wikipedia.org/wiki/Bull_graph>`_, a triangle with two pendant vertices. ``"diamond"`` | | `Diamond graph <https://en.wikipedia.org/wiki/Diamond_graph>`_, :math:`K_4` without an edge. ``"house"`` | | House graph, a square with a triangle on top. ``"house_x"`` | | House graph with both diagonals of the square. ``"krackhardt_kite"`` | | `Krackhardt's kite <https://en.wikipedia.org/wiki/Krackhardt_kite_graph>`_ social network [krackhardt-assessing-1990]_. ``"sedgewick_maze"`` | | Small maze with a cycle, from Sedgewick's *Algorithms in C*. The parameters ``directed`` and ``mutual`` give directed graphs with edges in the direction of increasing indices along the path or cycle, and in both directions if ``mutual=True``. The parameter ``mode`` takes the values ``"undirected"``, ``"out"`` (edges from the center, the root, or the first part), ``"in"`` (edges in the opposite direction) and ``"mutual"`` (edges in both directions). With ``directed=True``, the edges of ``"hypercube"`` point from lower to higher vertex indices. The graphs are constructed in C++ from their definitions, and the families are generated in time :math:`O(V + E)`, apart from a factor :math:`O(k)` per edge for the Kneser and Johnson graphs, and a factor :math:`O(\log E)` for the families whose parallel edges are removed by sorting the edge list. The numbering of the vertices follows the definitions, e.g. the vertex of a Kneser or Johnson graph with index :math:`i` is the subset of rank :math:`i` in colexicographic order, and the vertex :math:`(x, y)` of a Margulis–Gabber–Galil graph has index :math:`xn + y`. The multigraphs ``"margulis_gabber_galil"`` and ``"chordal_cycle"`` contain parallel edges and self-loops, as their definitions require. Examples -------- .. testsetup:: named_graph gt.seed_rng(42) np.random.seed(42) .. doctest:: named_graph >>> g = gt.named_graph("petersen") >>> print(g) <Graph object, undirected, with 10 vertices and 15 edges, at 0x...> >>> g = gt.named_graph("generalized_petersen", 7, 2) >>> print(g.num_vertices(), g.num_edges()) 14 21 >>> g = gt.named_graph("kneser", 7, 3) >>> print(g.num_vertices(), g.num_edges()) 35 70 >>> g = gt.named_graph("tree", 15, 2, mode="out") >>> print(g.vertex(0).out_degree(), g.vertex(14).in_degree()) 2 1 >>> g = gt.named_graph("hoffman_singleton") >>> pos = gt.sfdp_layout(g) >>> gt.graph_draw(g, pos=pos, output="hoffman_singleton.pdf") <...> .. testcleanup:: named_graph conv_png("hoffman_singleton.pdf") .. figure:: hoffman_singleton.png :align: center :width: 40% The Hoffman–Singleton graph. Several named graphs are drawn together as follows, as the components of a single graph: .. doctest:: named_graph >>> g = gt.Graph(directed=False) >>> for name in ["petersen", "heawood", "moebius_kantor", "grotzsch"]: ... g = gt.graph_union(g, gt.named_graph(name), vmap=None) >>> gt.graph_draw(g, pos=gt.sfdp_layout(g), ... output="named_graph-gallery.pdf") <...> .. testcleanup:: named_graph conv_png("named_graph-gallery.pdf") .. figure:: named_graph-gallery.png :align: center :width: 60% The Petersen, Heawood, Möbius–Kantor, and Grötzsch graphs, drawn as the components of a single graph. References ---------- .. [frucht-canonical-1977] R. Frucht, "A canonical representation of trivalent Hamiltonian graphs", J. Graph Theory 1, 45-60 (1977). :DOI:`10.1002/jgt.3190010111` .. [dorogovtsev-pseudofractal-2002] S. N. Dorogovtsev, A. V. Goltsev, and J. F. F. Mendes, "Pseudofractal scale-free web", Phys. Rev. E 65, 066122 (2002). :DOI:`10.1103/PhysRevE.65.066122` .. [mycielski-coloriage-1955] J. Mycielski, "Sur le coloriage des graphs", Colloq. Math. 3, 161-162 (1955). :DOI:`10.4064/cm-3-2-161-162` .. [harary-maximum-1962] F. Harary, "The maximum connectivity of a graph", Proc. Natl. Acad. Sci. USA 48, 1142-1146 (1962). :DOI:`10.1073/pnas.48.7.1142` .. [gabber-explicit-1981] O. Gabber and Z. Galil, "Explicit constructions of linear-sized superconcentrators", J. Comput. Syst. Sci. 22, 407-420 (1981). :DOI:`10.1016/0022-0000(81)90040-4` .. [watts-networks-1999] D. J. Watts, "Networks, dynamics, and the small-world phenomenon", Am. J. Sociol. 105, 493-527 (1999). :DOI:`10.1086/210318` .. [holland-method-1970] P. W. Holland and S. Leinhardt, "A method for detecting structure in sociometric data", Am. J. Sociol. 76, 492-513 (1970). :DOI:`10.1086/224954` .. [brouwer-distance-regular-1989] A. E. Brouwer, A. M. Cohen, and A. Neumaier, "Distance-Regular Graphs", Springer (1989). :DOI:`10.1007/978-3-642-74341-2` .. [tutte-hamiltonian-1946] W. T. Tutte, "On Hamiltonian circuits", J. London Math. Soc. s1-21, 98-101 (1946). :DOI:`10.1112/jlms/s1-21.2.98` .. [robertson-smallest-1964] N. Robertson, "The smallest graph of girth 5 and valency 4", Bull. Amer. Math. Soc. 70, 824-825 (1964). :DOI:`10.1090/S0002-9904-1964-11250-7` .. [hoffman-moore-1960] A. J. Hoffman and R. R. Singleton, "On Moore graphs with diameters 2 and 3", IBM J. Res. Dev. 4, 497-504 (1960). :DOI:`10.1147/rd.45.0497` .. [chvatal-smallest-1970] V. Chvátal, "The smallest triangle-free 4-chromatic 4-regular graph", J. Combin. Theory 9, 93-94 (1970). :DOI:`10.1016/S0021-9800(70)80057-6` .. [folkman-regular-1967] J. Folkman, "Regular line-symmetric graphs", J. Combin. Theory 3, 215-232 (1967). :DOI:`10.1016/S0021-9800(67)80069-3` .. [meredith-regular-1973] G. H. J. Meredith, "Regular n-valent n-connected nonHamiltonian non-n-edge-colorable graphs", J. Combin. Theory B 14, 55-60 (1973). :DOI:`10.1016/S0095-8956(73)80006-1` .. [beineke-characterizations-1970] L. W. Beineke, "Characterizations of derived graphs", J. Combin. Theory 9, 129-135 (1970). :DOI:`10.1016/S0021-9800(70)80019-9` .. [krackhardt-assessing-1990] D. Krackhardt, "Assessing the political landscape: Structure, cognition, and power in organizations", Admin. Sci. Q. 35, 342-369 (1990). :DOI:`10.2307/2393394` .. [wiki-gallery] https://en.wikipedia.org/wiki/Gallery_of_named_graphs """ key = str(name).lower().replace("-", "_").replace(" ", "_") f = _registry.get(key, None) if f is None: raise ValueError(f"unknown named graph: {name!r}") return f(*params, **kwargs)