#! /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/>.
"""
``graph_tool.structure``
------------------------
This module contains various functions that assess the graph structure.
Shortest paths
++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
shortest_distance
shortest_path
count_shortest_paths
all_shortest_paths
all_predecessors
random_shortest_path
k_shortest_paths
widest_distance
widest_path
resource_constrained_path
find_negative_cycle
voronoi_cells
ego_graph
spanner
Distances, eccentricity, and centers
++++++++++++++++++++++++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
pseudo_diameter
eccentricity
diameter
radius
harmonic_diameter
center
periphery
barycenter
average_shortest_path_length
Distance-based indices and small-world measures
+++++++++++++++++++++++++++++++++++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
global_efficiency
local_efficiency
wiener_index
hyper_wiener_index
schultz_index
gutman_index
s_metric
small_world_sigma
small_world_omega
Paths, walks, and cycles
++++++++++++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
all_paths
all_circuits
random_walk
loop_erased_random_walk
eulerian_path
eulerize
find_cycle
cycle_basis
girth
chordless_cycles
cycle_ratio
Components and connectivity
+++++++++++++++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
label_components
label_largest_component
extract_largest_component
label_out_component
count_reachable
make_connected
label_biconnected_components
find_bridges
local_bridges
chain_decomposition
is_semiconnected
is_kl_connected
kl_connected_subgraph
vertex_percolation
edge_percolation
Core decompositions
+++++++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
kcore_decomposition
kcore_subgraph
truss_decomposition
onion_decomposition
Cuts and expansion
++++++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
cut_size
volume
conductance
normalized_cut_size
edge_expansion
mixing_expansion
vertex_expansion
boundary_expansion
vertex_boundary
edge_boundary
Spanning trees
++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
minimum_spanning_tree
random_spanning_tree
minimum_spanning_arborescence
all_spanning_arborescences
common_spanning_trees
Trees
+++++
.. autosummary::
:nosignatures:
:toctree: autosummary
prufer_sequence
unfold_tree
tree_broadcast_center
tree_broadcast_time
Directed graphs
+++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
is_DAG
edge_reciprocity
topological_sort
all_topological_sorts
topological_generations
transitive_closure
transitive_reduction
feedback_arc_set
feedback_vertex_set
dag_longest_path
dag_to_branching
antichains
lowest_common_ancestors
dominator_tree
dominance_frontiers
is_aperiodic
flow_hierarchy
cd_index
is_tournament
tournament_hamiltonian_path
d-separation and graphical models
+++++++++++++++++++++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
is_d_separator
find_minimal_d_separator
is_minimal_d_separator
junction_tree
Chordal graphs and treewidth
++++++++++++++++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
is_chordal
chordal_completion
chordal_cliques
find_induced_nodes
treewidth
Cliques
+++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
maximal_cliques
all_cliques
largest_cliques
maximum_weight_clique
clique_number
approx_maximum_clique
large_clique_size
clique_removal
ramsey_r2
graphlet_decomposition
Matchings, independent sets, and covers
+++++++++++++++++++++++++++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
maximum_cardinality_matching
maximum_weight_matching
approx_minimum_maximal_matching
k_factor
maximal_extendability
maximal_independent_vertex_set
independence_number
largest_independent_vertex_sets
maximal_independent_vertex_sets
approx_minimum_vertex_cover
bipartite_vertex_cover
minimum_edge_cover
approx_minimum_edge_dominating_set
approx_minimum_dominating_set
connected_dominating_set
Coloring
++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
sequential_vertex_coloring
dsatur_vertex_coloring
equitable_vertex_coloring
edge_coloring
Combinatorial optimization
++++++++++++++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
tsp_tour
steiner_tree
approx_maximum_cut
densest_subgraph
vertex_ordering
bandwidth
Graph comparison and isomorphism
++++++++++++++++++++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
similarity
isomorphism
subgraph_isomorphism
mark_subgraph
maximum_common_subgraphs
graph_edit_distance
bliss_automorphism_group
nauty_automorphism_group
weisfeiler_lehman_hash
Vertex similarity and link prediction
+++++++++++++++++++++++++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
vertex_similarity
simrank
panther_similarity
community_link_prediction
common_neighbor_centrality
Planarity
+++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
is_planar
planar_faces
is_straight_line_drawing
Graph classes
+++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
is_bipartite
is_perfect
find_asteroidal_triple
is_threshold_graph
find_threshold_graph
is_distance_regular
is_strongly_regular
is_regular_expander
intersection_array
global_parameters
Graph polynomials
+++++++++++++++++
.. autosummary::
:nosignatures:
:toctree: autosummary
tutte_polynomial
chromatic_polynomial
"""
from .. dl_import import dl_import
dl_import("from . import libgraph_tool_structure")
from .. import _check_prop, _check_props, Vector_int32_t, Vector_size_t, \
_check_prop_writable, \
_check_prop_scalar, _check_prop_vector, Graph, VertexPropertyMap, \
PropertyMap, GraphView, libcore, _get_rng, perfect_prop_hash, \
_limit_args, _parallel
from .. generation import label_self_loops, label_parallel_edges, \
remove_parallel_edges, remove_self_loops, _simple_edges, moral_graph
import numpy, collections.abc, math, warnings, inspect, re, textwrap
__all__ = ["isomorphism", "subgraph_isomorphism", "mark_subgraph",
"bliss_automorphism_group", "nauty_automorphism_group",
"weisfeiler_lehman_hash", "maximal_cliques",
"maximum_cardinality_matching", "maximum_weight_matching",
"maximal_independent_vertex_set", "minimum_spanning_tree",
"minimum_spanning_arborescence", "random_spanning_tree",
"dominator_tree", "topological_sort", "transitive_closure",
"tsp_tour", "sequential_vertex_coloring", "label_components",
"label_largest_component", "extract_largest_component",
"label_biconnected_components", "label_out_component",
"vertex_percolation", "edge_percolation", "kcore_decomposition",
"truss_decomposition", "shortest_distance", "shortest_path",
"random_shortest_path", "random_walk", "count_shortest_paths",
"all_shortest_paths", "all_predecessors", "k_shortest_paths",
"all_paths", "all_circuits", "cycle_basis", "girth",
"pseudo_diameter", "eccentricity", "diameter", "radius",
"is_bipartite", "is_DAG", "is_planar", "similarity", "vertex_similarity", "edge_reciprocity", "simrank",
"transitive_reduction", "feedback_arc_set", "feedback_vertex_set",
"vertex_ordering", "bandwidth", "onion_decomposition",
"edge_coloring", "cycle_ratio", "steiner_tree",
"approx_minimum_dominating_set", "approx_minimum_vertex_cover",
"approx_maximum_cut", "treewidth",
"global_efficiency", "local_efficiency", "eulerian_path",
"average_shortest_path_length", "wiener_index", "harmonic_diameter",
"center", "periphery", "barycenter", "widest_distance",
"widest_path", "resource_constrained_path", "voronoi_cells",
"ego_graph", "find_cycle", "chordless_cycles",
"maximum_common_subgraphs", "kcore_subgraph", "clique_number",
"planar_faces", "graph_edit_distance", "tutte_polynomial",
"chromatic_polynomial", "is_chordal", "chordal_completion",
"chordal_cliques", "find_induced_nodes", "is_perfect",
"find_asteroidal_triple", "is_d_separator",
"find_minimal_d_separator", "is_minimal_d_separator", "is_tournament", "tournament_hamiltonian_path",
"loop_erased_random_walk", "common_spanning_trees",
"is_straight_line_drawing", "make_connected", "all_cliques",
"largest_cliques", "maximum_weight_clique", "independence_number",
"largest_independent_vertex_sets",
"maximal_independent_vertex_sets", "dsatur_vertex_coloring",
"equitable_vertex_coloring",
"minimum_edge_cover", "k_factor", "topological_generations",
"dag_longest_path", "all_topological_sorts", "antichains",
"is_aperiodic", "dominance_frontiers", "lowest_common_ancestors",
"prufer_sequence", "unfold_tree", "junction_tree",
"tree_broadcast_center", "tree_broadcast_time", "flow_hierarchy",
"hyper_wiener_index", "schultz_index", "gutman_index", "s_metric",
"intersection_array", "is_distance_regular", "global_parameters",
"is_strongly_regular", "is_regular_expander",
"find_negative_cycle", "is_semiconnected",
"eulerize", "find_bridges", "local_bridges", "chain_decomposition",
"spanner",
"small_world_sigma", "small_world_omega",
"community_link_prediction", "common_neighbor_centrality",
"panther_similarity", "bipartite_vertex_cover",
"maximal_extendability", "cd_index", "ramsey_r2",
"clique_removal", "approx_maximum_clique", "large_clique_size",
"approx_minimum_maximal_matching",
"approx_minimum_edge_dominating_set",
"densest_subgraph", "connected_dominating_set",
"all_spanning_arborescences", "cut_size", "volume", "conductance",
"normalized_cut_size", "edge_expansion", "mixing_expansion",
"vertex_expansion", "boundary_expansion", "vertex_boundary",
"edge_boundary", "is_threshold_graph", "find_threshold_graph",
"is_kl_connected", "kl_connected_subgraph", "count_reachable",
"dag_to_branching", "graphlet_decomposition"]
[docs]
@_parallel
@_check_props(graph="g1", v=("label1",), e=("eweight1",))
@_check_props(graph="g2", v=("label2",), e=("eweight2",))
def similarity(g1, g2, eweight1=None, eweight2=None, label1=None, label2=None,
norm=True, p=1., distance=False, asymmetric=False):
r"""Return the Jaccard adjacency similarity between two graphs.
Parameters
----------
g1 : :class:`~graph_tool.Graph`
First graph to be compared.
g2 : :class:`~graph_tool.Graph`
Second graph to be compared.
eweight1 : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights for the first graph to be used in comparison.
eweight2 : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights for the second graph to be used in comparison.
label1 : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex labels for the first graph to be used in comparison. If not
supplied, the vertex indices are used.
label2 : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex labels for the second graph to be used in comparison. If not
supplied, the vertex indices are used.
norm : bool (optional, default: ``True``)
If ``True``, the returned value is normalized by the total number of
edges.
p : float (optional, default: ``1.``)
Exponent of the :math:`L^p` distance function.
distance : bool (optional, default: ``False``)
If ``True``, the complementary value is returned, i.e. the distance
between the two graphs.
asymmetric : bool (optional, default: ``False``)
If ``True``, the asymmetric similarity of ``g1`` to ``g2`` will be
computed.
Returns
-------
similarity : float
Adjacency similarity value.
See Also
--------
vertex_similarity: Similarity between pairs of vertices
isomorphism: Isomorphism test between two graphs
graph_edit_distance: Edit distance between two graphs
weisfeiler_lehman_hash: Hash of a graph that is invariant under isomorphism
Notes
-----
In its default parametrization, the Jaccard adjacency similarity is the sum
of equal non-zero entries in the adjacency matrices of both graphs, given a
vertex ordering determined by the vertex labels. In other words, it counts
the number of edges which have the same source and target labels in both
graphs.
If ``norm == True`` (the default) the value returned is the total fraction
of edges of both networks that match.
This function also allows for generalized similarities according to an
:math:`L^p` norm, for arbitrary exponent :math:`p`.
More specifically, the (unnormalized) adjacency similarity is defined as:
.. math::
S(\boldsymbol A_1, \boldsymbol A_2) = E - d(\boldsymbol A_1, \boldsymbol A_2)
where
.. math::
d(\boldsymbol A_1, \boldsymbol A_2) = \left(\sum_{i\le j} \left|A_{ij}^{(1)} - A_{ij}^{(2)}\right|^p\right)^{1/p}
is the corresponding distance between graphs, and :math:`E=(\sum_{i\le
j}|A_{ij}^{(1)}|^p + |A_{ij}^{(2)}|^p)^{1/p}`. Unless otherwise stated via
the parameter ``p``, the exponent used is :math:`p=1`. This definition holds
for undirected graphs, otherwise the sums go over all directed pairs. If
edge weights are provided, the weighted adjacency matrix is used.
If a multigraph is passed, the matrix entries :math:`A^{(1)}_{ij}` and
:math:`A^{(2)}_{ij}` correspond to the edge multiplicities between nodes
:math:`i` and :math:`j` in each graph.
If ``norm == True`` the value returned is :math:`S(\boldsymbol A_1,
\boldsymbol A_2) / E`, which lies in the interval :math:`[0,1]`.
If ``asymmetric == True``, the above is changed so that the comparison is
made only for entries in :math:`\boldsymbol A_1` that are larger than in :math:`\boldsymbol A_2`, i.e.
.. math::
d(\boldsymbol A_1, \boldsymbol A_2) = \left(\sum_{i\le j} \left|A_{ij}^{(1)} - A_{ij}^{(2)}\right|^p H(A_{ij}^{(1)} - A_{ij}^{(2)})\right)^{1/p},
where :math:`H(x) = \{1 \text{ if } x > 0; 0 \text{ otherwise}\}` is the
unit step function, and the total sum is changed accordingly to
:math:`E=\left(\sum_{i\le j}|A_{ij}^{(1)}|^p\right)^{1/p}`.
**Relation to set operations**
If the graph is unweighted, :math:`p=1`, and ``norm == False`` the
algorithm is equivalent to the following set comparisons:
1. If ``distance == True`` the returned value is equal to
.. math::
2 |\boldsymbol A_1 \cup \boldsymbol A_2|
where :math:`\boldsymbol A_1 \cup \boldsymbol A_2` is the union of the
edges in :math:`\boldsymbol A_1` and :math:`\boldsymbol A_2`.
2. If ``distance == False`` the returned value is equal to
.. math::
2 |\boldsymbol A_1 \cap \boldsymbol A_2|
where :math:`\boldsymbol A_1 \cap \boldsymbol A_2` is the intersection of
the edges in :math:`\boldsymbol A_1` and :math:`\boldsymbol A_2`.
3. If ``distance == True`` and ``asymmetric == True`` the returned value is
equal to
.. math::
|\boldsymbol A_1 \setminus \boldsymbol A_2|
where :math:`\boldsymbol A_1 \setminus \boldsymbol A_2` is the set of
edges in :math:`\boldsymbol A_1` that are not also in :math:`\boldsymbol
A_2`.
The algorithm runs with complexity :math:`O(E_1 + V_1 + E_2 + V_2)`.
@parallel@
(The above is applicable only if the vertex labels are integers bounded
by the sizes of the graphs.)
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> g = gt.random_graph(100, lambda: (3,3))
>>> u = g.copy()
>>> gt.similarity(u, g)
1.0
>>> gt.random_rewire(u)
190
>>> gt.similarity(u, g)
0.03
"""
if label1 is None:
label1 = g1.vertex_index
if label2 is None:
label2 = g2.vertex_index
_check_prop_scalar(label1, name="label1")
_check_prop_scalar(label2, name="label2")
if label1.value_type() != label2.value_type():
try:
label2 = label2.copy(label1.value_type())
except ValueError:
label1 = label1.copy(label2.value_type())
if eweight1 is None and eweight2 is None:
ew1 = ew2 = libcore.any()
else:
if eweight1 is None:
eweight1 = g1.new_ep(eweight2.value_type(), 1)
if eweight2 is None:
eweight2 = g2.new_ep(eweight1.value_type(), 1)
_check_prop_scalar(eweight1, name="eweight1")
_check_prop_scalar(eweight2, name="eweight2")
if eweight1.value_type() != eweight2.value_type():
try:
eweight2 = eweight2.copy(eweight1.value_type())
except ValueError:
eweight1 = eweight1.copy(eweight2.value_type())
ew1 = eweight1
ew2 = eweight2
def fast_labels(label, g):
# The fast version indexes an array with the labels, so they must be
# small non-negative integers.
if not label.is_writable():
return True
a = label.fa
if len(a) == 0:
return True
return (numpy.issubdtype(a.dtype, numpy.integer) and a.min() >= 0 and
a.max() <= g.num_vertices())
if not fast_labels(label1, g1) or not fast_labels(label2, g2):
s = libgraph_tool_structure.\
similarity(g1, g2,
ew1, ew2, label1,
label2, p, asymmetric)
else:
s = libgraph_tool_structure.\
similarity_fast(g1, g2,
ew1, ew2, label1,
label2, p, asymmetric)
if not g1.is_directed() or not g2.is_directed():
s /= 2
s **= 1./p
if eweight1 is None and eweight2 is None:
if asymmetric:
E = g1.num_edges()
else:
E = g1.num_edges() + g2.num_edges()
else:
if asymmetric:
E = float((abs(eweight1.fa)**p).sum()) ** (1./p)
else:
E = float((abs(eweight1.fa)**p).sum() +
(abs(eweight2.fa)**p).sum()) ** (1./p)
if not distance:
s = E - s
if norm:
return s / E if E > 0 else numpy.nan
return s
[docs]
@_parallel
@_limit_args({"sim_type": ["dice", "salton", "hub-promoted", "hub-suppressed",
"jaccard", "inv-log-weight", "resource-allocation",
"leicht-holme-newman", "common-neighbors",
"preferential-attachment"]})
@_check_props(v=("sim_map",), e=("eweight",))
def vertex_similarity(g, sim_type="jaccard", vertex_pairs=None, eweight=None,
sim_map=None):
r"""Return the similarity between pairs of vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
The graph to be used.
sim_type : ``str`` (optional, default: ``"jaccard"``)
Type of similarity to use. This must be one of ``"dice"``, ``"salton"``,
``"hub-promoted"``, ``"hub-suppressed"``, ``"jaccard"``,
``"inv-log-weight"``, ``"resource-allocation"``,
``"leicht-holme-newman"``, ``"common-neighbors"``, or
``"preferential-attachment"``.
vertex_pairs : iterable of pairs of integers (optional, default: ``None``)
Pairs of vertices to compute the similarity. If omitted, all pairs will
be considered.
eweight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights.
sim_map : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, and ``vertex_pairs is None``, the vertex similarities will
be stored in this vector-valued property. Otherwise, a new one will be
created.
Returns
-------
similarities : :class:`numpy.ndarray` or :class:`~graph_tool.VertexPropertyMap`
If ``vertex_pairs`` was supplied, this will be a :class:`numpy.ndarray`
with the corresponding similarities, otherwise it will be a
vector-valued vertex :class:`~graph_tool.VertexPropertyMap`, with the
similarities to all other vertices.
See Also
--------
simrank: SimRank similarity between pairs of vertices
panther_similarity: Vertices most similar to a given one
community_link_prediction: Community-aware link prediction scores
common_neighbor_centrality: Link prediction score with distances
similarity: Similarity between two graphs
Notes
-----
According to ``sim_type``, this function computes one of the following
similarities:
``sim_type == "dice"``
The Sørensen–Dice similarity [sorensen-dice]_ of vertices :math:`u` and
:math:`v` is defined as
.. math::
\frac{2|\Gamma(u)\cap\Gamma(v)|}{|\Gamma(u)|+|\Gamma(v)|},
where :math:`\Gamma(u)` is the set of neighbors of vertex :math:`u`.
``sim_type == "salton"``
The Salton (or cosine) similarity [salton]_ of vertices :math:`u` and
:math:`v` is defined as
.. math::
\frac{|\Gamma(u)\cap\Gamma(v)|}{\sqrt{|\Gamma(u)||\Gamma(v)|}},
where :math:`\Gamma(u)` is the set of neighbors of vertex :math:`u`.
``sim_type == "hub-promoted"``
The "hub promoted" similarity [ravasz_hierarchical_2002]_ of vertices
:math:`u` and :math:`v` is defined as
.. math::
\frac{|\Gamma(u)\cap\Gamma(v)|}{\max(|\Gamma(u)|,|\Gamma(v)|)},
where :math:`\Gamma(u)` is the set of neighbors of vertex :math:`u`.
``sim_type == "hub-suppressed"``
The "hub suppressed" similarity of vertices :math:`u` and
:math:`v` is defined as
.. math::
\frac{|\Gamma(u)\cap\Gamma(v)|}{\min(|\Gamma(u)|,|\Gamma(v)|)},
where :math:`\Gamma(u)` is the set of neighbors of vertex :math:`u`.
``sim_type == "jaccard"``
The Jaccard similarity [jaccard]_ of vertices :math:`u` and
:math:`v` is defined as
.. math::
\frac{|\Gamma(u)\cap\Gamma(v)|}{|\Gamma(u)\cup\Gamma(v)|},
where :math:`\Gamma(u)` is the set of neighbors of vertex :math:`u`.
``sim_type == "inv-log-weight"``
The inverse log weighted similarity [adamic-friends-2003]_ of vertices
:math:`u` and :math:`v` is defined as
.. math::
\sum_{w \in \Gamma(u)\cap\Gamma(v)}\frac{1}{\log |\Gamma(w)|},
where :math:`\Gamma(u)` is the set of neighbors of vertex :math:`u`.
``sim_type == "resource-allocation"``
The resource allocation similarity [zhou-predicting-2009]_ of vertices
:math:`u` and :math:`v` is defined as
.. math::
\sum_{w \in \Gamma(u)\cap\Gamma(v)}\frac{1}{|\Gamma(w)|},
where :math:`\Gamma(u)` is the set of neighbors of vertex :math:`u`.
``sim_type == "leicht-holme-newman"``
The Leicht-Holme-Newman similarity [leicht_vertex_2006]_ of vertices
:math:`u` and :math:`v` is defined as
.. math::
\frac{|\Gamma(u)\cap\Gamma(v)|}{|\Gamma(u)||\Gamma(v)|},
where :math:`\Gamma(u)` is the set of neighbors of vertex :math:`u`.
``sim_type == "common-neighbors"``
The number of common neighbors of vertices :math:`u` and :math:`v`,
.. math::
|\Gamma(u)\cap\Gamma(v)|.
``sim_type == "preferential-attachment"``
The preferential attachment score [liben-nowell-link-prediction-2007]_
of vertices :math:`u` and :math:`v`,
.. math::
|\Gamma(u)||\Gamma(v)|.
For directed graphs, only out-neighbors are considered in the above
algorithms (for "inv-log-weight", the in-degrees are used to compute the
weights). To use the in-neighbors instead, a :class:`~graph_tool.GraphView`
should be used to reverse the graph, e.g. ``vertex_similarity(GraphView(g,
reversed=True))``.
For weighted or multigraphs, in the above equations it is assumed the
following:
.. math::
|\Gamma(u)\cap\Gamma(v)| &= \sum_w \min(A_{wv}, A_{wu}),\\
|\Gamma(u)\cup\Gamma(v)| &= \sum_w \max(A_{wv}, A_{wu}),\\
|\Gamma(u)| &= \sum_w A_{wu},
where :math:`A_{wu}` is the weighted adjacency matrix.
See [liben-nowell-link-prediction-2007]_ for a review of the above.
The algorithm runs with complexity :math:`O(\left<k\right>N^2)` if
``vertex_pairs is None``, otherwise with :math:`O(\left<k\right>P)` where
:math:`P` is the length of ``vertex_pairs``.
@parallel@
Examples
--------
.. testcode::
:hide:
import matplotlib
>>> g = gt.collection.data["polbooks"]
>>> s = gt.vertex_similarity(g, "jaccard")
>>> color = g.new_vp("double")
>>> color.a = s[0].a
>>> gt.graph_draw(g, pos=g.vp.pos, vertex_text=g.vertex_index,
... vertex_color=color, vertex_fill_color=color,
... vcmap=matplotlib.cm.inferno,
... output="polbooks-jaccard.svg")
<...>
.. figure:: polbooks-jaccard.*
:align: center
Jaccard similarities to vertex ``0`` in a political books network.
References
----------
.. [sorensen-dice] https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
.. [salton] G. Salton, M. J. McGill, "Introduction to Modern Information
Retrieval", (McGraw-Hill, Auckland, 1983).
.. [ravasz_hierarchical_2002] Ravasz, E., Somera, A. L., Mongru, D. A.,
Oltvai, Z. N., & Barabási, A. L., "Hierarchical organization of
modularity in metabolic networks", Science, 297(5586), 1551-1555,
(2002). :doi:`10.1126/science.1073374`
.. [jaccard] https://en.wikipedia.org/wiki/Jaccard_index
.. [leicht_vertex_2006] E. A. Leicht, Petter Holme, and M. E. J. Newman,
"Vertex similarity in networks", Phys. Rev. E 73, 026120 (2006),
:doi:`10.1103/PhysRevE.73.026120`, :arxiv:`physics/0510143`
.. [adamic-friends-2003] Lada A. Adamic and Eytan Adar, "Friends and neighbors
on the Web", Social Networks Volume 25, Issue 3, Pages 211–230 (2003)
:doi:`10.1016/S0378-8733(03)00009-1`
.. [liben-nowell-link-prediction-2007] David Liben-Nowell and Jon Kleinberg,
"The link-prediction problem for social networks", Journal of the
American Society for Information Science and Technology, Volume 58, Issue
7, pages 1019–1031 (2007), :doi:`10.1002/asi.20591`
.. [zhou-predicting-2009] Zhou, Tao, Linyuan Lü, and Yi-Cheng Zhang,
"Predicting missing links via local information", The European Physical
Journal B 71, no. 4: 623-630 (2009), :doi:`10.1140/epjb/e2009-00335-8`,
:arxiv:`0901.0553`
"""
if vertex_pairs is None:
if sim_map is None:
s = g.new_vp("vector<double>")
else:
s = sim_map
if sim_type == "dice":
libgraph_tool_structure.dice_similarity(g,
s,
eweight)
elif sim_type == "salton":
libgraph_tool_structure.salton_similarity(g,
s,
eweight)
elif sim_type == "hub-promoted":
libgraph_tool_structure.hub_promoted_similarity(g,
s,
eweight)
elif sim_type == "hub-suppressed":
libgraph_tool_structure.hub_suppressed_similarity(g,
s,
eweight)
elif sim_type == "jaccard":
libgraph_tool_structure.jaccard_similarity(g,
s,
eweight)
elif sim_type == "inv-log-weight":
libgraph_tool_structure.inv_log_weight_similarity(g,
s,
eweight)
elif sim_type == "resource-allocation":
libgraph_tool_structure.r_allocation_similarity(g,
s,
eweight)
elif sim_type == "leicht-holme-newman":
libgraph_tool_structure.leicht_holme_newman_similarity(g,
s,
eweight)
elif sim_type in ["common-neighbors", "preferential-attachment"]:
libgraph_tool_structure.\
cn_pa_similarity(g, s, eweight,
0 if sim_type == "common-neighbors" else 1)
else:
raise ValueError("invalid similarity type: " + str(sim_type))
else:
vertex_pairs = numpy.asarray(vertex_pairs, dtype="int64")
s = numpy.zeros(vertex_pairs.shape[0], dtype="double")
if sim_type == "dice":
libgraph_tool_structure.dice_similarity_pairs(g,
vertex_pairs,
s, eweight)
elif sim_type == "salton":
libgraph_tool_structure.salton_similarity_pairs(g,
vertex_pairs,
s, eweight)
elif sim_type == "hub-promoted":
libgraph_tool_structure.hub_promoted_similarity_pairs(g,
vertex_pairs,
s, eweight)
elif sim_type == "hub-suppressed":
libgraph_tool_structure.hub_suppressed_similarity_pairs(g,
vertex_pairs,
s, eweight)
elif sim_type == "jaccard":
libgraph_tool_structure.jaccard_similarity_pairs(g,
vertex_pairs,
s, eweight)
elif sim_type == "inv-log-weight":
libgraph_tool_structure.\
inv_log_weight_similarity_pairs(g, vertex_pairs,
s, eweight)
elif sim_type == "resource-allocation":
libgraph_tool_structure.\
r_allocation_similarity_pairs(g, vertex_pairs,
s, eweight)
elif sim_type == "leicht-holme-newman":
libgraph_tool_structure.\
leicht_holme_newman_similarity_pairs(g, vertex_pairs,
s, eweight)
elif sim_type in ["common-neighbors", "preferential-attachment"]:
libgraph_tool_structure.\
cn_pa_similarity_pairs(g, vertex_pairs, s, eweight,
0 if sim_type == "common-neighbors"
else 1)
else:
raise ValueError("invalid similarity type: " + str(sim_type))
return s
def _has_parallel_edges(g):
"""Whether ``g`` has parallel edges between distinct vertices."""
p = label_parallel_edges(g, mark_only=True).fa
return bool(numpy.any(p & (label_self_loops(g, mark_only=True).fa == 0)))
[docs]
@_check_props(graph="g1", v=("vertex_inv1",))
@_check_props(graph="g2", v=("vertex_inv2",))
def isomorphism(g1, g2, vertex_inv1=None, vertex_inv2=None, isomap=False,
edge_label=None):
r"""Check whether two graphs are isomorphic.
Parameters
----------
g1 : :class:`~graph_tool.Graph`
First graph.
g2 : :class:`~graph_tool.Graph`
Second graph.
vertex_inv1 : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex invariant of the first graph. Only vertices with the same
invariants are considered in the isomorphism.
vertex_inv2 : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex invariant of the second graph. Only vertices with the same
invariants are considered in the isomorphism.
isomap : ``bool`` (optional, default: ``False``)
If ``True``, a :class:`~graph_tool.VertexPropertyMap` with the
isomorphism mapping is returned as well.
edge_label : pair of :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge labels of the first and second graph (in this order). If given,
only isomorphisms that map every edge to one with the same label are
considered.
Returns
-------
is_isomorphism : ``bool``
``True`` if both graphs are isomorphic, otherwise ``False``.
isomap : :class:`~graph_tool.VertexPropertyMap`
Isomorphism mapping corresponding to a property map belonging to the
first graph which maps its vertices to their corresponding vertices of
the second graph.
See Also
--------
subgraph_isomorphism: Embeddings of a graph as a subgraph of another
bliss_automorphism_group: Automorphism group with bliss
nauty_automorphism_group: Automorphism group with nauty or Traces
weisfeiler_lehman_hash: Hash of a graph that is invariant under isomorphism
Notes
-----
Without edge labels, the algorithm of [boost-isomorphism]_ is used, with
the number of self-loops of each vertex included in its invariant. This
algorithm does not take into account the multiplicities of the edges, so
that if either graph has parallel edges between distinct vertices, or if
edge labels are given, the isomorphism is searched instead with the VF2
algorithm of :func:`subgraph_isomorphism`, with the vertex invariants as
vertex labels, which maps every edge to a distinct edge, and takes into
account self-loops and parallel edges.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> g = gt.random_graph(100, lambda: (3,3))
>>> g2 = gt.Graph(g)
>>> gt.isomorphism(g, g2)
True
>>> g.add_edge(g.vertex(0), g.vertex(1))
<...>
>>> gt.isomorphism(g, g2)
False
With edge labels, the isomorphisms must preserve them:
>>> g = gt.circular_graph(4)
>>> g2 = gt.circular_graph(4)
>>> l1 = g.new_ep("int", vals=[0, 1, 0, 1])
>>> l2 = g2.new_ep("int", vals=[0, 0, 1, 1])
>>> gt.isomorphism(g, g2, edge_label=(l1, l2))
False
References
----------
.. [boost-isomorphism] http://www.boost.org/libs/graph/doc/isomorphism.html
"""
if (vertex_inv1 is None) != (vertex_inv2 is None):
raise ValueError("Either both or none of vertex_inv1 and vertex_inv2 "
"must be given.")
# The BGL algorithm ignores the multiplicities of the edges, and does not
# support edge labels, which are both handled by VF2 instead.
vf2 = (edge_label is not None or _has_parallel_edges(g1) or
_has_parallel_edges(g2))
if vf2 and g1.is_directed() != g2.is_directed():
return (False, g1.new_vp("int32_t", val=-1)) if isomap else False
if vertex_inv1 is None:
x1 = g1.get_total_degrees(g1.get_vertices())
x2 = g2.get_total_degrees(g2.get_vertices())
else:
# the values must be hashed together, so that equal values in both
# graphs get the same hash
h1, h2 = perfect_prop_hash([vertex_inv1, vertex_inv2])
x1 = h1.fa
x2 = h2.fa
# The self-loops are not considered by the BGL algorithm, and VF2 does
# not match those of undirected graphs, which appear twice among the
# out-edges of their vertex. They are therefore hidden from both
# algorithms, and the multiset of the labels of the self-loops of each
# vertex (i.e. their number, without labels) is included in the
# invariants instead.
if edge_label is not None:
el1, el2 = perfect_prop_hash(edge_label, htype="int64_t")
else:
el1 = el2 = None
def remove_loops(g, el):
l = label_self_loops(g, mark_only=True)
es = g.get_edges([l] + ([el] if el is not None else []))
es = es[es[:, 2] > 0]
loops = numpy.zeros((len(es), 2), dtype="int64")
loops[:, 0] = es[:, 0]
if el is not None:
loops[:, 1] = es[:, 3]
if len(es) > 0:
g = GraphView(g, efilt=1 - l.fa)
return g, loops
g1, l1 = remove_loops(g1, el1)
g2, l2 = remove_loops(g2, el2)
n1 = numpy.zeros(g1.num_vertices(True), dtype="int64")
n2 = numpy.zeros(g2.num_vertices(True), dtype="int64")
if len(l1) + len(l2) > 0:
# the rows (graph, vertex, label), sorted, and the sorted labels of
# each vertex as a row of a matrix, padded with -1, whose distinct
# rows identify the multisets
ls = numpy.concatenate((numpy.column_stack((numpy.zeros(len(l1)), l1)),
numpy.column_stack((numpy.ones(len(l2)), l2))))
ls = ls.astype("int64")
ls = ls[numpy.lexsort((ls[:, 2], ls[:, 1], ls[:, 0]))]
keys, start, idx, count = numpy.unique(ls[:, :2], axis=0,
return_index=True,
return_inverse=True,
return_counts=True)
idx = idx.ravel()
m = numpy.full((len(keys), count.max()), -1, dtype="int64")
m[idx, numpy.arange(len(ls)) - start[idx]] = ls[:, 2]
mid = numpy.unique(m, axis=0, return_inverse=True)[1].ravel() + 1
k1 = keys[:, 0] == 0
n1[keys[k1, 1]] = mid[k1]
n2[keys[~k1, 1]] = mid[~k1]
n1 = n1[g1.get_vertices()]
n2 = n2[g2.get_vertices()]
# map the pairs (invariant, self-loops) jointly to the range
# [0, inv_max)
x = numpy.concatenate((numpy.column_stack((x1, n1)),
numpy.column_stack((x2, n2))))
if len(x) > 0:
x = numpy.unique(x, axis=0, return_inverse=True)[1].ravel()
else:
x = numpy.zeros(0, dtype="int64")
vertex_inv1 = g1.new_vertex_property("int64_t")
vertex_inv2 = g2.new_vertex_property("int64_t")
vertex_inv1.fa = x[:len(x1)]
vertex_inv2.fa = x[len(x1):]
inv_max = x.max() + 1 if len(x) > 0 else 1
if vf2:
if g1.num_vertices() == 0 or g2.num_vertices() == 0:
iso = g1.num_vertices() == g2.num_vertices() and \
g1.num_edges() == g2.num_edges()
vm = g1.new_vp("int32_t")
else:
vms = subgraph_isomorphism(g1, g2, max_n=1,
vertex_label=(vertex_inv1,
vertex_inv2),
edge_label=edge_label,
subgraph=False)
iso = len(vms) > 0
vm = vms[0].copy("int32_t") if iso else g1.new_vp("int32_t")
return (iso, vm) if isomap else iso
imap = g1.new_vertex_property("int32_t")
iso = libgraph_tool_structure.\
check_isomorphism(g1, g2,
vertex_inv1,
vertex_inv2,
inv_max,
imap)
if isomap:
return iso, imap
else:
return iso
[docs]
def subgraph_isomorphism(sub, g, max_n=0, vertex_label=None, edge_label=None,
induced=False, subgraph=True, generator=False,
vertex_domains=None, edge_time=None, delta=0):
r"""Obtain all subgraph isomorphisms of `sub` in `g` (or at most `max_n` subgraphs, if `max_n > 0`).
Parameters
----------
sub : :class:`~graph_tool.Graph`
Subgraph for which to be searched.
g : :class:`~graph_tool.Graph`
Graph in which the search is performed.
max_n : int (optional, default: ``0``)
Maximum number of matches to find. If `max_n == 0`, all matches are
found.
vertex_label : pair of :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, this should be a pair of :class:`~graph_tool.VertexPropertyMap`
objects, belonging to ``sub`` and ``g`` (in this order), which specify
vertex labels which should match, in addition to the topological
isomorphism.
edge_label : pair of :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If provided, this should be a pair of :class:`~graph_tool.EdgePropertyMap`
objects, belonging to ``sub`` and ``g`` (in this order), which specify
edge labels which should match, in addition to the topological
isomorphism.
induced : bool (optional, default: ``False``)
If ``True``, only node-induced subgraphs are found.
subgraph : bool (optional, default: ``True``)
If ``False``, all non-subgraph isomorphisms between `sub` and `g` are
found.
generator : bool (optional, default: ``False``)
If ``True``, a generator will be returned, instead of a list. This is
useful if the number of isomorphisms is too large to store in memory. If
``generator == True``, the option ``max_n`` is ignored.
vertex_domains : list of iterables of ``int`` (optional, default: ``None``)
If given, for every vertex of ``sub`` (in index order), the vertices of
``g`` to which it may be mapped.
edge_time : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If given, the times of the edges of ``g``, and only the
time-respecting matches are returned (see below).
delta : ``float`` (optional, default: ``0``)
Largest time difference of the edges incident to a vertex in a
time-respecting match.
Returns
-------
vertex_maps : list (or generator) of :class:`~graph_tool.VertexPropertyMap` objects
List (or generator) containing vertex property map objects which
indicate different isomorphism mappings. The property maps vertices in
`sub` to the corresponding vertex index in `g`.
See Also
--------
mark_subgraph: Mark a subgraph in a graph
isomorphism: Isomorphism test between two graphs
maximum_common_subgraphs: Maximum common induced subgraphs of two graphs
graph_tool.clustering.motifs: Count of the motifs of a graph
Notes
-----
The implementation is based on the VF2 algorithm, introduced by Cordella et
al. [cordella-improved-2001]_ [cordella-subgraph-2004]_. The spatial
complexity is of order :math:`O(V)`, where :math:`V` is the (maximum) number
of vertices of the two graphs. Time complexity is :math:`O(V^2)` in the best
case and :math:`O(V!\times V)` in the worst case [boost-subgraph-iso]_.
If ``generator == False``, the search is split by the image of the first
vertex of ``sub`` matched by VF2, and the parts are searched in parallel;
the matches are returned in the same order as in a single search, and with
``max_n > 0`` they are the first ``max_n`` of this order. The generator
performs a single serial search.
With ``vertex_domains``, every vertex of ``sub`` can only be mapped to the
vertices of ``g`` in its domain.
With ``edge_time``, a match is time-respecting if, for every matched
vertex of ``g``, the times of the edges of ``g`` between it and the other
matched vertices differ by at most ``delta``, and, for directed graphs,
none of these out-edges is earlier than any of these in-edges, as in the
temporal subgraph isomorphism of [redmond-temporal-2013]_. The time
condition is checked for every match found by the VF2 search, so that the
time of the search does not decrease with ``delta``.
Examples
--------
We search for the wheel graph with five spokes among the induced
subgraphs of the Delaunay triangulation of random points in the plane:
.. testsetup::
np.random.seed(18)
>>> points = np.random.random((50, 2)) * 4
>>> g, pos = gt.triangulation(points, type="delaunay")
>>> sub = gt.Graph([(0, i) for i in range(1, 6)] +
... [(i, i % 5 + 1) for i in range(1, 6)], directed=False)
>>> vm = gt.subgraph_isomorphism(sub, g, induced=True)
>>> print(len(vm))
140
The 140 mappings correspond to 14 distinct wheels, since each of them is
found once for every one of the 10 automorphisms of the wheel. We
highlight the first one with :func:`~graph_tool.structure.mark_subgraph`:
>>> vmask, emask = gt.mark_subgraph(g, sub, vm[0])
>>> vcolor = g.new_vp("string", vals=np.where(vmask.a, "#f28c8e",
... "#cccccc"))
>>> ecolor = g.new_ep("string", vals=np.where(emask.a, "#e41a1c",
... "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(emask.a, 2.5, 1))
>>> gt.graph_draw(g, pos, vertex_fill_color=vcolor, edge_color=ecolor,
... edge_pen_width=ewidth, output="subgraph-iso-embed.pdf")
<...>
>>> a = 2 * np.pi * np.arange(5) / 5
>>> spos = sub.new_vp("vector<double>",
... vals=[(0, 0)] + list(zip(np.sin(a), -np.cos(a))))
>>> gt.graph_draw(sub, spos, vertex_fill_color="#f28c8e",
... edge_color="#e41a1c", output="subgraph-iso.pdf")
<...>
.. testcleanup::
conv_png("subgraph-iso-embed.pdf")
conv_png("subgraph-iso.pdf")
.. image:: subgraph-iso.png
:width: 30%
.. image:: subgraph-iso-embed.png
:width: 30%
Left: wheel graph searched. Right: one of its occurrences as an induced
subgraph of the Delaunay triangulation of 50 random points, with its
vertices and edges in red.
References
----------
.. [cordella-improved-2001] L. P. Cordella, P. Foggia, C. Sansone, and M. Vento,
"An improved algorithm for matching large graphs.", 3rd IAPR-TC15 Workshop
on Graph-based Representations in Pattern Recognition, pp. 149-159, Cuen, 2001.
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.101.5342
.. [cordella-subgraph-2004] L. P. Cordella, P. Foggia, C. Sansone, and M. Vento,
"A (Sub)Graph Isomorphism Algorithm for Matching Large Graphs.",
IEEE Trans. Pattern Anal. Mach. Intell., vol. 26, no. 10, pp. 1367-1372, 2004.
:doi:`10.1109/TPAMI.2004.75`
.. [boost-subgraph-iso] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/isomorphism/vf2_sub_graph_iso.html
.. [subgraph-isomorphism-wikipedia] http://en.wikipedia.org/wiki/Subgraph_isomorphism_problem
.. [redmond-temporal-2013] Ursula Redmond and Pádraig Cunningham,
"Temporal subgraph isomorphism", Proceedings of the 2013 IEEE/ACM
International Conference on Advances in Social Networks Analysis and
Mining, 1451-1452 (2013), :doi:`10.1145/2492517.2492586`
"""
if sub.num_vertices() == 0:
raise ValueError("Cannot search for an empty subgraph.")
dom_offset = dom_targets = None
if vertex_domains is not None:
doms = [numpy.unique(numpy.asarray([int(v) for v in d],
dtype="int64"))
for d in vertex_domains]
if len(doms) != sub.num_vertices(True):
raise ValueError("There must be one vertex domain for every " +
"vertex of the subgraph.")
dom_offset = numpy.zeros(len(doms) + 1, dtype="int64")
dom_offset[1:] = numpy.cumsum([len(d) for d in doms])
dom_targets = numpy.concatenate(doms + [numpy.zeros(0, "int64")])
if edge_time is not None:
_check_prop_scalar(edge_time, "edge_time")
edge_time = edge_time.copy("double")
if vertex_label is None:
vertex_label = (None, None)
elif vertex_label[0].value_type() != vertex_label[1].value_type():
raise ValueError("Both vertex label property maps must be of the same type!")
elif vertex_label[0].value_type() != "int64_t":
vertex_label = perfect_prop_hash(vertex_label, htype="int64_t")
if edge_label is None:
edge_label = (None, None)
elif edge_label[0].value_type() != edge_label[1].value_type():
raise ValueError("Both edge label property maps must be of the same type!")
elif edge_label[0].value_type() != "int64_t":
edge_label = perfect_prop_hash(edge_label, htype="int64_t")
vmaps = libgraph_tool_structure.\
subgraph_isomorphism(sub, g,
_check_prop("v", sub, vertex_label[0]),
_check_prop("v", g, vertex_label[1]),
_check_prop("e", sub, edge_label[0]),
_check_prop("e", g, edge_label[1]),
max_n, induced, not subgraph,
generator, dom_offset, dom_targets,
_check_prop("e", g, edge_time), float(delta))
if generator:
return (VertexPropertyMap(vmap, sub) for vmap in vmaps)
else:
return [VertexPropertyMap(vmap, sub) for vmap in vmaps]
[docs]
def mark_subgraph(g, sub, vmap, vmask=None, emask=None):
r"""
Mark a given subgraph ``sub`` on the graph ``g``.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph in which the subgraph will be marked.
sub : :class:`~graph_tool.Graph`
Subgraph to be marked.
vmap : :class:`~graph_tool.VertexPropertyMap`
Vertex property map belonging to ``sub``, which maps its vertices to
the indices of the corresponding vertices in ``g``.
vmask : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Boolean vertex property map of ``g`` where the result will be stored.
If not provided, a new one will be created.
emask : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Boolean edge property map of ``g`` where the result will be stored.
If not provided, a new one will be created.
Returns
-------
vmask : :class:`~graph_tool.VertexPropertyMap`
Boolean vertex property map indicating whether or not a vertex in
``g`` belongs to the subgraph ``sub``.
emask : :class:`~graph_tool.EdgePropertyMap`
Boolean edge property map indicating whether or not an edge in ``g``
belongs to the subgraph ``sub``.
See Also
--------
subgraph_isomorphism: Occurrences of a subgraph in a graph
maximum_common_subgraphs: Maximum common induced subgraphs of two graphs
"""
if vmask is None:
vmask = g.new_vertex_property("bool")
if emask is None:
emask = g.new_edge_property("bool")
vmask.a = False
emask.a = False
for v in sub.vertices():
w = g.vertex(vmap[v])
vmask[w] = True
us = set([g.vertex(vmap[x]) for x in v.out_neighbors()])
for ew in w.out_edges():
if ew.target() in us:
emask[ew] = True
return vmask, emask
def _label_codes(g, label, key):
"""Return integer codes for the values of a vertex or edge property map,
indexed by the vertex or edge index, which are equal if and only if the
values are equal (up to hash collisions for non-scalar values), and do not
depend on the graph."""
return libgraph_tool_structure.label_codes(g,
label._get_any(), key == "v")
def _vprop_from_array(g, a):
"""Return a new ``int64_t`` vertex property map with the values of an array
indexed by the vertex index."""
p = g.new_vp("int64_t")
p.a = a
return p
def _automorphism_group(backend, g, vertex_label, edge_label, orbits,
canonical):
gens, factors, orb, lab = libgraph_tool_structure.automorphism_group(
g, backend,
vertex_label._get_any() if vertex_label is not None else None,
edge_label._get_any() if edge_label is not None else None,
canonical)
order = 1
for f in factors:
order *= int(f)
ret = [[_vprop_from_array(g, gen) for gen in gens], order]
if orbits:
ret.append(_vprop_from_array(g, orb))
if canonical:
ret.append(_vprop_from_array(g, lab))
return tuple(ret)
_aut_params = r"""g : :class:`~graph_tool.Graph`
Graph to be used.
vertex_label : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If given, only automorphisms that preserve the values of this property
map are considered.
edge_label : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If given, only automorphisms that preserve the values of this property
map are considered.
orbits : ``bool`` (optional, default: ``False``)
If ``True``, the vertex orbits of the group are also returned.
canonical : ``bool`` (optional, default: ``False``)
If ``True``, a canonical labeling of the vertices is also returned."""
_aut_returns = r"""generators : ``list`` of :class:`~graph_tool.VertexPropertyMap`
Generators of the automorphism group, each given by the image
``gen[v]`` of every vertex ``v``.
order : ``int``
Order of the automorphism group, i.e. the number of automorphisms.
orbit : :class:`~graph_tool.VertexPropertyMap`
Orbit of every vertex, labeled by the smallest vertex index it
contains. Only returned if ``orbits == True``.
labeling : :class:`~graph_tool.VertexPropertyMap`
Canonical position of every vertex, in the range :math:`[0, V-1]`.
Only returned if ``canonical == True``."""
_aut_notes = r"""An
`automorphism <https://en.wikipedia.org/wiki/Graph_automorphism>`_ of a
graph is a permutation :math:`\pi` of its
vertices that maps the graph onto itself, i.e. such that, for every pair
of vertices :math:`u` and :math:`v`, the edges from :math:`\pi(u)` to
:math:`\pi(v)` are as many as those from :math:`u` to :math:`v` (following
the edge directions, for directed graphs), and that preserves the labels:
:math:`\pi(v)` has the same label as :math:`v`, and the multiset of the
labels of the edges from :math:`\pi(u)` to :math:`\pi(v)` is that of the
edges from :math:`u` to :math:`v`. The automorphisms form a group under
composition, whose orbits are the sets of vertices that are mapped onto
one another. The group is described by a set of generators, i.e.
automorphisms whose compositions yield every automorphism, and by its
order, the number of automorphisms.
Graphs with edge labels, parallel edges, or self-loops are
reduced to vertex-colored simple graphs with the same automorphisms:
self-loops are absorbed into the colors of their vertices, parallel edges
are merged into a single edge labeled by the multiset of their labels, and
the edges with a label other than the most frequent one are subdivided by an
auxiliary vertex of a distinct color.
Every generator is a property map with an entry for each vertex, so that the
memory needed is :math:`O(V)` per generator, which may be large for networks
with many generators.
Two graphs are isomorphic if and only if they become identical, including
their vertex and edge labels, after their vertices are relabeled according
to their
`canonical labelings <https://en.wikipedia.org/wiki/Graph_canonization>`_.
The canonical labeling depends on the
algorithm and its version, and hence can only be compared between results of
the same function and version of `graph-tool`."""
[docs]
def bliss_automorphism_group(g, vertex_label=None, edge_label=None,
orbits=False, canonical=False):
r"""Obtain the automorphism group of the graph with the bliss algorithm.
Parameters
----------
@params@
Returns
-------
@returns@
See Also
--------
nauty_automorphism_group: Automorphism group with nauty or Traces
isomorphism: Isomorphism test between two graphs
weisfeiler_lehman_hash: Hash of a graph that is invariant under isomorphism
Notes
-----
@notes@
The automorphisms are found with the search algorithm of Junttila and
Kaski implemented by the bliss library [junttila-bliss-2007]_
[junttila-bliss-2011]_, a copy of which is included in `graph-tool`. The
group is returned as a set of at most :math:`V-1` generators. The running
time is typically almost linear in the size of the graph for sparse
networks, but is exponential in the worst case.
Examples
--------
The Petersen graph has 120 automorphisms, and all its vertices are
equivalent:
>>> g = gt.collection.petersen_graph()
>>> gens, order, orbit = gt.bliss_automorphism_group(g, orbits=True)
>>> print(order, len(set(orbit.a)))
120 1
Two graphs can be tested for isomorphism by comparing their canonically
relabeled edges:
>>> def canonical_edges(g):
... gens, order, c = gt.bliss_automorphism_group(g, canonical=True)
... es = c.a[g.get_edges()]
... es.sort(axis=1)
... return set(map(tuple, es))
>>> g = gt.collection.data["karate"]
>>> u = gt.Graph(g, vorder=g.new_vp("int", vals=np.random.permutation(g.num_vertices())))
>>> canonical_edges(g) == canonical_edges(u)
True
References
----------
.. [junttila-bliss-2007] Tommi Junttila and Petteri Kaski, "Engineering an
efficient canonical labeling tool for large and sparse graphs",
Proceedings of the Ninth Workshop on Algorithm Engineering and
Experiments (ALENEX), 135-149 (2007), :DOI:`10.1137/1.9781611972870.13`
.. [junttila-bliss-2011] Tommi Junttila and Petteri Kaski, "Conflict
propagation and component recursion for canonical labeling",
Theory and Practice of Algorithms in (Computer) Systems (TAPAS),
151-162 (2011), :DOI:`10.1007/978-3-642-19754-3_16`
.. [bliss] https://users.aalto.fi/~tjunttil/bliss/
"""
return _automorphism_group("bliss", g, vertex_label, edge_label, orbits,
canonical)
[docs]
def nauty_automorphism_group(g, vertex_label=None, edge_label=None,
orbits=False, canonical=False, traces=False):
r"""Obtain the automorphism group of the graph with the nauty or Traces
algorithms.
Parameters
----------
@params@
traces : ``bool`` (optional, default: ``False``)
If ``True``, the Traces algorithm is used instead of nauty's.
Returns
-------
@returns@
See Also
--------
bliss_automorphism_group: Automorphism group with the bliss algorithm
isomorphism: Isomorphism test between two graphs
weisfeiler_lehman_hash: Hash of a graph that is invariant under isomorphism
Notes
-----
@notes@
The automorphisms are found with the sparse version of the nauty
algorithm or with the Traces algorithm of McKay and Piperno
[mckay-practical-2014]_, both from the nauty library [nauty]_, of which
`graph-tool` includes a copy compiled with thread-local storage, so that
concurrent calls are possible. Directed graphs are passed to
the library as undirected graphs with three copies of every vertex, since
the search of nauty for directed graphs is very slow. The group is
returned as a set of at most :math:`V-1` generators.
The two algorithms explore the same search tree in different ways: nauty
goes depth-first, whereas Traces goes breadth-first, compares the
sequences of cell splits of the refinements to discard nodes early, and
keeps track of the group found so far to prune equivalent nodes. The
running time of both is exponential in the worst case, and neither is
always faster than the other, or than
:func:`~graph_tool.structure.bliss_automorphism_group`.
Traces gives the order of the group only as a floating-point number, so
the exact order is computed from the generators. The group is first split
into the direct product of the groups generated on disjoint sets of
vertices, and the order of each of these is found with the randomized
Schreier-Sims algorithm [seress-permutation-2003]_, as a product of
orbit sizes. The result is a lower bound on the order, each of whose
factors is at most :math:`V`, so that a bound that is not exact falls
short by a fraction of at least :math:`1/V`; the algorithm continues until
the bound agrees with the estimate of Traces to within :math:`1/(2V)`, at
which point it is exact.
Examples
--------
.. doctest:: nauty
>>> g = gt.collection.data["karate"]
>>> gens, order = gt.nauty_automorphism_group(g)
>>> print(order)
480
>>> gens, order = gt.nauty_automorphism_group(g, traces=True)
>>> print(order)
480
References
----------
.. [mckay-practical-2014] Brendan D. McKay and Adolfo Piperno, "Practical
graph isomorphism, II", Journal of Symbolic Computation 60, 94-112
(2014), :DOI:`10.1016/j.jsc.2013.09.003`, :arxiv:`1301.1493`
.. [seress-permutation-2003] Ákos Seress, "Permutation group
algorithms", Cambridge University Press (2003),
:DOI:`10.1017/CBO9780511546549`
.. [nauty] https://pallini.di.uniroma1.it
"""
return _automorphism_group("traces" if traces else "nauty", g,
vertex_label, edge_label, orbits, canonical)
# The placeholders are replaced with the fragments indented as the placeholder
# lines, since docstrings may or may not be dedented already, depending on the
# Python version (dedenting is done by the compiler since 3.13).
for f in [bliss_automorphism_group, nauty_automorphism_group]:
for key, frag in [("params", _aut_params), ("returns", _aut_returns),
("notes", _aut_notes)]:
f.__doc__ = re.sub(rf"^( *)@{key}@ *$",
lambda m: textwrap.indent(inspect.cleandoc(frag),
m.group(1)),
f.__doc__, flags=re.M)
del f, key, frag
[docs]
@_parallel
def weisfeiler_lehman_hash(g, vertex_label=None, edge_label=None, n_iter=3,
vertex_hashes=False):
r"""Return the Weisfeiler-Lehman hash of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
vertex_label : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If given, the initial labels of the vertices.
edge_label : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If given, the labels of the edges.
n_iter : ``int`` (optional, default: ``3``)
Number of refinement iterations.
vertex_hashes : ``bool`` (optional, default: ``False``)
If ``True``, the hashes of the individual vertices after the last
iteration are also returned.
Returns
-------
hash : ``int``
Hash of the graph, as an unsigned 64-bit integer.
vhash : :class:`~graph_tool.VertexPropertyMap`
Hashes of the vertices, as signed 64-bit integers. Only returned if
``vertex_hashes == True``.
See Also
--------
isomorphism: Exact isomorphism test between two graphs
bliss_automorphism_group: Canonical labeling with the bliss algorithm
nauty_automorphism_group: Canonical labeling with nauty or Traces
Notes
-----
The
`color refinement <https://en.wikipedia.org/wiki/Weisfeiler_Leman_graph_isomorphism_test>`_
of Weisfeiler and Leman
[weisfeiler-reduction-1968]_ [shervashidze-weisfeiler-2011]_ starts from
the labels :math:`h^{(0)}_v = \mathrm{hash}(x_v)`, where :math:`x_v` is
the value of ``vertex_label`` (the same for all vertices if it is not
given), and computes in each iteration
.. math::
h^{(t+1)}_v = \mathrm{hash}\left(h^{(t)}_v,
\{\!\{(d_e, y_e, h^{(t)}_{u_e}) : e \ni v\}\!\}\right),
where the multiset runs over the edges :math:`e` incident to :math:`v`
(both in- and out-edges, for directed graphs), :math:`u_e` is the other
endpoint of :math:`e`, :math:`y_e` its value of ``edge_label`` (if
given), and :math:`d_e` indicates whether :math:`e` is an out- or an
in-edge of :math:`v` (for undirected graphs, it is the same for all
edges). Every edge appears in the multiset as many times as it
contributes to the total degree of :math:`v`: parallel edges appear once
each, and a self-loop twice (once as an out-edge and once as an in-edge,
for directed graphs), with :math:`u_e = v`. The multisets are hashed
after sorting. The hash of the graph is
:math:`\mathrm{hash}(n_{\text{iter}}, M^{(0)}, \dots,
M^{(n_{\text{iter}})})`, where :math:`M^{(t)} =
\{\!\{h^{(t)}_v\}\!\}` is the multiset of the labels of iteration
:math:`t`, and the vertex hashes returned are
:math:`h^{(n_{\text{iter}})}_v`.
Isomorphic graphs have the same hash, but graphs with the same hash are
not necessarily isomorphic: besides hash collisions, which are unlikely
for 64-bit hashes, the refinement cannot distinguish some non-isomorphic
graphs, such as regular graphs of the same size and degree. The
automorphism group and an exact isomorphism test are obtained with
:func:`~graph_tool.structure.bliss_automorphism_group` or
:func:`~graph_tool.structure.nauty_automorphism_group`. The hash values
are not cryptographic, and do not depend on the platform; the values of
labels of type ``python::object`` are hashed via their Python
representation.
The algorithm runs in time :math:`O(n_{\text{iter}}(V\log V + E\log
k_{\text{max}}))`.
@parallel@
Examples
--------
>>> g = gt.collection.data["karate"]
>>> u = gt.Graph(g, vorder=g.new_vp("int", vals=np.random.permutation(g.num_vertices())))
>>> gt.weisfeiler_lehman_hash(g) == gt.weisfeiler_lehman_hash(u)
True
>>> u.remove_edge(next(u.edges()))
>>> gt.weisfeiler_lehman_hash(g) == gt.weisfeiler_lehman_hash(u)
False
References
----------
.. [weisfeiler-reduction-1968] Boris Weisfeiler and Andrei Leman, "The
reduction of a graph to canonical form and the algebra which appears
therein", Nauchno-Technicheskaya Informatsia 2(9), 12-16 (1968).
.. [shervashidze-weisfeiler-2011] Nino Shervashidze, Pascal Schweitzer,
Erik Jan van Leeuwen, Kurt Mehlhorn and Karsten M. Borgwardt,
"Weisfeiler-Lehman graph kernels", Journal of Machine Learning
Research 12, 2539-2561 (2011),
https://jmlr.org/papers/v12/shervashidze11a.html
"""
if vertex_label is None:
vc = numpy.zeros(g.num_vertices(True), dtype="int64")
else:
vc = numpy.ascontiguousarray(_label_codes(g, vertex_label, "v"))
ec = None
if edge_label is not None:
ec = numpy.ascontiguousarray(_label_codes(g, edge_label, "e"))
h, vh = libgraph_tool_structure.weisfeiler_lehman_hash(g,
vc, ec, n_iter)
if vertex_hashes:
p = g.new_vp("int64_t")
p.a = vh
return h, p
return h
[docs]
def maximal_cliques(g, min_size=None, max_size=None, vertices=None):
"""Return an iterator over the maximal cliques of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
min_size : ``int`` (optional, default: ``None``)
If given, only the maximal cliques with at least this many vertices
are returned.
max_size : ``int`` (optional, default: ``None``)
If given, only the maximal cliques with at most this many vertices
are returned.
vertices : iterable of ``int`` (optional, default: ``None``)
If given, only the maximal cliques that contain all these vertices
are returned. They must form a clique.
Returns
-------
maximal_cliques : iterator over :class:`numpy.ndarray` instances
Iterator over lists of vertices corresponding to the maximal cliques.
See Also
--------
all_cliques: All cliques, maximal or not
largest_cliques: Cliques of maximum size
clique_number: Size of a largest clique
chordal_cliques: Maximal cliques of a chordal graph
graph_tool.clustering.motifs: Counts of connected subgraphs
Notes
-----
This implements the Bron-Kerbosch algorithm [bron_algorithm_1973]_
[bron-kerbosh-wiki]_ with pivoting [tomita_worst-case_2006]_
[cazals_note_2008]_.
The edge directions and self-loops are ignored, and the maximal cliques of
size one (i.e. vertices without neighbors) are not included.
The worst case complexity of this algorithm is :math:`O(3^{V/3})` for a
graph of :math:`V` vertices, but for sparse graphs it is typically much
faster. The branches of the search that cannot lead to a clique within
the size bounds are pruned, and with ``vertices`` the search starts from
these vertices and their common neighbors. Isolated vertices are not
returned as cliques of size one, unless they are given in ``vertices``.
Examples
--------
>>> g = gt.collection.data["polblogs"]
>>> len(list(gt.maximal_cliques(g)))
49618
>>> len(list(gt.maximal_cliques(g, min_size=10)))
25165
>>> len(list(gt.maximal_cliques(g, vertices=[0])))
37
References
----------
.. [bron_algorithm_1973] Coen Bron and Joep Kerbosch, "Algorithm 457:
finding all cliques of an undirected graph", Commun. ACM 16, 9, 575-577
(1973), :doi:`10.1145/362342.362367`
.. [tomita_worst-case_2006] Etsuji Tomita, Akira Tanaka, and Haruhisa
Takahashi. "The worst-case time complexity for generating all maximal
cliques and computational experiments." Theoretical Computer Science 363.1
28-42 (2006), :doi:`10.1016/j.tcs.2006.06.015`
.. [cazals_note_2008] Frédéric Cazals, and Chinmay Karande, "A note on the
problem of reporting maximal cliques." Theoretical Computer Science 407.1-3
564-568 (2008), :doi:`10.1016/j.tcs.2008.05.010`
.. [bron-kerbosh-wiki] https://en.wikipedia.org/wiki/Bron%E2%80%93Kerbosch_algorithm
"""
if g.is_directed():
g = GraphView(g, directed=False)
if vertices is None:
vertices = []
vertices = numpy.unique(numpy.asarray([int(v) for v in vertices],
dtype="int64"))
if min_size is None:
min_size = 0
if max_size is None:
max_size = 0
elif max_size < 1:
return
for c in libgraph_tool_structure.max_cliques(g, vertices, int(min_size),
int(max_size)):
yield c
[docs]
@_check_props(e=("weights", "tree_map"))
def minimum_spanning_tree(g, weights=None, root=None, tree_map=None,
include=None, exclude=None):
r"""
Return the minimum spanning tree of a given graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
The edge weights. If provided, the minimum spanning tree will minimize
the edge weights.
root : :class:`~graph_tool.Vertex` (optional, default: ``None``)
Root of the minimum spanning tree. If this is provided, Prim's algorithm
is used. Otherwise, Kruskal's algorithm is used.
tree_map : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If provided, the edge tree map will be written in this property map.
include : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Boolean edge property map marking edges that must belong to the tree.
exclude : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Boolean edge property map marking edges that must not belong to the
tree.
Returns
-------
tree_map : :class:`~graph_tool.EdgePropertyMap`
Edge property map which marks the tree edges: 1 for tree edge, 0
otherwise.
See Also
--------
minimum_spanning_arborescence: Minimum spanning tree of a directed graph
random_spanning_tree: Uniformly sampled spanning tree
steiner_tree: Approximate minimum tree connecting a subset of vertices
graph_tool.spectral.num_spanning_trees: Number of spanning trees
Notes
-----
The algorithm runs with :math:`O(E\log E)` complexity, or :math:`O(E\log V)`
if `root` is specified.
With ``include`` and ``exclude``, the tree is the minimum one among those
that contain the included edges and none of the excluded ones, as used
to enumerate spanning trees in order of weight [sorensen-algorithm-2005]_:
the excluded edges are removed, and the included ones get a weight
smaller than all others, so that they are taken first (if they form a
cycle, not all of them are in the tree). If the remaining edges do not
connect the graph, a spanning forest is returned.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> from numpy.random import random
>>> g, pos = gt.triangulation(random((400, 2)) * 10, type="delaunay")
>>> weight = g.new_edge_property("double")
>>> for e in g.edges():
... weight[e] = linalg.norm(pos[e.target()].a - pos[e.source()].a)
>>> tree = gt.minimum_spanning_tree(g, weights=weight)
>>> gt.graph_draw(g, pos=pos, output="triang_orig.pdf")
<...>
>>> u = gt.GraphView(g, efilt=tree)
>>> gt.graph_draw(u, pos=pos, output="triang_min_span_tree.pdf")
<...>
.. testcleanup::
conv_png("triang_orig.pdf")
conv_png("triang_min_span_tree.pdf")
.. image:: triang_orig.png
:width: 400px
.. image:: triang_min_span_tree.png
:width: 400px
*Left:* Original graph, *Right:* The minimum spanning tree.
References
----------
.. [kruskal-shortest-1956] J. B. Kruskal. "On the shortest spanning subtree
of a graph and the traveling salesman problem", In Proceedings of the
American Mathematical Society, volume 7, pages 48-50, 1956.
:doi:`10.1090/S0002-9939-1956-0078686-7`
.. [prim-shortest-1957] R. Prim. "Shortest connection networks and some
generalizations", Bell System Technical Journal, 36:1389-1401, 1957.
.. [boost-mst] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/about/graph_theory_review.html#sec:minimum-spanning-tree
.. [mst-wiki] http://en.wikipedia.org/wiki/Minimum_spanning_tree
.. [sorensen-algorithm-2005] Kenneth Sörensen and Gerrit K. Janssens, "An
algorithm to generate all spanning trees of a graph in order of
increasing cost", Pesquisa Operacional 25, 219-229 (2005),
:DOI:`10.1590/S0101-74382005000200004`
"""
if tree_map is None:
tree_map = g.new_edge_property("bool")
if tree_map.value_type() != "bool":
raise ValueError("edge property 'tree_map' must be of value type bool.")
if include is not None or exclude is not None:
w = g.new_ep("double")
if weights is None:
w.a = 1
else:
w.a = weights.a
es = g.get_edges([g.edge_index])[:, 2]
if include is not None:
inc = include.a[es].astype(bool)
if inc.any():
# The weights are shifted to be at least one, which does not
# change the minimum tree, so that the included edges can get
# a smaller weight that is not negative (as required by
# Prim's algorithm).
w.a[es] -= w.a[es].min() - 1
w.a[es[inc]] = 0
weights = w
if exclude is not None:
g = GraphView(g, efilt=numpy.logical_not(exclude.a.astype(bool)))
u = GraphView(g, directed=False)
if root is None:
libgraph_tool_structure.\
get_kruskal_spanning_tree(u,
weights,
tree_map)
else:
libgraph_tool_structure.\
get_prim_spanning_tree(u, int(root),
weights,
tree_map)
return tree_map
[docs]
@_check_props(e=("weights", "tree_map"))
def minimum_spanning_arborescence(g, weights=None, root=None,
tree_map=None, maximum=False,
spanning=True):
r"""Return the minimum spanning arborescence of a directed graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed graph to be used.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
The edge weights. If not supplied, every edge has unit weight. They
may be negative.
root : :class:`~graph_tool.Vertex` (optional, default: ``None``)
Root of the arborescence. If not supplied, the root is chosen so that
the total weight is minimal.
tree_map : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If provided, the edge tree map will be written in this property map.
maximum : ``bool`` (optional, default: ``False``)
If ``True``, the arborescence (or branching) of maximum weight is
returned instead.
spanning : ``bool`` (optional, default: ``True``)
If ``False``, a minimum (or maximum) branching is returned instead of
a spanning arborescence, and ``root`` is ignored.
Returns
-------
tree_map : :class:`~graph_tool.EdgePropertyMap`
Edge property map that marks the tree edges: 1 for tree edge, 0
otherwise.
See Also
--------
all_spanning_arborescences: Spanning arborescences in order of weight
minimum_spanning_tree: Minimum spanning tree of an undirected graph
random_spanning_tree: Uniformly sampled spanning tree
Notes
-----
A
`spanning arborescence <https://en.wikipedia.org/wiki/Arborescence_(graph_theory)>`_
is a directed spanning tree in which every vertex
except the root has exactly one incoming tree edge, so that there is a
directed path from the root to every vertex. The one with the smallest sum
of edge weights is the directed analogue of the minimum spanning tree
(see :func:`minimum_spanning_tree`, which treats directed graphs as
undirected), and is also known as the optimum branching
[edmonds-optimum-1967]_
[chu-shortest-1965]_. A maximum spanning arborescence (``maximum == True``)
is obtained with negated weights. If no spanning arborescence exists
(because some vertex cannot be reached from the root, or from any single
vertex if ``root is None``), a :class:`ValueError` is raised. Self-loops
are ignored.
The implementation follows the :math:`O(E\log V)` algorithm of
[tarjan-finding-1977]_ (with the correction of [camerini-note-1979]_),
where every vertex selects its cheapest incoming edge, and the cycles that
form are contracted, using mergeable heaps of the incoming edges. If
``root`` is ``None``, a virtual root is connected to every vertex with an
edge heavier than any arborescence.
A branching is a forest of arborescences, i.e. a set of edges in which
every vertex has at most one incoming edge and that has no cycles. With
``spanning == False``, the branching of minimum (or maximum) weight is
obtained as the minimum spanning arborescence of the graph extended with
a virtual root connected to every vertex by an edge of weight zero,
without these edges. Hence, a minimum branching contains only edges of
negative weight, and a maximum branching only edges of positive weight.
The spanning arborescences in order of their weight are generated by
:func:`all_spanning_arborescences`.
Examples
--------
.. testcode::
:hide:
np.random.seed(42)
gt.seed_rng(42)
>>> g = gt.collection.data["polblogs"]
>>> g = gt.extract_largest_component(g, directed=True, prune=True)
>>> w = g.new_ep("double", vals=np.random.random(g.num_edges()))
>>> tree = gt.minimum_spanning_arborescence(g, weights=w)
>>> print(tree.a.sum(), (tree.a * w.a).sum())
792 154.328281612...
>>> b = gt.minimum_spanning_arborescence(g, weights=w, maximum=True,
... spanning=False)
>>> print(b.a.sum(), (b.a * w.a).sum())
792 644.162253899...
The arborescence can be visualized for a smaller graph, obtained from the
Delaunay triangulation of random points in the plane, with the edges
directed away from vertex 0 (or arbitrarily, between vertices at the
same distance from it), and the lengths of the edges as weights:
.. testcode::
:hide:
np.random.seed(42)
>>> points = np.random.random((60, 2)) * 4
>>> u, pos = gt.triangulation(points, type="delaunay")
>>> d = gt.shortest_distance(u, 0)
>>> es = u.get_edges()
>>> back = d.a[es[:, 0]] > d.a[es[:, 1]]
>>> es[back] = es[back][:, ::-1]
>>> g = gt.Graph(es)
>>> w = g.new_ep("double", vals=np.linalg.norm(points[es[:, 0]] -
... points[es[:, 1]], axis=1))
>>> tree = gt.minimum_spanning_arborescence(g, weights=w, root=0)
>>> vcolor = g.new_vp("string", vals=["#f28c8e"] +
... ["#cccccc"] * (g.num_vertices() - 1))
>>> ecolor = g.new_ep("string", vals=np.where(tree.a, "#e41a1c",
... "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(tree.a, 2, 1))
>>> gt.graph_draw(g, pos, vertex_fill_color=vcolor, edge_color=ecolor,
... edge_pen_width=ewidth, eorder=tree,
... output="minimum_spanning_arborescence-triang.pdf")
<...>
.. testcleanup::
conv_png("minimum_spanning_arborescence-triang.pdf")
.. figure:: minimum_spanning_arborescence-triang.png
:align: center
:width: 60%
Minimum spanning arborescence rooted at vertex 0 (in red) of the
Delaunay triangulation of 60 random points, with the edges directed
away from the root and weighted by their Euclidean lengths. The edges
of the arborescence are shown in red, and the other edges in gray.
References
----------
.. [edmonds-optimum-1967] Jack Edmonds, "Optimum branchings", Journal of
Research of the National Bureau of Standards B 71, 233-240 (1967),
:doi:`10.6028/jres.071B.032`
.. [chu-shortest-1965] Yoeng-Jin Chu and Tseng-Hong Liu, "On the shortest
arborescence of a directed graph", Scientia Sinica 14, 1396-1400
(1965).
.. [tarjan-finding-1977] Robert E. Tarjan, "Finding optimum branchings",
Networks 7, 25-35 (1977), :doi:`10.1002/net.3230070103`
.. [camerini-note-1979] Paolo M. Camerini, Luigi Fratta and Francesco
Maffioli, "A note on finding optimum branchings", Networks 9, 309-312
(1979), :doi:`10.1002/net.3230090403`
"""
if not g.is_directed():
raise ValueError("The graph must be directed; for undirected graphs, " +
"use minimum_spanning_tree().")
if tree_map is None:
tree_map = g.new_edge_property("bool")
if tree_map.value_type() != "bool":
raise ValueError("edge property 'tree_map' must be of value type bool.")
if weights is not None:
_check_prop_scalar(weights, "weights")
ok = libgraph_tool_structure.\
min_spanning_arborescence(g, weights,
-1 if root is None else int(root),
tree_map, maximum, spanning)
if not ok:
raise ValueError("The graph has no spanning arborescence" +
(" with the given root" if root is not None else "") +
".")
return tree_map
[docs]
def all_spanning_arborescences(g, weights=None, root=None, maximum=False):
r"""Return an iterator over the spanning arborescences of a directed
graph, in order of increasing (or decreasing) weight.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed graph to be used.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
The edge weights. If not supplied, every edge has unit weight.
root : :class:`~graph_tool.Vertex` (optional, default: ``None``)
Root of the arborescences. If not supplied, arborescences with any
root are generated.
maximum : ``bool`` (optional, default: ``False``)
If ``True``, the arborescences are generated in order of decreasing
weight.
Returns
-------
arborescences : iterator over :class:`~graph_tool.EdgePropertyMap`
Iterator over Boolean edge property maps that mark the edges of each
arborescence.
See Also
--------
minimum_spanning_arborescence: Minimum spanning arborescence only
common_spanning_trees: Spanning trees common to two graphs
graph_tool.spectral.num_spanning_trees: Number of spanning trees
Notes
-----
A
`spanning arborescence <https://en.wikipedia.org/wiki/Arborescence_(graph_theory)>`_
with root :math:`r` is a set of :math:`V-1`
edges in which every vertex other than :math:`r` has exactly one
incoming edge and which contains a directed path from :math:`r` to every
vertex, and its weight is the sum of the weights of its edges. The
arborescences are generated with the partition scheme of Sörensen and
Janssens [sorensen-algorithm-2005]_: the arborescences that contain a set
of included edges and avoid a set of excluded edges are represented by the
minimum one among them, found with
:func:`minimum_spanning_arborescence` after removing the excluded edges
and the other edges that point to the heads of the included ones. After this arborescence is generated, its set is split
along its edges :math:`f_1,\dots,f_m` that are not included into the sets
with the included edges extended by :math:`f_1,\dots,f_{i-1}` and the
excluded edges extended by :math:`f_i`. The sets are kept in a priority
queue ordered by their minimum weight, so that every arborescence takes
time :math:`O(VE\log V)`. Self-loops are ignored, and arborescences of
equal weight are generated in an unspecified order.
Examples
--------
>>> g = gt.complete_graph(4, directed=True)
>>> w = g.new_ep("double", vals=np.arange(g.num_edges()))
>>> print(*[(tree.a * w.a).sum() for tree in
... gt.all_spanning_arborescences(g, w, root=0)])
3.0 6.0 6.0 9.0 9.0 10.0 12.0 13.0 13.0 13.0 16.0 16.0 16.0 19.0 20.0 23.0
References
----------
.. [sorensen-algorithm-2005] Kenneth Sörensen and Gerrit K. Janssens, "An
algorithm to generate all spanning trees of a graph in order of
increasing cost", Pesquisa Operacional 25, 219-229 (2005),
:doi:`10.1590/S0101-74382005000200004`
"""
if not g.is_directed():
raise ValueError("The graph must be directed.")
if weights is not None:
_check_prop_scalar(weights, "weights")
for idx, w in libgraph_tool_structure.\
ranked_arborescences(g, weights,
-1 if root is None else int(root),
maximum):
tree = g.new_ep("bool")
tree.a[idx] = True
yield tree
[docs]
@_check_props(e=("weights", "tree_map"))
def random_spanning_tree(g, weights=None, root=None, tree_map=None):
r"""Return a random spanning tree of a given graph, which can be directed or
undirected.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
The edge weights. If provided, the probability of a particular spanning
tree being selected is the product of its edge weights.
root : :class:`~graph_tool.Vertex` (optional, default: ``None``)
Root of the spanning tree. If not provided, it will be selected randomly.
tree_map : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If provided, the edge tree map will be written in this property map.
Returns
-------
tree_map : :class:`~graph_tool.EdgePropertyMap`
Edge property map which marks the tree edges: 1 for tree edge, 0
otherwise.
See Also
--------
minimum_spanning_tree: Minimum spanning tree
loop_erased_random_walk: Loop-erased random walk
minimum_spanning_arborescence: Minimum spanning arborescence
Notes
-----
The running time for this algorithm is :math:`O(\tau)`, with :math:`\tau`
being the mean hitting time of a random walk on the graph. In the worst case,
we have :math:`\tau \sim O(V^3)`, with :math:`V` being the number of
vertices in the graph. However, in much more typical cases (e.g. sparse
random graphs) the running time is simply :math:`O(V)`.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> from numpy.random import random
>>> g, pos = gt.triangulation(random((400, 2)), type="delaunay")
>>> weight = g.new_edge_property("double")
>>> for e in g.edges():
... weight[e] = linalg.norm(pos[e.target()].a - pos[e.source()].a)
>>> tree = gt.random_spanning_tree(g, weights=weight)
>>> tree2 = gt.random_spanning_tree(g, weights=weight)
>>> gt.graph_draw(g, pos=pos, output="rtriang_orig.pdf")
<...>
>>> u = gt.GraphView(g, efilt=tree)
>>> gt.graph_draw(u, pos=pos, output="triang_random_span_tree.pdf")
<...>
>>> u2 = gt.GraphView(g, efilt=tree2)
>>> gt.graph_draw(u2, pos=pos, output="triang_random_span_tree2.pdf")
<...>
.. testcleanup::
conv_png("rtriang_orig.pdf")
conv_png("triang_random_span_tree.pdf")
conv_png("triang_random_span_tree2.pdf")
.. image:: rtriang_orig.png
:width: 300px
.. image:: triang_random_span_tree.png
:width: 300px
.. image:: triang_random_span_tree2.png
:width: 300px
*Left:* Original graph, *Middle:* A random spanning tree, *Right:* Another
random spanning tree
References
----------
.. [wilson-generating-1996] David Bruce Wilson, "Generating random spanning
trees more quickly than the cover time", Proceedings of the twenty-eighth
annual ACM symposium on Theory of computing, Pages 296-303, ACM New York,
1996, :doi:`10.1145/237814.237880`
.. [boost-rst] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/spanning_trees/random_spanning_tree.html
"""
if tree_map is None:
tree_map = g.new_edge_property("bool")
if tree_map.value_type() != "bool":
raise ValueError("edge property 'tree_map' must be of value type bool.")
if root is None:
root = g.vertex(numpy.random.randint(0, g.num_vertices()),
use_index=False)
# we need to restrict ourselves to the in-component of root
l = label_out_component(GraphView(g, reversed=True), root)
u = GraphView(g, vfilt=l)
if u.num_vertices() != g.num_vertices():
raise ValueError("There must be a path from all vertices to the root vertex: %d" % int(root) )
libgraph_tool_structure.\
random_spanning_tree(g, int(root),
weights,
tree_map, _get_rng())
return tree_map
[docs]
@_check_props(v=("dom_map",))
def dominator_tree(g, root, dom_map=None):
r"""Return a vertex property map containing the dominator vertices for each
vertex.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
root : :class:`~graph_tool.Vertex`
The root vertex.
dom_map : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, the dominator map will be written in this property map.
Returns
-------
dom_map : :class:`~graph_tool.VertexPropertyMap`
The dominator map. It contains for each vertex, the index of its
immediate dominator vertex.
See Also
--------
dominance_frontiers: Dominance frontier of every vertex
lowest_common_ancestors: Lowest common ancestors of pairs of vertices
topological_sort: Topological ordering of a directed acyclic graph
Notes
-----
A vertex u dominates a vertex v, if every path of directed graph from the
entry to v must go through u.
The values of the root and of the vertices that are not reachable from it
are left unchanged. If ``dom_map`` is not provided, they are therefore
zero, the same value as for the vertices whose immediate dominator is
vertex ``0``, so the latter can only be identified by also determining
which vertices are reachable from the root (e.g. with
:func:`~graph_tool.structure.label_out_component`).
The algorithm of Lengauer and Tarjan is run on the subgraph of the
vertices reachable from the root, since the predecessors that are not
reachable would otherwise affect the result.
The algorithm runs with :math:`O((V+E)\log (V+E))` complexity.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> g = gt.random_graph(100, lambda: (2, 2))
>>> tree = gt.minimum_spanning_tree(g)
>>> g.set_edge_filter(tree)
>>> root = [v for v in g.vertices() if v.in_degree() == 0]
>>> dom = gt.dominator_tree(g, root[0])
>>> print(dom.a)
[ 0 0 0 0 0 38 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0]
For a small control-flow graph, the dominator tree can be drawn together
with the graph:
>>> g = gt.Graph([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4), (4, 5), (5, 1),
... (4, 6)])
>>> dom = gt.dominator_tree(g, 0)
>>> print(dom.a)
[0 0 1 1 1 4 4]
>>> h = g.copy()
>>> h.add_edge_list([(dom[v], v) for v in range(1, 7)])
>>> ecolor = h.new_ep("string", vals=["#999999"] * 8 + ["#e41a1c"] * 6)
>>> pos = h.new_vp("vector<double>", vals=[(0, 0), (0, 1), (-1, 2),
... (1, 2), (0, 3), (-1, 4),
... (1, 4)])
>>> gt.graph_draw(h, pos, vertex_text=h.vertex_index,
... vertex_fill_color="#cccccc", edge_color=ecolor,
... vertex_size=25, edge_pen_width=2,
... output="dominator_tree-cfg.pdf")
<...>
.. testcleanup::
conv_png("dominator_tree-cfg.pdf")
.. figure:: dominator_tree-cfg.png
:align: center
:width: 30%
Directed graph (gray edges) and its dominator tree from vertex 0
(red edges, from every immediate dominator to the vertices it
dominates).
References
----------
.. [dominator-bgl] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/utility/lengauer_tarjan_dominator.html
"""
if dom_map is None:
dom_map = g.new_vertex_property("int32_t")
if dom_map.value_type() != "int32_t":
raise ValueError("vertex property 'dom_map' must be of value type" +
" int32_t.")
if not g.is_directed():
raise ValueError("dominator tree requires a directed graph.")
reach = label_out_component(g, root)
u = GraphView(g, vfilt=reach)
libgraph_tool_structure.\
dominator_tree(u, int(root),
dom_map)
return dom_map
[docs]
def topological_sort(g, lexicographic=False, key=None):
r"""
Return the topological sort of the given graph. It is returned as an array
of vertex indices, in the sort order.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. It must be a directed acyclic graph (DAG).
lexicographic : ``bool`` (optional, default: ``False``)
If ``True``, the lexicographically smallest topological sort is
returned (see below).
key : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Scalar vertex priorities for the lexicographic sort, which is implied
if this is given. If not given, the vertex indices are used.
Returns
-------
sort : :class:`numpy.ndarray`
Array of vertex indices in topological order.
See Also
--------
all_topological_sorts: All topological orderings
topological_generations: Topological generation of every vertex
is_DAG: Test for directed acyclic graphs
dag_longest_path: Longest path of a directed acyclic graph
Notes
-----
The topological sort algorithm creates a linear ordering of the vertices
such that if edge (u,v) appears in the graph, then u comes before v in the
ordering. The graph must be a directed acyclic graph (DAG).
The time complexity is :math:`O(V + E)`.
With ``lexicographic == True``, the sort is obtained with Kahn's
algorithm [kahn-topological-1962]_, where among the vertices whose
predecessors have all been placed the one with the smallest key (and the
smallest index among equal keys) is placed next. This takes time
:math:`O((V + E)\log V)`.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> g = gt.random_graph(30, lambda: (3, 3))
>>> tree = gt.minimum_spanning_tree(g)
>>> g.set_edge_filter(tree)
>>> sort = gt.topological_sort(g)
>>> print(sort)
[28 27 29 26 25 24 22 21 20 19 18 16 15 14 13 11 9 8 7 3 2 10 4 17
5 1 0 12 23 6]
>>> print(gt.topological_sort(g, lexicographic=True))
[20 15 25 0 8 13 23 6 26 2 10 4 17 5 21 28 7 11 27 14 3 29 12 22
1 19 16 18 9 24]
A topological ordering can be visualized by placing the vertices of a
directed acyclic graph along the horizontal axis in its order, and
along the vertical axis in their topological generations (see
:func:`~graph_tool.structure.topological_generations`), so that every
edge points to the right:
.. testcode::
:hide:
gt.seed_rng(42)
np.random.seed(42)
>>> es = [(i, j) for i in range(12) for j in range(i + 1, 12)
... if np.random.random() < .25]
>>> g = gt.Graph(es)
>>> sort = gt.topological_sort(g)
>>> rank = g.new_vp("int")
>>> rank.a[sort] = np.arange(g.num_vertices())
>>> gen = gt.topological_generations(g)
>>> pos = g.new_vp("vector<double>",
... vals=np.array([rank.a, 3 * gen.a]).T)
>>> gt.graph_draw(g, pos, vertex_text=g.vertex_index,
... vertex_fill_color="#cccccc", edge_color="#999999",
... vertex_size=30, output="topological_sort-dag.pdf")
<...>
.. testcleanup::
conv_png("topological_sort-dag.pdf")
.. figure:: topological_sort-dag.png
:align: center
:width: 70%
Topological ordering of a random directed acyclic graph, with the
vertices placed horizontally in the order and vertically by their
topological generation.
References
----------
.. [kahn-topological-1962] Arthur B. Kahn, "Topological sorting of large
networks", Communications of the ACM 5, 558-562 (1962),
:doi:`10.1145/368996.369025`
.. [topological-boost] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/topological_sort/topological_sort.html
.. [topological-wiki] http://en.wikipedia.org/wiki/Topological_sorting
"""
if lexicographic or key is not None:
if not g.is_directed():
raise ValueError("Graph is not a directed acylic graph (DAG).")
if key is not None:
_check_prop_scalar(key, "key")
try:
return libgraph_tool_structure.\
lexicographic_topological_sort(g, key)
except ValueError:
raise ValueError("Graph is not a directed acylic graph (DAG).")
topological_order = Vector_int32_t()
is_DAG = libgraph_tool_structure.\
topological_sort(g, topological_order)
if not is_DAG:
raise ValueError("Graph is not a directed acylic graph (DAG).");
return topological_order.a[::-1].copy()
[docs]
def transitive_closure(g, reflexive=False):
"""Return the transitive closure graph of g.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed graph to be used.
reflexive : ``bool`` or ``None`` (optional, default: ``False``)
If ``True``, every vertex gets a self-loop; if ``None``, no vertex
does; if ``False``, only the vertices on a cycle do.
Returns
-------
tc : :class:`~graph_tool.Graph`
The transitive closure graph.
See Also
--------
transitive_reduction: Inverse operation for directed acyclic graphs
count_reachable: Number of vertices reachable from every vertex
label_out_component: Vertices reachable from a given vertex
Notes
-----
The transitive closure of a graph G = (V,E) is a graph G* = (V,E*) such that
E* contains an edge (u,v) if and only if G contains a path (of at least one
edge) from u to v. The transitive_closure() function transforms the input
graph g into the transitive closure graph tc. Hence, a vertex has a
self-loop in tc if and only if it lies on a cycle, unless ``reflexive``
is ``True`` (the reflexive transitive closure, where every vertex has a
self-loop) or ``None`` (where none has).
The time complexity (worst-case) is :math:`O(VE)`.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> g = gt.random_graph(30, lambda: (3, 3))
>>> tc = gt.transitive_closure(g)
>>> print(tc.num_edges(), gt.transitive_closure(g, reflexive=None).num_edges())
900 870
For a small directed acyclic graph, the edges added by the closure can
be shown in a drawing:
>>> g = gt.Graph([(0, 1), (1, 2), (2, 3), (1, 4), (4, 3)])
>>> tc = gt.transitive_closure(g, reflexive=None)
>>> new = tc.new_ep("bool")
>>> for e in tc.edges():
... new[e] = g.edge(e.source(), e.target()) is None
>>> ecolor = tc.new_ep("string", vals=np.where(new.a, "#e41a1c",
... "#999999"))
>>> pos = tc.new_vp("vector<double>", vals=[(0, 0), (1, 1), (2.5, 1.5),
... (3, 0), (1.5, -1)])
>>> gt.graph_draw(tc, pos, vertex_text=tc.vertex_index,
... vertex_fill_color="#cccccc", edge_color=ecolor,
... vertex_size=25, edge_pen_width=2,
... output="transitive_closure-dag.pdf")
<...>
.. testcleanup::
conv_png("transitive_closure-dag.pdf")
.. figure:: transitive_closure-dag.png
:align: center
:width: 40%
Transitive closure of a directed acyclic graph of five vertices. The
edges of the original graph are shown in gray, and those added by the
closure in red.
References
----------
.. [transitive-boost] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/utility/transitive_closure.html
.. [transitive-wiki] http://en.wikipedia.org/wiki/Transitive_closure
"""
if not g.is_directed():
raise ValueError("graph must be directed for transitive closure.")
tg = Graph()
libgraph_tool_structure.transitive_closure(g,
tg,
{True: 1, False: 0,
None: -1}[reflexive])
# the closure is a relation, but parallel self-loops of the original graph
# are copied as they are
remove_parallel_edges(tg)
return tg
[docs]
@_check_props(v=("vprop",))
def label_components(g, vprop=None, directed=None, attractors=False):
"""
Label the components to which each vertex in the graph belongs. If the
graph is directed, it finds the strongly connected components.
A property map with the component labels is returned, together with a
histogram of component labels.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
vprop : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex property to store the component labels. If none is supplied, one
is created.
directed : bool (optional, default: ``None``)
Treat graph as directed or not, independently of its actual
directionality.
attractors : bool (optional, default: ``False``)
If ``True``, and the graph is directed, an additional array with Boolean
values is returned, specifying if the strongly connected components are
attractors or not.
Returns
-------
comp : :class:`~graph_tool.VertexPropertyMap`
Vertex property map with component labels.
hist : :class:`numpy.ndarray`
Histogram of component labels.
is_attractor : :class:`numpy.ndarray`
A Boolean array specifying if the strongly connected components are
attractors or not. This is returned only if ``attractors == True``, and
the graph is directed.
See Also
--------
label_largest_component: Label the largest component
extract_largest_component: Extract the largest component
label_biconnected_components: Biconnected components
label_out_component: Vertices reachable from a given vertex
count_reachable: Number of vertices reachable from every vertex
Notes
-----
The components are arbitrarily labeled from 0 to N-1, where N is the total
number of components.
The algorithm runs in :math:`O(V + E)` time.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(43)
gt.seed_rng(43)
>>> g = gt.random_graph(100, lambda: (poisson(2), poisson(2)))
>>> comp, hist, is_attractor = gt.label_components(g, attractors=True)
>>> print(comp.a)
[12 12 4 12 12 13 16 12 12 12 12 17 12 12 12 12 12 12 12 7 14 12 12 18
19 12 20 12 12 21 12 11 12 22 12 12 12 1 23 12 10 12 24 12 3 12 9 6
12 12 12 12 12 0 5 12 12 25 8 12 12 2 26 15 12 12 12 12 27 12 12 12
12 12 12 12 28 29 12 12 12 12 12 12 12 30 12 31 12 12 12 32 33 12 12 12
12 12 12 12]
>>> print(hist)
[ 1 1 1 1 1 1 1 1 1 1 1 1 67 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1]
>>> print(is_attractor)
[ True True True False True True True True True True True True
False True True False False False False False False False False False
False False True False False False False False False False]
The largest component and the attractors can be shown in a drawing of
the graph:
.. testcode::
:hide:
gt.seed_rng(42)
>>> pos = gt.sfdp_layout(g)
>>> vcolor = g.new_vp("string",
... vals=np.where(comp.a == hist.argmax(), "#f28c8e",
... np.where(is_attractor[comp.a],
... "#9bbedc", "#cccccc")))
>>> gt.graph_draw(g, pos, vertex_fill_color=vcolor, edge_color="#999999",
... output="label_components-random.pdf")
<...>
.. testcleanup::
conv_png("label_components-random.pdf")
.. figure:: label_components-random.png
:align: center
:width: 50%
Strongly connected components of a directed random graph. The
largest component is shown in red, the other attractors in blue, and
the remaining vertices in gray.
"""
if vprop is None:
vprop = g.new_vertex_property("int32_t")
_check_prop_writable(vprop, name="vprop")
_check_prop_scalar(vprop, name="vprop")
if directed is not None:
g = GraphView(g, directed=directed)
hist = libgraph_tool_structure.\
label_components(g, vprop)
if attractors and g.is_directed() and directed != False:
is_attractor = numpy.ones(len(hist), dtype="bool")
libgraph_tool_structure.\
label_attractors(g, vprop,
is_attractor)
return vprop, hist, is_attractor
else:
return vprop, hist
[docs]
def label_largest_component(g, directed=None):
"""
Label the largest component in the graph. If the graph is directed, then the
largest strongly connected component is labelled.
A property map with a boolean label is returned.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
directed : bool (optional, default: ``None``)
Treat graph as directed or not, independently of its actual
directionality.
Returns
-------
comp : :class:`~graph_tool.VertexPropertyMap`
Boolean vertex property map which labels the largest component.
See Also
--------
label_components: Connected components
extract_largest_component: Extract the largest component
vertex_percolation: Size of the largest component as vertices are removed
Notes
-----
The algorithm runs in :math:`O(V + E)` time.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> g = gt.random_graph(100, lambda: poisson(1), directed=False)
>>> l = gt.label_largest_component(g)
>>> print(l.a)
[0 1 0 0 1 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 1 0 1 0 0 1 0 1 0 1 0 0 0 0 1 1 0
1 0 1 0 1 0 0 0 0 0 0 0 1 0 1 1 0 0 0 1 1 1 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 1 0 0 0]
>>> u = gt.GraphView(g, vfilt=l) # extract the largest component as a graph
>>> print(u.num_vertices())
28
The largest component can be highlighted in a drawing of the graph:
.. testcode::
:hide:
gt.seed_rng(42)
>>> pos = gt.sfdp_layout(g)
>>> vcolor = g.new_vp("string", vals=np.where(l.a, "#f28c8e", "#cccccc"))
>>> gt.graph_draw(g, pos, vertex_fill_color=vcolor, edge_color="#999999",
... output="label_largest_component-random.pdf")
<...>
.. testcleanup::
conv_png("label_largest_component-random.pdf")
.. figure:: label_largest_component-random.png
:align: center
:width: 50%
Largest component (in red) of a sparse random graph.
"""
label = g.new_vertex_property("bool")
c, h = label_components(g, directed=directed)
label.fa = c.fa == h.argmax()
return label
[docs]
@_check_props(v=("label",))
def label_out_component(g, root, label=None):
"""
Label the out-component (or simply the component for undirected graphs) of a
root vertex.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
root : :class:`~graph_tool.Vertex`
The root vertex.
label : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, this must be an initialized Boolean vertex property map
where the out-component will be labeled.
Returns
-------
label : :class:`~graph_tool.VertexPropertyMap`
Boolean vertex property map which labels the out-component.
See Also
--------
label_components: Connected components
count_reachable: Number of vertices reachable from every vertex
ego_graph: Subgraph within a given distance of a vertex
shortest_distance: Distances from a source vertex
Notes
-----
The algorithm runs in :math:`O(V + E)` time.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> g = gt.random_graph(100, lambda: poisson(2.2), directed=False)
>>> l = gt.label_out_component(g, g.vertex(2))
>>> print(l.a)
[1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 0 0 1 0 1 0
1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1
1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 1 0]
The in-component can be obtained by reversing the graph.
>>> l = gt.label_out_component(gt.GraphView(g, reversed=True, directed=True),
... g.vertex(1))
>>> print(l.a)
[0 1 1 0 0 1 0 0 0 1 1 0 1 0 0 0 0 1 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 0 0 1 0
1 1 0 0 0 1 1 1 1 0 1 1 1 1 1 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 1 0 1 0 0 0
0 1 0 1 0 1 0 0 1 0 1 1 1 1 0 1 0 0 0 1 0 0 1 0 0 0]
In a directed graph, the out-component contains the vertices reachable
from the given one, as shown for a Price network, whose edges point
from newer to older vertices:
.. testcode::
:hide:
gt.seed_rng(42)
>>> g = gt.price_network(60, m=2)
>>> l = gt.label_out_component(g, g.vertex(59))
>>> pos = gt.sfdp_layout(g)
>>> vcolor = g.new_vp("string", vals=np.where(l.a, "#f28c8e", "#cccccc"))
>>> vcolor[59] = "#9bbedc"
>>> gt.graph_draw(g, pos, vertex_fill_color=vcolor, edge_color="#999999",
... output="label_out_component-price.pdf")
<...>
.. testcleanup::
conv_png("label_out_component-price.pdf")
.. figure:: label_out_component-price.png
:align: center
:width: 50%
Out-component (in red) of the vertex shown in blue in a Price network
of 60 vertices.
"""
if label is None:
label = g.new_vertex_property("bool")
elif label.value_type() != "bool":
raise ValueError("value type of `label` must be `bool`, not %s" %
label.value_type())
libgraph_tool_structure.\
label_out_component(g, int(root),
label)
return label
[docs]
@_check_props(v=("vprop",), e=("eprop",))
def label_biconnected_components(g, eprop=None, vprop=None):
"""
Label the edges of biconnected components, and the vertices which are
articulation points.
An edge property map with the component labels is returned, together with
a boolean vertex map marking the articulation points, and a histogram of
component labels.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
eprop : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge property to label the biconnected components.
vprop : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex property to mark the articulation points. If none is supplied,
one is created.
Returns
-------
bicomp : :class:`~graph_tool.EdgePropertyMap`
Edge property map with the biconnected component labels.
articulation : :class:`~graph_tool.VertexPropertyMap`
Boolean vertex property map which has value 1 for each vertex which is
an articulation point, and zero otherwise.
hist : :class:`numpy.ndarray`
Histogram of biconnected component labels.
See Also
--------
label_components: Connected components
find_bridges: Bridges of a graph
chain_decomposition: Chain decomposition of a graph
Notes
-----
A connected graph is biconnected if the removal of any single vertex (and
all edges incident on that vertex) can not disconnect the graph. More
generally, the biconnected components of a graph are the maximal subsets of
vertices such that the removal of a vertex from a particular component will
not disconnect the component. Unlike connected components, vertices may
belong to multiple biconnected components: those vertices that belong to
more than one biconnected component are called "articulation points" or,
equivalently, "cut vertices". Articulation points are vertices whose removal
would increase the number of connected components in the graph. Thus, a
graph without articulation points is biconnected. Vertices can be present in
multiple biconnected components, but each edge can only be contained in a
single biconnected component.
The algorithm runs in :math:`O(V + E)` time.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> g = gt.random_graph(100, lambda: poisson(2), directed=False)
>>> comp, art, hist = gt.label_biconnected_components(g)
>>> print(comp.a)
[31 31 31 0 31 31 31 31 31 15 27 31 28 31 31 14 31 31 31 31 3 31 31 31
32 31 31 19 16 29 20 31 31 31 31 31 31 31 31 31 31 31 31 10 24 31 4 8
22 31 31 31 31 2 31 31 31 31 31 18 31 31 31 31 31 11 21 23 1 31 31 30
7 31 31 31 25 31 31 31 31 31 31 6 26 17 31 31 31 13 31 31 31 12 9 31
31 31 31 5 31 31 31]
>>> print(art.a)
[1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 0 1 0 0 0 0 0 1 1 0 0 0 1 0 1 0 0 0 0 0 0
1 0 1 0 0 0 0 0 0 1 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 0 1 1 0
1 0 0 1 0 1 0 0 1 0 0 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0]
>>> print(hist)
[ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 71 1]
The largest biconnected component and the articulation points can be
shown in a drawing of the graph:
.. testcode::
:hide:
gt.seed_rng(42)
>>> pos = gt.sfdp_layout(g)
>>> vcolor = g.new_vp("string", vals=np.where(art.a, "#9bbedc",
... "#cccccc"))
>>> big = comp.a == hist.argmax()
>>> ecolor = g.new_ep("string", vals=np.where(big, "#e41a1c", "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(big, 2, 1))
>>> gt.graph_draw(g, pos, vertex_fill_color=vcolor, edge_color=ecolor,
... edge_pen_width=ewidth,
... output="label_biconnected_components-random.pdf")
<...>
.. testcleanup::
conv_png("label_biconnected_components-random.pdf")
.. figure:: label_biconnected_components-random.png
:align: center
:width: 50%
Biconnected components of a sparse random graph. The edges of the
largest biconnected component are shown in red, and the articulation
points in blue.
"""
if vprop is None:
vprop = g.new_vertex_property("bool")
if eprop is None:
eprop = g.new_edge_property("int32_t")
_check_prop_writable(vprop, name="vprop")
_check_prop_scalar(vprop, name="vprop")
_check_prop_writable(eprop, name="eprop")
_check_prop_scalar(eprop, name="eprop")
g = GraphView(g, directed=False)
hist = libgraph_tool_structure.\
label_biconnected_components(g, eprop,
vprop)
return eprop, vprop, hist
[docs]
def vertex_percolation(g, vertices, second=False):
"""Compute the size of the largest or second-largest component as vertices
are (virtually) removed from the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
vertices : :class:`numpy.ndarray` or iterable of ints
List of vertices in reversed order of removal.
second : bool (optional, default: ``False``)
If ``True``, the size of the second-largest component will be computed.
Returns
-------
size : :class:`numpy.ndarray`
Size of the largest (or second-largest) component prior to removal of
each vertex.
comp : :class:`~graph_tool.VertexPropertyMap`
Vertex property map with component labels.
See Also
--------
edge_percolation: Size of the largest component as edges are removed
label_largest_component: Label the largest component
label_components: Connected components
Notes
-----
The algorithm runs in :math:`O(V + E)` time.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> g = gt.random_graph(10000, lambda: geometric(1./4) + 1, directed=False)
>>> vertices = sorted([v for v in g.vertices()], key=lambda v: v.out_degree())
>>> sizes, comp = gt.vertex_percolation(g, vertices)
>>> numpy.random.shuffle(vertices)
>>> sizes2, comp = gt.vertex_percolation(g, vertices)
>>> figure()
<...>
>>> plot(sizes, label="Targeted")
[...]
>>> plot(sizes2, label="Random")
[...]
>>> xlabel("Vertices remaining")
Text(...)
>>> ylabel("Size of largest component")
Text(...)
>>> legend(loc="upper left")
<...>
>>> savefig("vertex-percolation.svg")
.. figure:: vertex-percolation.*
:align: center
Targeted and random vertex percolation of a random graph with an
exponential degree distribution.
References
----------
.. [newman-ziff] M. E. J. Newman, R. M. Ziff, "A fast Monte Carlo algorithm
for site or bond percolation", Phys. Rev. E 64, 016706 (2001)
:doi:`10.1103/PhysRevE.64.016706`, :arxiv:`cond-mat/0101295`
"""
vertices = numpy.asarray(vertices, dtype="uint64")
tree = g.vertex_index.copy("int64_t")
size = g.new_vertex_property("int64_t", 1)
visited = g.new_vertex_property("bool", False)
max_size = numpy.zeros(len(vertices), dtype="uint64")
u = GraphView(g, directed=False)
libgraph_tool_structure.\
percolate_vertex(u,
tree,
size,
visited,
vertices, max_size, second)
return max_size, tree
[docs]
def edge_percolation(g, edges, second=False):
"""Compute the size of the largest or second-largest component as edges are
(virtually) removed from the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
edges : :class:`numpy.ndarray` or iterable of pairs of ints
List of edges in reversed order of removal. If the type is
:class:`numpy.ndarray`, it should have a shape ``(E, 2)``, where ``E``
is the number of edges, such that ``edges[i,0]`` and ``edges[i,1]`` are
both endpoints of edge ``i``.
second : bool (optional, default: ``False``)
If ``True``, the size of the second-largest component will be computed.
Returns
-------
size : :class:`numpy.ndarray`
Size of the largest (or second-largest) component prior to removal of
each edge.
comp : :class:`~graph_tool.VertexPropertyMap`
Vertex property map with component labels.
See Also
--------
vertex_percolation: Size of the largest component as vertices are removed
label_largest_component: Label the largest component
label_components: Connected components
Notes
-----
The algorithm runs in :math:`O(E)` time.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> g = gt.random_graph(10000, lambda: geometric(1./4) + 1, directed=False)
>>> edges = sorted([(e.source(), e.target()) for e in g.edges()],
... key=lambda e: e[0].out_degree() * e[1].out_degree())
>>> sizes, comp = gt.edge_percolation(g, edges)
>>> numpy.random.shuffle(edges)
>>> sizes2, comp = gt.edge_percolation(g, edges)
>>> figure()
<...>
>>> plot(sizes, label="Targeted")
[...]
>>> plot(sizes2, label="Random")
[...]
>>> xlabel("Edges remaining")
Text(...)
>>> ylabel("Size of largest component")
Text(...)
>>> legend(loc="lower right")
<...>
>>> savefig("edge-percolation.svg")
.. figure:: edge-percolation.*
:align: center
Targeted and random edge percolation of a random graph with an
exponential degree distribution.
References
----------
.. [newman-ziff] M. E. J. Newman, R. M. Ziff, "A fast Monte Carlo algorithm
for site or bond percolation", Phys. Rev. E 64, 016706 (2001)
:doi:`10.1103/PhysRevE.64.016706`, :arxiv:`cond-mat/0101295`
"""
edges = numpy.asarray(edges, dtype="uint64")
tree = g.vertex_index.copy("int64_t")
size = g.new_vertex_property("int64_t", 1)
max_size = numpy.zeros(len(edges), dtype="uint64")
u = GraphView(g, directed=False)
libgraph_tool_structure.\
percolate_edge(u,
tree,
size,
edges, max_size, second)
return max_size, tree
def _degree_mode(mode):
modes = {"total": 0, "in": 1, "out": 2}
if mode not in modes:
raise ValueError(f"invalid degree mode: {mode}")
return modes[mode]
[docs]
@_check_props(v=("vprop",))
def kcore_decomposition(g, vprop=None, mode="total"):
"""Perform a k-core decomposition of the given graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
vprop : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex property to store the decomposition. If ``None`` is supplied,
one is created.
mode : ``str`` (optional, default: ``"total"``)
For directed graphs, the degree used in the decomposition: ``"total"``,
``"in"``, or ``"out"``.
Returns
-------
kval : :class:`~graph_tool.VertexPropertyMap`
Vertex property map with the k-core decomposition, i.e. a given vertex v
belongs to the ``kval[v]``-core.
See Also
--------
kcore_subgraph: K-core, k-shell, k-crust, or k-corona as a subgraph
onion_decomposition: Refinement of the k-core decomposition into layers
truss_decomposition: Edge counterpart based on triangles
Notes
-----
The k-core is a maximal set of vertices such that its induced subgraph only
contains vertices with degree larger than or equal to k.
For directed graphs, the degree is the total (in + out) degree by
default, or the in- or out-degree according to ``mode``. For the
in-degree, the removal of a vertex lowers the in-degrees of its
out-neighbors, and analogously for the out-degree.
The algorithm accepts graphs with parallel edges and self loops, in which
case these edges contribute to the degree in the usual fashion.
This algorithm is described in [batagelj-algorithm]_ and runs in :math:`O(V + E)`
time.
Examples
--------
>>> g = gt.collection.data["netscience"]
>>> g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
>>> kcore = gt.kcore_decomposition(g)
>>> gt.graph_draw(g, pos=g.vp["pos"], vertex_fill_color=kcore, vertex_text=kcore, output="netsci-kcore.svg")
<...>
.. figure:: netsci-kcore.svg
:align: center
:width: 80%
K-core decomposition of a network of network scientists.
References
----------
.. [k-core] http://en.wikipedia.org/wiki/Degeneracy_%28graph_theory%29
.. [batagelj-algorithm] Vladimir Batagelj, Matjaž Zaveršnik, "Fast
algorithms for determining (generalized) core groups in social
networks", Advances in Data Analysis and Classification
Volume 5, Issue 2, pp 129-145 (2011), :DOI:`10.1007/s11634-010-0079-y`,
:arxiv:`cs/0310049`
"""
if vprop is None:
vprop = g.new_vertex_property("int32_t")
_check_prop_writable(vprop, name="vprop")
_check_prop_scalar(vprop, name="vprop")
libgraph_tool_structure.\
kcore_decomposition(g, vprop, _degree_mode(mode))
return vprop
[docs]
def onion_decomposition(g, mode="total"):
r"""Perform the onion decomposition of the given graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
mode : ``str`` (optional, default: ``"total"``)
For directed graphs, the degree used in the decomposition: ``"total"``,
``"in"``, or ``"out"``.
Returns
-------
core : :class:`~graph_tool.VertexPropertyMap`
The k-core of every vertex, as given by
:func:`~graph_tool.structure.kcore_decomposition`.
layer : :class:`~graph_tool.VertexPropertyMap`
The layer of every vertex, numbered from one.
See Also
--------
kcore_decomposition: K-core decomposition
kcore_subgraph: K-core, k-shell, k-crust, or k-corona as a subgraph
truss_decomposition: Edge counterpart based on triangles
Notes
-----
The onion decomposition [hebert-dufresne-multi-scale-2016]_ refines the
`k-core decomposition <https://en.wikipedia.org/wiki/Degeneracy_(graph_theory)>`_
by removing the vertices in rounds. Starting with
:math:`k` equal to the smallest degree, in every round all the remaining
vertices whose degree in the remaining graph is at most :math:`k` are
removed simultaneously, receive the core number :math:`k`, and form a new
layer; when no remaining vertex has degree at most :math:`k`, :math:`k`
is increased to the smallest remaining degree. The layers are thus
numbered consecutively over all the cores, so that the vertices of a
layer belong to the same core, and the layers of higher cores have higher
numbers.
The algorithm runs in :math:`O(V + E)` time.
Examples
--------
>>> g = gt.collection.data["netscience"]
>>> core, layer = gt.onion_decomposition(g)
>>> print(core.a.max(), layer.a.max())
19 26
The layers can be visualized by coloring the vertices, here of the
largest component:
>>> from matplotlib.colors import LinearSegmentedColormap
>>> cmap = LinearSegmentedColormap.from_list("layer", ["#d9d9d9",
... "#7dabd1"])
>>> u = gt.extract_largest_component(g)
>>> gt.graph_draw(u, g.vp.pos, vertex_fill_color=layer.copy("double"),
... vcmap=cmap,
... edge_color="#999999",
... output="onion_decomposition-netsci.pdf")
<...>
.. testcleanup::
conv_png("onion_decomposition-netsci.pdf")
.. figure:: onion_decomposition-netsci.png
:align: center
:width: 80%
Onion decomposition of the network of coauthorships in network
science, shown for its largest component. The colors of the vertices
range from gray (first layer) to blue (last layer).
References
----------
.. [hebert-dufresne-multi-scale-2016] Laurent Hébert-Dufresne, Joshua A.
Grochow and Antoine Allard, "Multi-scale structure and topological
anomaly detection via a new network statistic: The onion
decomposition", Scientific Reports 6, 31708 (2016),
:DOI:`10.1038/srep31708`, :arxiv:`1510.08542`
"""
core = g.new_vp("int64_t")
layer = g.new_vp("int64_t")
libgraph_tool_structure.onion_decomposition(g,
core,
layer,
_degree_mode(mode))
return core, layer
def _dist_value_type(weights):
"""Return the value type of the distances accumulated from the edge
``weights``: integer and Boolean weights are summed as ``int64_t``, to
avoid overflows and to count Boolean weights as integers."""
if weights is None:
return "int32_t"
t = weights.value_type()
if t in ["bool", "uint8_t", "int16_t", "int32_t", "int64_t"]:
return "int64_t"
return t
[docs]
def truss_decomposition(g, eprop=None):
r"""Perform a k-truss decomposition of the given graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. If it is directed, it is treated as undirected.
eprop : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge property map where the trussness values will be stored, of type
``int32_t``.
Returns
-------
eprop : :class:`~graph_tool.EdgePropertyMap`
Edge property map with the trussness of each edge.
See Also
--------
kcore_decomposition: Vertex counterpart based on degrees
onion_decomposition: Refinement of the k-core decomposition into layers
graph_tool.clustering.edge_clustering: Number of triangles of every edge
Notes
-----
The :math:`k`-truss of a graph is its largest subgraph in which every edge
belongs to at least :math:`k-2` triangles of the subgraph
[cohen-trusses-2008]_. The trussness of an edge is the largest :math:`k`
such that the edge belongs to the :math:`k`-truss; edges that belong to
no triangle have trussness 2. Since a :math:`k`-truss is a
:math:`(k-1)`-core (see :func:`kcore_decomposition`), the decomposition
finds cohesive subgraphs at a finer level than the cores.
Parallel edges are treated as a single edge (and receive the same
value), and self-loops receive the value zero.
The algorithm of [wang-truss-2012]_ is used, which removes the edges in
increasing order of the number of triangles they belong to, and runs in
time :math:`O(E^{3/2})`.
Examples
--------
>>> g = gt.collection.data["football"]
>>> truss = gt.truss_decomposition(g)
>>> print(np.bincount(truss.fa))
[ 0 0 96 88 39 0 157 65 96 72]
The trussness can be visualized by coloring the edges:
>>> from matplotlib.colors import LinearSegmentedColormap
>>> cmap = LinearSegmentedColormap.from_list("truss", ["#d9d9d9",
... "#e41a1c"])
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color="#cccccc",
... edge_color=truss.copy("double"), ecmap=cmap,
... eorder=truss, edge_pen_width=1.5,
... output="truss_decomposition-football.pdf")
<...>
.. testcleanup::
conv_png("truss_decomposition-football.pdf")
.. figure:: truss_decomposition-football.png
:align: center
:width: 60%
Truss decomposition of the network of American college football
games. The colors of the edges range from gray (trussness 2) to red
(trussness 9).
References
----------
.. [cohen-trusses-2008] Jonathan Cohen, "Trusses: Cohesive subgraphs for
social network analysis", National Security Agency technical report
(2008).
.. [wang-truss-2012] Jia Wang and James Cheng, "Truss decomposition in
massive networks", Proceedings of the VLDB Endowment 5, 812-823
(2012), :doi:`10.14778/2311906.2311909`, :arxiv:`1205.6693`
"""
if eprop is None:
eprop = g.new_edge_property("int32_t")
_check_prop_writable(eprop, name="eprop")
if eprop.value_type() != "int32_t":
raise ValueError("eprop must be of type 'int32_t'")
u = GraphView(g, directed=False)
libgraph_tool_structure.truss_decomposition(u, u.own_property(eprop))
return eprop
[docs]
@_check_props(v=("dist_map", "pred_map"), e=("weights",))
def shortest_distance(g, source=None, target=None, weights=None,
negative_weights=False, max_dist=None, directed=None,
dense=False, dist_map=None, pred_map=False,
return_reached=False, dag=False):
r"""Calculate the distance from a source to a target vertex, or to all
vertices from a given source, or the all pairs shortest paths, if the source
is not specified.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex` (optional, default: ``None``)
Source vertex of the search. If unspecified, the all pairs shortest
distances are computed.
target : :class:`~graph_tool.Vertex` or iterable of such objects (optional, default: ``None``)
Target vertex (or vertices) of the search. If unspecified, the distance
to all vertices from the source will be computed.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
The edge weights. If provided, the shortest path will correspond to the
minimal sum of weights.
negative_weights : ``bool`` (optional, default: ``False``)
If ``True``, this will trigger the use of the Bellman-Ford algorithm.
Ignored if ``source`` is ``None``.
max_dist : scalar value (optional, default: ``None``)
If specified, this limits the maximum distance of the vertices
searched. This parameter has no effect if source is ``None``, or if
``negative_weights=True``.
directed : ``bool`` (optional, default: ``None``)
Treat graph as directed or not, independently of its actual
directionality.
dense : ``bool`` (optional, default: ``False``)
If ``True``, and source is ``None``, the Floyd-Warshall algorithm is used,
otherwise the Johnson algorithm is used. If source is not ``None``, or
if ``weights`` is ``None``, this option has no effect.
dist_map : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex property to store the distances. If none is supplied, one
is created, with value type ``int32_t`` if ``weights`` is ``None``,
``int64_t`` if the weights are integer or Boolean, and otherwise the
value type of the weights.
.. warning::
If this parameter is supplied, the user is responsible for
initializing it to infinity. This can be done as:
>>> dist_map = g.new_vp("double", numpy.inf) # doctest: +SKIP
or
>>> dist_map = g.new_vp("int32_t", numpy.iinfo(numpy.int32).max) # doctest: +SKIP
depending on the distance type.
pred_map : ``bool`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``False``)
If ``True``, a vertex property map with the predecessors is returned.
If a :class:`~graph_tool.VertexPropertyMap` is passed, it must be of value
type ``int64_t`` and it will be used to store the predecessors. Ignored
if ``source`` is ``None``.
.. warning::
If a property map is supplied, the user is responsible for
initializing to the identity map. This can be done as:
>>> pred_map = g.vertex_index.copy() # doctest: +SKIP
return_reached : ``bool`` (optional, default: ``False``)
If ``True``, return an array of visited vertices.
dag : ``bool`` (optional, default: ``False``)
If ``True``, assume that the graph is a Directed Acyclic Graph (DAG),
which will be faster if ``weights`` are given, in which case they are
also allowed to contain negative values (irrespective of the parameter
``negative_weights``). Ignored if ``source`` is ``None``.
Returns
-------
dist_map : :class:`~graph_tool.VertexPropertyMap` or :class:`numpy.ndarray` or scalar
Vertex property map with the distances from source. If ``source`` is
``None``, it will have a vector value type, with the distances to every
vertex. If ``target`` is an iterable, instead of
:class:`~graph_tool.VertexPropertyMap`, this will be of type
:class:`numpy.ndarray`, and contain only the distances to those specific
targets. If a single source and a single target are specified, a single
scalar will be returned.
pred_map : :class:`~graph_tool.VertexPropertyMap` (optional, if ``pred_map == True``)
Vertex property map with the predecessors in the search tree.
visited : :class:`numpy.ndarray` (optional, if ``return_reached == True``)
Array containing vertices visited during the search.
See Also
--------
shortest_path: Shortest path between two vertices
all_shortest_paths: All shortest paths between two vertices
count_shortest_paths: Number of shortest paths between two vertices
eccentricity: Eccentricity of every vertex
widest_distance: Width of the widest paths from a source vertex
Notes
-----
If a source is given, the distances are calculated with a breadth-first
search (BFS) or Dijkstra's algorithm [dijkstra]_, if weights are given. If
``negative_weights == True``, the Bellman-Ford algorithm is used
[bellman-ford]_, which accepts negative weights, as long as there are no
negative loops. If source is not given, the distances are calculated with
a BFS from every vertex, or, if weights are given, with Johnson's
algorithm [johnson-apsp]_, which runs Dijkstra's algorithm from every
vertex, after the weights are made non-negative with potentials obtained
with the Bellman-Ford algorithm, if some of them are negative. If
``dense=True``, the Floyd-Warshall algorithm [floyd-warshall-apsp]_ is
used instead, which is comparable in speed only for very dense graphs
and much slower for sparse ones. In both cases, a
:class:`ValueError` is raised if the graph contains a cycle of negative
total weight.
If a single target is given, and neither ``negative_weights``, ``dag``
nor ``return_reached`` is ``True``, the search proceeds alternately from
the source and, along the reversed edges, from the target, until both
searches meet [pohl-bidirectional]_. This reduces the number of vertices
visited, in particular in networks with a small diameter. In this case,
``dist_map`` and ``pred_map`` contain the values for the vertices reached
by the search from the source and for the vertices of the path, and the
remaining entries are left unchanged.
If there is no path between two vertices, the computed distance will
correspond to the maximum value allowed by the value type of ``dist_map``,
or ``inf`` in case of floating point types.
If source is specified, the algorithm runs in :math:`O(V + E)` time, or
:math:`O(V \log V)` if weights are given (if ``dag == True`` this improves
to :math:`O(V+E)`). If ``negative_weights == True``, the complexity is
:math:`O(VE)`. If source is not specified, the algorithm runs in parallel
with complexity :math:`O(V (V + E))`, if weights are given it runs
in :math:`O(VE\log V)` time (plus :math:`O(VE)` for the Bellman-Ford
algorithm, which is not parallel, if there are negative weights), or
:math:`O(V^3)` if ``dense=True``.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> from numpy.random import poisson
>>> g = gt.random_graph(100, lambda: (poisson(3), poisson(3)))
>>> dist = gt.shortest_distance(g, source=g.vertex(0))
>>> print(dist.a)
[ 0 4 5 4 6 4
5 5 2 3 4 4
6 5 7 5 2147483647 4
2147483647 3 3 4 3 2
4 5 5 4 4 4
4 6 3 4 3 5
1 5 4 3 4 3
6 2147483647 4 5 3 5
6 4 5 4 4 3
3 4 6 4 2 3
4 5 4 5 4 2
5 5 3 3 2147483647 4
2147483647 7 6 3 4 4
5 4 1 2147483647 3 2
4 4 5 3 4 5
5 5 5 5 5 5
4 3 2 3]
>>>
>>> dist = gt.shortest_distance(g)
>>> print(dist[g.vertex(0)].a)
[ 0 4 5 4 6 4
5 5 2 3 4 4
6 5 7 5 2147483647 4
2147483647 3 3 4 3 2
4 5 5 4 4 4
4 6 3 4 3 5
1 5 4 3 4 3
6 2147483647 4 5 3 5
6 4 5 4 4 3
3 4 6 4 2 3
4 5 4 5 4 2
5 5 3 3 2147483647 4
2147483647 7 6 3 4 4
5 4 1 2147483647 3 2
4 4 5 3 4 5
5 5 5 5 5 5
4 3 2 3]
>>> dist = gt.shortest_distance(g, source=g.vertex(0), target=g.vertex(2))
>>> print(dist)
5
>>> dist = gt.shortest_distance(g, source=g.vertex(0), target=[g.vertex(2), g.vertex(6)])
>>> print(dist)
[5 5]
The distances from a vertex can be visualized by coloring the vertices
of a network with stored positions:
>>> from matplotlib.colors import LinearSegmentedColormap
>>> g = gt.collection.data["karate"]
>>> dist = gt.shortest_distance(g, source=g.vertex(16))
>>> cmap = LinearSegmentedColormap.from_list("dist", ["#ed6a6b",
... "#d9d9d9"])
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=dist, vcmap=cmap,
... vertex_text=dist, edge_color="#999999",
... output="shortest_distance-karate.pdf")
<...>
.. testcleanup::
conv_png("shortest_distance-karate.pdf")
.. figure:: shortest_distance-karate.png
:align: center
:width: 50%
Shortest-path distances from vertex 16 of Zachary's karate club
network, given by the labels and by the colors, which range from red
(distance zero) to gray (largest distance).
References
----------
.. [bfs] Edward Moore, "The shortest path through a maze", International
Symposium on the Theory of Switching (1959), Harvard University Press.
.. [bfs-boost] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/traversal/breadth_first_search.html
.. [dijkstra] E. Dijkstra, "A note on two problems in connexion with
graphs." Numerische Mathematik, 1:269-271, 1959.
.. [dijkstra-boost] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/shortest_paths/dijkstra_shortest_paths.html
.. [pohl-bidirectional] Ira Pohl, "Bi-directional search", Machine
Intelligence 6, 127-140 (1971).
.. [johnson-apsp] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/shortest_paths/johnson_all_pairs_shortest.html
.. [floyd-warshall-apsp] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/shortest_paths/floyd_warshall_shortest.html
.. [bellman-ford] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/shortest_paths/bellman_ford_shortest.html
"""
tgtlist = False
if isinstance(target, collections.abc.Iterable):
tgtlist = True
target = numpy.asarray(target, dtype="int64")
elif target is None:
target = numpy.array([], dtype="int64")
else:
target = numpy.asarray([int(g.vertex(int(target)))], dtype="int64")
dist_type = _dist_value_type(weights)
if dist_map is None:
if source is not None:
dist_map = g.new_vertex_property(dist_type)
else:
dist_map = g.new_vertex_property("vector<%s>" % dist_type)
_check_prop_writable(dist_map, name="dist_map")
if source is not None:
_check_prop_scalar(dist_map, name="dist_map")
else:
_check_prop_vector(dist_map, name="dist_map")
if max_dist is None:
max_dist = 0
if directed is not None:
u = GraphView(g, directed=directed)
else:
u = g
get_pred = pred_map is True or isinstance(pred_map, VertexPropertyMap)
if source is not None:
if numpy.issubdtype(dist_map.a.dtype, numpy.integer):
dist_map.set_value(numpy.iinfo(dist_map.a.dtype).max)
else:
dist_map.set_value(numpy.inf)
if isinstance(pred_map, PropertyMap):
pmap = pred_map
if pmap.value_type() != "int64_t":
raise ValueError("supplied pred_map must be of value type 'int64_t'")
else:
pmap = u.copy_property(u.vertex_index, value_type="int64_t")
reached = libcore.Vector_size_t()
libgraph_tool_structure.get_dists(u,
int(u.vertex(int(source))),
target,
dist_map,
weights,
pmap,
float(max_dist),
negative_weights, reached, dag,
get_pred, return_reached)
else:
libgraph_tool_structure.get_all_dists(u,
dist_map,
weights, dense)
if source is not None and len(target) > 0:
if len(target) == 1 and not tgtlist:
dist_map = dist_map.a[target[0]]
else:
dist_map = numpy.array(dist_map.a[target])
if source is not None:
if get_pred:
ret = (dist_map, pmap)
else:
ret = (dist_map,)
if return_reached:
return ret + (numpy.asarray(reached.a.copy()),)
else:
if len(ret) == 1:
return ret[0]
return ret
else:
return dist_map
[docs]
@_check_props(v=("pred_map",), e=("weights",))
def shortest_path(g, source, target, weights=None, negative_weights=False,
pred_map=None, dag=False):
r"""Return the shortest path from ``source`` to ``target``.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex`
Source vertex of the search.
target : :class:`~graph_tool.Vertex`
Target vertex of the search.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
The edge weights.
negative_weights : ``bool`` (optional, default: ``False``)
If ``True``, this will trigger the use of the Bellman-Ford algorithm.
pred_map : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex property map with the predecessors in the search tree. If this is
provided, the shortest paths are not computed, and are obtained directly
from this map.
dag : ``bool`` (optional, default: ``False``)
If ``True``, assume that the graph is a Directed Acyclic Graph (DAG),
which will be faster if ``weights`` are given, in which case they are
also allowed to contain negative values (irrespective of the parameter
``negative_weights``).
Returns
-------
vertex_list : list of :class:`~graph_tool.Vertex`
List of vertices from `source` to `target` in the shortest path.
edge_list : list of :class:`~graph_tool.Edge`
List of edges from `source` to `target` in the shortest path.
See Also
--------
shortest_distance: Distances from a source vertex
all_shortest_paths: All shortest paths between two vertices
random_shortest_path: Uniformly random shortest path
k_shortest_paths: The k shortest simple paths between two vertices
widest_path: Widest path between two vertices
Notes
-----
The paths are computed with a breadth-first search (BFS) or Dijkstra's
algorithm [dijkstra]_, if weights are given. Unless ``negative_weights``
or ``dag`` is ``True``, the search proceeds alternately from the source
and, along the reversed edges, from the target, until both searches meet
[pohl-bidirectional]_. If ``negative_weights == True``, the Bellman-Ford
algorithm is used [bellman-ford]_, which accepts negative weights, as
long as there are no negative loops.
The algorithm runs in :math:`O(V + E)` time, or :math:`O(V \log V)` if
weights are given (if ``dag == True`` this improves to :math:`O(V+E)`).
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(43)
gt.seed_rng(43)
>>> from numpy.random import poisson
>>> g = gt.random_graph(300, lambda: (poisson(4), poisson(4)))
>>> vlist, elist = gt.shortest_path(g, g.vertex(10), g.vertex(11))
>>> print([str(v) for v in vlist])
['10', '114', '96', '97', '11']
>>> print([str(e) for e in elist])
['(10, 114)', '(114, 96)', '(96, 97)', '(97, 11)']
A shortest path can be highlighted in a drawing of a network with
stored positions:
>>> g = gt.collection.data["polbooks"]
>>> d, (s, t) = gt.pseudo_diameter(g)
>>> vlist, elist = gt.shortest_path(g, s, t)
>>> onpath = g.new_ep("bool")
>>> for e in elist:
... onpath[e] = True
>>> inpath = g.new_vp("bool")
>>> for v in vlist:
... inpath[v] = True
>>> vcolor = g.new_vp("string", vals=np.where(inpath.a, "#f28c8e",
... "#cccccc"))
>>> ecolor = g.new_ep("string", vals=np.where(onpath.a, "#e41a1c",
... "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(onpath.a, 3, 1))
The path is drawn on top of all other vertices and edges by giving its
edges and vertices larger values of ``zorder``:
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color=ecolor, edge_pen_width=ewidth,
... edge_zorder=onpath.copy("double"),
... vertex_zorder=g.new_vp("double", vals=2 * inpath.a),
... output="shortest_path-polbooks.pdf")
<...>
.. testcleanup::
conv_png("shortest_path-polbooks.pdf")
.. figure:: shortest_path-polbooks.png
:align: center
:width: 50%
Shortest path between the endpoints of a pseudo-diameter of the
network of books about US politics, with its vertices and edges shown
in red.
References
----------
.. [bfs] Edward Moore, "The shortest path through a maze", International
Symposium on the Theory of Switching (1959), Harvard University
Press
.. [bfs-boost] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/traversal/breadth_first_search.html
.. [dijkstra] E. Dijkstra, "A note on two problems in connexion with
graphs." Numerische Mathematik, 1:269-271, 1959.
.. [dijkstra-boost] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/shortest_paths/dijkstra_shortest_paths.html
.. [pohl-bidirectional] Ira Pohl, "Bi-directional search", Machine
Intelligence 6, 127-140 (1971).
.. [bellman-ford] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/shortest_paths/bellman_ford_shortest.html
"""
if pred_map is None:
pred_map = shortest_distance(g, source, target, weights=weights,
negative_weights=negative_weights,
pred_map=True, dag=dag)[1]
source = g.vertex(source)
target = g.vertex(target)
_check_prop_scalar(pred_map, "pred_map")
if pred_map.value_type() != "int64_t":
pred_map = pred_map.copy("int64_t")
return libgraph_tool_structure.shortest_path_preds(g, int(source),
int(target),
weights, pred_map)
[docs]
@_check_props(v=("dist_map", "pred_map"), e=("weights",))
def all_predecessors(g, dist_map, pred_map, weights=None, epsilon=1e-8):
"""Return a property map with all possible predecessors in the search tree
determined by ``dist_map`` and ``pred_map``.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
dist_map : :class:`~graph_tool.VertexPropertyMap`
Vertex property map with the distances from ``source`` to all other
vertices.
pred_map : :class:`~graph_tool.VertexPropertyMap`
Vertex property map with the predecessors in the search tree.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
The edge weights.
epsilon : ``float`` (optional, default: ``1e-8``)
Maximum relative difference between distances to be considered "equal",
in case floating-point weights are used.
Returns
-------
all_preds_map : :class:`~graph_tool.VertexPropertyMap`
Vector-valued vertex property map with all possible predecessors in the
search tree.
See Also
--------
shortest_distance: Distances from a source vertex
all_shortest_paths: All shortest paths between two vertices
count_shortest_paths: Number of shortest paths between two vertices
"""
_check_prop_scalar(pred_map, "pred_map")
# the C++ function expects the type returned by shortest_distance()
if pred_map.value_type() != "int64_t":
pred_map = pred_map.copy("int64_t")
preds = g.new_vertex_property("vector<int64_t>")
libgraph_tool_structure.get_all_preds(g,
dist_map,
pred_map,
weights,
preds,
epsilon)
return preds
[docs]
@_check_props(v=("dist_map", "pred_map", "all_preds_map"))
def all_shortest_paths(g, source, target, dist_map=None, pred_map=None,
all_preds_map=None, epsilon=1e-8, edges=False, **kwargs):
"""Return an iterator over all shortest paths from `source` to `target`.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex`
Source vertex of the search.
target : :class:`~graph_tool.Vertex`
Target vertex of the search.
dist_map : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex property map with the distances from ``source`` to all other
vertices.
pred_map : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex property map with the predecessors in the search tree. If this is
provided, the shortest paths are not computed, and are obtained directly
from this map.
all_preds_map : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vector-valued vertex property map with all possible predecessors in the
search tree. If this is provided, the shortest paths are obtained
directly from this map.
epsilon : ``float`` (optional, default: ``1e-8``)
Maximum relative difference between distances to be considered "equal",
in case floating-point weights are used.
edges : ``bool`` (optional, default: ``False``)
If ``True``, the returned iterator is over edge descriptors.
**kwargs : Keyword parameter list
The remaining parameters will be passed to
:func:`~graph_tool.structure.shortest_distance`.
Returns
-------
path_iterator : iterator over a sequence of integers
Iterator over sequences of vertices from `source` to `target` in the
shortest path. If ``edges == True``, the iterator is over sequences of
edge descriptors (:class:`~graph_tool.Edge`).
See Also
--------
shortest_path: Shortest path between two vertices
all_predecessors: All shortest-path predecessors of every vertex
count_shortest_paths: Number of shortest paths between two vertices
random_shortest_path: Uniformly random shortest path
Notes
-----
The paths are computed in the same manner as in
:func:`~graph_tool.structure.shortest_distance`, which is used internally.
If both ``dist_map`` and ``pred_map`` are provided, the
:func:`~graph_tool.structure.shortest_distance` is not called.
Examples
--------
>>> g = gt.collection.data["pgp-strong-2009"]
>>> for path in gt.all_shortest_paths(g, 92, 45):
... print(path)
[ 92 107 2176 7027 26 21 45]
[ 92 107 2176 7033 26 21 45]
[ 92 82 94 5877 5879 34 45]
[ 92 89 94 5877 5879 34 45]
The union of all shortest paths between two vertices can be shown in a
drawing of a network with stored positions:
>>> g = gt.collection.data["karate"]
>>> onpath = g.new_ep("bool")
>>> inpath = g.new_vp("bool")
>>> for path in gt.all_shortest_paths(g, 16, 24):
... inpath.a[path] = True
... for u, v in zip(path[:-1], path[1:]):
... onpath[g.edge(u, v)] = True
>>> vcolor = g.new_vp("string", vals=np.where(inpath.a, "#f28c8e",
... "#cccccc"))
>>> ecolor = g.new_ep("string", vals=np.where(onpath.a, "#e41a1c",
... "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(onpath.a, 2.5, 1))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color=ecolor, edge_pen_width=ewidth,
... edge_zorder=onpath.copy("double"),
... vertex_zorder=g.new_vp("double", vals=2 * inpath.a),
... output="all_shortest_paths-karate.pdf")
<...>
.. testcleanup::
conv_png("all_shortest_paths-karate.pdf")
.. figure:: all_shortest_paths-karate.png
:align: center
:width: 50%
All shortest paths between vertices 16 and 24 of Zachary's karate
club network, with their vertices and edges shown in red.
"""
if dist_map is None or pred_map is None:
dist_map, pred_map = shortest_distance(g, source, **dict(kwargs,
pred_map=True))
if pred_map[target] == int(target):
return
if all_preds_map is None:
all_preds_map = all_predecessors(g, dist_map, pred_map,
kwargs.get("weights", None), epsilon)
weights = _check_prop("e", g, kwargs.get("weights", None))
path_iterator = \
libgraph_tool_structure.get_all_shortest_paths(g,
int(source),
int(target),
all_preds_map,
weights,
edges)
for p in path_iterator:
yield p
[docs]
@_check_props(v=("dist_map", "pred_map", "all_preds_map"))
def random_shortest_path(g, source, target, dist_map=None, pred_map=None,
all_preds_map=None, epsilon=1e-8, nsamples=1,
iterator=False, **kwargs):
"""Return a random shortest path from `source` to `target`, uniformly sampled
from all paths of equal length.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex`
Source vertex of the search.
target : :class:`~graph_tool.Vertex`
Target vertex of the search.
dist_map : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex property map with the distances from ``source`` to all other
vertices.
pred_map : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex property map with the predecessors in the search tree. If this is
provided, the shortest paths are not computed, and are obtained directly
from this map.
all_preds_map : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vector-valued vertex property map with all possible predecessors in the
search tree. If this is provided, the shortest paths are obtained
directly from this map.
epsilon : ``float`` (optional, default: ``1e-8``)
Maximum relative difference between distances to be considered "equal",
in case floating-point weights are used.
nsamples : ``int`` (optional, default: ``1``)
Number of paths to sample.
iterator : ``bool`` (optional, default: ``False``)
If ``True``, an iterator is returned.
**kwargs : Keyword parameter list
The remaining parameters will be passed to
:func:`~graph_tool.structure.shortest_distance`.
Returns
-------
path : :class:`numpy.ndarray`, or list of :class:`numpy.ndarray` or iterator over :class:`numpy.ndarray`
Sequence of vertices from `source` to `target` in the shortest path. If
``nsamples > 1`` a list (or iterator) over paths is returned.
See Also
--------
all_shortest_paths: All shortest paths between two vertices
count_shortest_paths: Number of shortest paths between two vertices
shortest_path: Shortest path between two vertices
Notes
-----
The paths are computed in the same manner as in
:func:`~graph_tool.structure.shortest_distance`, which is used internally.
If both ``dist_map`` and ``pred_map`` are provided, the
:func:`~graph_tool.structure.shortest_distance` is not called.
Examples
--------
.. testcode::
:hide:
gt.seed_rng(42)
>>> g = gt.collection.data["pgp-strong-2009"]
>>> path = gt.random_shortest_path(g, 92, 45)
>>> print(path)
[ 92 89 94 5877 5879 34 45]
"""
if dist_map is None or pred_map is None:
dist_map, pred_map = shortest_distance(g, source,
**dict(kwargs, pred_map=True))
if all_preds_map is None:
all_preds_map = all_predecessors(g, dist_map, pred_map,
kwargs.get("weights", None), epsilon)
all_succ_map = g.new_vp("vector<int64_t>")
count_map = g.new_vp("int64_t")
visited_map = g.new_vp("bool")
libgraph_tool_structure.get_weighted_succs(int(target),
all_preds_map._get_any(),
all_succ_map._get_any(),
count_map._get_any(),
visited_map._get_any())
def sample_gen():
if pred_map[target] == int(target):
return
for i in range(nsamples):
path = Vector_size_t()
libgraph_tool_structure.get_random_shortest_path(int(source),
int(target),
all_succ_map._get_any(),
count_map._get_any(),
path, _get_rng())
yield numpy.array(path.a)
if iterator:
return sample_gen()
else:
samples = list(sample_gen())
if len(samples) == 1:
return samples[0]
return samples
[docs]
@_check_props(v=("dist_map", "pred_map", "all_preds_map"))
def count_shortest_paths(g, source, target, dist_map=None, pred_map=None,
all_preds_map=None, epsilon=1e-8, **kwargs):
"""Return the number of shortest paths from `source` to `target`.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex`
Source vertex of the search.
target : :class:`~graph_tool.Vertex`
Target vertex of the search.
dist_map : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex property map with the distances from ``source`` to all other
vertices.
pred_map : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex property map with the predecessors in the search tree. If this is
provided, the shortest paths are not computed, and are obtained directly
from this map.
all_preds_map : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vector-valued vertex property map with all possible predecessors in the
search tree. If this is provided, the shortest paths are obtained
directly from this map.
epsilon : ``float`` (optional, default: ``1e-8``)
Maximum relative difference between distances to be considered "equal",
in case floating-point weights are used.
**kwargs : Keyword parameter list
The remaining parameters will be passed to
:func:`~graph_tool.structure.shortest_distance`.
Returns
-------
n_paths : ``int``
Number of shortest paths from `source` to `target`.
See Also
--------
all_shortest_paths: All shortest paths between two vertices
random_shortest_path: Uniformly random shortest path
all_predecessors: All shortest-path predecessors of every vertex
Notes
-----
The paths are computed in the same manner as in
:func:`~graph_tool.structure.shortest_distance`, which is used internally.
If both ``dist_map`` and ``pred_map`` are provided, the
:func:`~graph_tool.structure.shortest_distance` is not called.
Examples
--------
>>> g = gt.collection.data["pgp-strong-2009"]
>>> n_paths = gt.count_shortest_paths(g, 92, 45)
>>> print(n_paths)
4
"""
if dist_map is None or pred_map is None:
dist_map, pred_map = shortest_distance(g, source,
**dict(kwargs, pred_map=True))
if pred_map[target] == int(target):
return 0
if all_preds_map is None:
all_preds_map = all_predecessors(g, dist_map, pred_map,
kwargs.get("weights", None), epsilon)
all_succ_map = g.new_vp("vector<int64_t>")
count_map = g.new_vp("int64_t")
visited_map = g.new_vp("bool")
libgraph_tool_structure.get_weighted_succs(int(target),
all_preds_map._get_any(),
all_succ_map._get_any(),
count_map._get_any(),
visited_map._get_any())
return count_map[source]
[docs]
@_parallel
@_check_props(e=("weights",))
def k_shortest_paths(g, source, target, k, weights=None, edges=False):
r"""Return the :math:`k` shortest simple paths between two vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex`
Source vertex.
target : :class:`~graph_tool.Vertex`
Target vertex.
k : ``int``
Number of paths.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Non-negative edge weights. If not supplied, every edge has unit
length.
edges : ``bool`` (optional, default: ``False``)
If ``True``, the paths are given by the indices of their edges,
otherwise by their vertices.
Returns
-------
paths : ``list`` of :class:`numpy.ndarray`
The paths, in non-decreasing order of length. Fewer than ``k`` paths
are returned if there are fewer simple paths between the two
vertices.
See Also
--------
shortest_path: A single shortest path
all_shortest_paths: All paths of minimum length
all_paths: All simple paths between two vertices
resource_constrained_path: Shortest path with constraints on resources
Notes
-----
The paths are simple (they do not repeat vertices), and are distinct as
sequences of edges, so that paths that differ only by parallel edges are
counted separately. They are obtained with the algorithm of
[yen-finding-1971]_, which derives each new candidate path from the
previous one by deviating from it at each of its vertices (the "spur"
vertices), avoiding the edges already used by the paths found with the
same prefix. Each of the :math:`k` steps requires a shortest-path search
from every vertex of the last path, which are done in parallel, giving
:math:`O(kV(E + V\log V))` time in the worst case.
@parallel@
Examples
--------
>>> g = gt.collection.data["karate"]
>>> for p in gt.k_shortest_paths(g, g.vertex(16), g.vertex(26), 4):
... print(p)
[16 5 0 8 33 26]
[16 5 0 13 33 26]
[16 5 0 19 33 26]
[16 5 0 31 33 26]
The paths can be highlighted in a drawing of the network:
>>> onpath = g.new_ep("bool")
>>> for p in gt.k_shortest_paths(g, g.vertex(16), g.vertex(26), 4):
... for u, v in zip(p[:-1], p[1:]):
... onpath[g.edge(u, v)] = True
>>> u = gt.GraphView(g, efilt=onpath)
>>> inpath = u.get_total_degrees(g.get_vertices()) > 0
>>> vcolor = g.new_vp("string", vals=np.where(inpath, "#f28c8e",
... "#cccccc"))
>>> ecolor = g.new_ep("string", vals=np.where(onpath.a, "#e41a1c",
... "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(onpath.a, 2.5, 1))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color=ecolor, edge_pen_width=ewidth,
... edge_zorder=onpath.copy("double"),
... vertex_zorder=g.new_vp("double", vals=2 * inpath),
... output="k_shortest_paths-karate.pdf")
<...>
.. testcleanup::
conv_png("k_shortest_paths-karate.pdf")
.. figure:: k_shortest_paths-karate.png
:align: center
:width: 50%
Four shortest paths between vertices 16 and 26 of Zachary's karate
club network. The vertices and edges of the paths are shown in red.
References
----------
.. [yen-finding-1971] Jin Y. Yen, "Finding the k shortest loopless paths
in a network", Management Science 17, 712-716 (1971),
:doi:`10.1287/mnsc.17.11.712`
"""
if weights is not None:
_check_prop_scalar(weights, "weights")
if weights.fa.size > 0 and weights.fa.min() < 0:
raise ValueError("The edge weights must be non-negative.")
if int(source) == int(target):
raise ValueError("Source and target must be distinct.")
return libgraph_tool_structure.k_shortest_paths(g, int(source), int(target),
int(k), weights, edges)
[docs]
def all_paths(g, source, target, cutoff=None, edges=False, min_length=None):
"""Return an iterator over all paths from `source` to `target`.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex`
Source vertex of the search.
target : :class:`~graph_tool.Vertex`
Target vertex of the search.
cutoff : ``int`` (optional, default: ``None``)
Maximum path length.
edges : ``bool`` (optional, default: ``False``)
If ``True``, the returned iterator is over edge descriptors.
min_length : ``int`` (optional, default: ``None``)
Minimum path length (number of edges).
Returns
-------
path_iterator : iterator over a sequence of integers (or :class:`~graph_tool.Edge`)
Iterator over sequences of vertices from `source` to `target` in the
path. If ``edges == True``, the iterator is over sequences of edge
descriptors (:class:`~graph_tool.Edge`).
See Also
--------
k_shortest_paths: The k shortest simple paths
all_shortest_paths: All paths of minimum length
all_circuits: All cycles of a directed graph
Notes
-----
The algorithm uses a depth-first search to find all the paths.
The total number of paths between any two vertices can be quite large,
possibly scaling as :math:`O(V!)`.
Examples
--------
>>> g = gt.collection.data["football"]
>>> for path in gt.all_paths(g, 13, 2, cutoff=2):
... print(path)
[13 2]
[13 15 2]
[13 60 2]
[13 64 2]
[ 13 100 2]
[ 13 106 2]
>>> for path in gt.all_paths(g, 13, 2, cutoff=2, min_length=2):
... print(path)
[13 15 2]
[13 60 2]
[13 64 2]
[ 13 100 2]
[ 13 106 2]
"""
if cutoff is None:
cutoff = g.num_edges() + 1
visited = g.new_vp("bool", False)
if min_length is None:
min_length = 0
path_iterator = libgraph_tool_structure.get_all_paths(g,
int(source),
int(target),
cutoff,
int(min_length),
visited,
edges)
for p in path_iterator:
yield p
[docs]
@_parallel
@_check_props(e=("weights",))
def cycle_basis(g, minimum=False, weights=None, edges=False):
r"""Return a basis of the cycle space of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. If it is directed, it is treated as undirected.
minimum : ``bool`` (optional, default: ``False``)
If ``True``, a basis of minimum total weight is returned; otherwise
the fundamental cycles of a spanning forest.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Non-negative edge weights, used if ``minimum == True``. If not
supplied, every edge has unit weight.
edges : ``bool`` (optional, default: ``False``)
If ``True``, the cycles are given by the indices of their edges,
otherwise by their vertices.
Returns
-------
cycles : ``list`` of :class:`numpy.ndarray`
The cycles, each given by its vertices (or edges) in the order in
which they are traversed. A minimum basis is sorted by weight.
See Also
--------
find_cycle: A single cycle of the graph
all_circuits: All cycles of a directed graph
chordless_cycles: All chordless cycles
girth: Length of the shortest cycle
Notes
-----
The
`cycle space <https://en.wikipedia.org/wiki/Cycle_space>`_
of an undirected graph is the vector space over
:math:`\mathrm{GF}(2)` spanned by the edge sets of its cycles, with the
symmetric difference as the sum; its dimension is :math:`E - V + C`,
where :math:`C` is the number of connected components. Self-loops and
parallel edges count as cycles of lengths one and two.
The fundamental cycles are formed by each edge outside a breadth-first
spanning forest and the forest path between its endpoints, obtained in
time :math:`O(V + \sum_i L_i)`, where :math:`L_i` is the length of
cycle :math:`i`.
A
`minimum cycle basis <https://en.wikipedia.org/wiki/Cycle_basis>`_
minimizes the sum of the weights of its cycles. It
is computed with the algorithm of de Pina [pina-applications-1995]_
[kavitha-cycle-2009]_, which finds the cycles one at a time, each as the
shortest cycle that has an odd number of edges in common with a "support"
vector kept orthogonal to the cycles already found. Each such cycle is a
shortest path in a graph with two copies of every vertex, searched from
every vertex in parallel, so that the total time is :math:`O(KV(E + V\log
V) + K^2E)` with :math:`K = E - V + C`, and the memory :math:`O(K^2)`;
hence it is suitable only for moderate graph sizes.
@parallel@
Examples
--------
>>> g = gt.collection.data["karate"]
>>> cycles = gt.cycle_basis(g, minimum=True)
>>> print(len(cycles), [len(c) for c in cycles[-3:]])
45 [4, 4, 4]
The last three cycles of the basis can be highlighted in a drawing of
the network:
>>> colors = ["#e41a1c", "#377eb8", "#4daf4a"]
>>> ecolor = g.new_ep("string", val="#999999")
>>> ewidth = g.new_ep("double", val=1)
>>> for c, color in zip(cycles[-3:], colors):
... for u, v in zip(c, np.roll(c, -1)):
... ecolor[g.edge(u, v)] = color
... ewidth[g.edge(u, v)] = 2.5
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color="#cccccc",
... edge_color=ecolor, edge_pen_width=ewidth,
... output="cycle_basis-karate.pdf")
<...>
.. testcleanup::
conv_png("cycle_basis-karate.pdf")
.. figure:: cycle_basis-karate.png
:align: center
:width: 50%
Three cycles of the minimum cycle basis of Zachary's karate club
network, shown in red, blue, and green.
References
----------
.. [pina-applications-1995] José Coelho de Pina, "Applications of shortest
path methods", PhD thesis, University of Amsterdam (1995).
.. [kavitha-cycle-2009] Telikepalli Kavitha, Christian Liebchen, Kurt
Mehlhorn, Dimitrios Michail, Romeo Rizzi, Torsten Ueckerdt and
Katharina A. Zweig, "Cycle bases in graphs: characterization,
algorithms, complexity, and applications", Computer Science Review 3,
199-243 (2009), :doi:`10.1016/j.cosrev.2009.08.001`
"""
u = GraphView(g, directed=False)
if not minimum:
return libgraph_tool_structure.fundamental_cycles(u, edges)
if weights is not None:
_check_prop_scalar(weights, "weights")
if weights.fa.size > 0 and weights.fa.min() < 0:
raise ValueError("The edge weights must be non-negative.")
weights = u.own_property(weights)
return libgraph_tool_structure.minimum_cycle_basis(u, weights, edges)
[docs]
@_parallel
def girth(g, cycle=False):
r"""Return the girth of the graph, i.e. the length of its shortest cycle.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
cycle : ``bool`` (optional, default: ``False``)
If ``True``, a shortest cycle is also returned.
Returns
-------
girth : ``int`` or ``float``
The length of the shortest cycle (directed, if the graph is directed),
or ``numpy.inf`` if there are no cycles.
cycle : :class:`numpy.ndarray`
The vertices of a shortest cycle, in order (or ``None`` if there are
no cycles). Only returned if ``cycle == True``.
See Also
--------
find_cycle: A single cycle of the graph
cycle_basis: Basis of the cycle space
chordless_cycles: All chordless cycles
Notes
-----
The
`girth <https://en.wikipedia.org/wiki/Girth_(graph_theory)>`_
is the length of a shortest cycle, i.e. its number of edges. Self-loops
are cycles of length one, and in undirected graphs parallel
edges form cycles of length two.
A breadth-first search is made from every vertex, in parallel, and is
stopped once it can no longer find a cycle shorter than the shortest one
found so far. In the worst case, the time is :math:`O(V(V + E))`.
@parallel@
Examples
--------
>>> g = gt.collection.petersen_graph()
>>> print(gt.girth(g))
5
>>> g = gt.collection.data["karate"]
>>> print(gt.girth(g, cycle=True))
(3, array([0, 1, 2], dtype=uint64))
"""
gi, c = libgraph_tool_structure.girth(g)
if gi is None:
gi = numpy.inf
if cycle:
return gi, c
return gi
[docs]
def all_circuits(g, unique=False, max_length=0, min_length=0):
"""Return an iterator over all the cycles in a directed graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
A directed graph to be used. (Undirected graphs are also accepted, in
which case each undirected edge is assumed to be equivalent to two
directed edges in both directions.)
unique : ``bool`` (optional, default: ``False``)
If ``True``, parallel edges and self-loops will be ignored.
max_length : ``int`` (optional, default: ``0``)
The maximum circuit length to consider. Beyond this it truncates the
depth-first search, reducing the computation time by ignoring longer
circuits. The default value of ``max_length = 0`` implies no maximum.
min_length : ``int`` (optional, default: ``0``)
The minimum circuit length; shorter circuits are not returned.
Returns
-------
cycle_iterator : iterator over a sequence of integers
Iterator over sequences of vertices that form a circuit.
See Also
--------
chordless_cycles: Cycles without chords
cycle_basis: Basis of the cycle space
find_cycle: A single cycle of the graph
all_paths: All simple paths between two vertices
Notes
-----
This algorithm [johnson-finding-1975]_ [hawick-enumerating-2008]_ runs in
worst time :math:`O[(V + E)(C + 1)]`, where :math:`C` is the number of
circuits.
Examples
--------
.. testcode::
:hide:
gt.seed_rng(42)
>>> g = gt.random_graph(10, lambda: (1, 1))
>>> for c in gt.all_circuits(g):
... print(c)
[0 6]
[1 5 4 9 7 2 8 3]
References
----------
.. [johnson-finding-1975] D.B. Johnson, "Finding all the elementary circuits of a directed graph",
SIAM Journal on Computing, 1975. :doi:`10.1137/0204007`
.. [hawick-enumerating-2008] K.A. Hawick and H.A. James, "Enumerating
Circuits and Loops in Graphs with Self-Arcs and Multiple-Arcs.",
In Proceedings of FCS. 2008, 14-20,
http://cssg.massey.ac.nz/cstn/013/cstn-013.html
.. [hawick-bgl] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/cycle_detection/hawick_circuits.html
"""
circuits_iterator = libgraph_tool_structure.\
get_all_circuits(g, unique, max_length, min_length)
return circuits_iterator
[docs]
@_check_props(e=("weights",))
def pseudo_diameter(g, source=None, weights=None):
r"""
Compute the pseudo-diameter of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex` (optional, default: ``None``)
Source vertex of the search. If not supplied, the first vertex
in the graph will be chosen.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
The edge weights.
Returns
-------
pseudo_diameter : float
The pseudo-diameter of the graph.
end_points : pair of :class:`~graph_tool.Vertex`
The two vertices which correspond to the pseudo-diameter found.
See Also
--------
diameter: Exact diameter of a graph
radius: Radius of a graph
eccentricity: Eccentricity of every vertex
shortest_distance: Distances from a source vertex
Notes
-----
The pseudo-diameter is an approximate graph diameter. It is obtained by
starting from a vertex `source`, and finds a vertex `target` that is
farthest away from `source`. This process is repeated by treating
`target` as the new starting vertex, and ends when the graph distance no
longer increases. A vertex from the last level set that has the smallest
degree is chosen as the final starting vertex u, and a traversal is done
to see if the graph distance can be increased. This graph distance is
taken to be the pseudo-diameter.
The paths are computed with a breadth-first search (BFS) or Dijkstra's
algorithm [dijkstra]_, if weights are given.
The algorithm runs in :math:`O(V + E)` time, or :math:`O(V \log V)` if
weights are given.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> from numpy.random import poisson
>>> g = gt.random_graph(300, lambda: (poisson(3), poisson(3)))
>>> dist, ends = gt.pseudo_diameter(g)
>>> print(dist)
8.0
>>> print(int(ends[0]), int(ends[1]))
0 157
References
----------
.. [pseudo-diameter] http://en.wikipedia.org/wiki/Distance_%28graph_theory%29
.. [dijkstra] E. Dijkstra, "A note on two problems in connexion with
graphs." Numerische Mathematik, 1:269-271, 1959.
"""
if source is None:
source = g.vertex(0, use_index=False)
dist, target = 0, source
while True:
new_source = target
new_target, new_dist = libgraph_tool_structure.get_diam(g,
int(new_source),
weights)
if new_dist > dist:
target = new_target
source = new_source
dist = new_dist
else:
break
return dist, (g.vertex(source), g.vertex(target))
def _ecc_map(g, weights):
if weights is None:
return g.new_vp("int32_t")
_check_prop_scalar(weights, "weights")
if weights.fa.size > 0 and weights.fa.min() < 0:
raise ValueError("The edge weights must be non-negative.")
vt = weights.value_type()
if vt not in ["double", "long double"]:
vt = "int64_t"
return g.new_vp(vt)
[docs]
@_parallel
@_check_props(e=("weights",))
def eccentricity(g, weights=None, epsilon=1e-8):
r"""Compute the eccentricity of every vertex.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Non-negative edge weights. If not supplied, every edge has unit length.
epsilon : ``float`` (optional, default: ``1e-8``)
Relative tolerance with which lower and upper bounds of the
eccentricity are considered equal, if the weights are floating-point
numbers.
Returns
-------
ecc : :class:`~graph_tool.VertexPropertyMap`
Vertex property map with the eccentricities. Its value type is
``int32_t`` if ``weights is None``, ``int64_t`` for integer weights,
and the type of the weights otherwise.
See Also
--------
diameter: Maximum eccentricity
radius: Minimum eccentricity
center: Vertices of minimum eccentricity
periphery: Vertices of maximum eccentricity
shortest_distance: Distances between vertices
Notes
-----
The
`eccentricity <https://en.wikipedia.org/wiki/Distance_(graph_theory)>`_
of a vertex :math:`v` is the largest shortest-path
distance from :math:`v` to any other vertex,
.. math::
\epsilon(v) = \max_{u} d(v, u),
where the maximum is taken only over the vertices reachable from
:math:`v`. Hence, isolated vertices have eccentricity zero, and in a
disconnected graph the eccentricities are those within each component.
For directed graphs, :math:`d(v, u)` is the length of the shortest
directed path from :math:`v` to :math:`u`.
The minimum and maximum eccentricities are the radius and the diameter,
which are computed directly, with fewer searches, by :func:`radius` and
:func:`diameter`. The center and the periphery of the graph are the
vertices whose eccentricity equals the radius and the diameter,
respectively.
For undirected graphs, the eccentricity bounding algorithm of
[takes-computing-2013]_ is used: a search from a vertex :math:`v` yields
the bounds :math:`\max(\epsilon(v)-d(v,u), d(v,u)) \le \epsilon(u) \le
\epsilon(v) + d(v, u)` for every other vertex :math:`u`, and the searches
continue only from vertices whose bounds do not yet coincide. In large
sparse networks, the number of searches needed is typically a small
fraction of the number of vertices, although in the worst case it is
:math:`V`, giving :math:`O(V(V+E))` time, or :math:`O(V(V+E)\log V)` with
weights. For directed graphs, the bounds do not apply, and a search is
made from every vertex.
The searches are breadth-first, or use Dijkstra's algorithm if weights
are given.
@parallel@
With :math:`T` threads, the algorithm uses :math:`O(TV)` memory.
Examples
--------
.. testcode::
:hide:
gt.seed_rng(42)
>>> g = gt.collection.data["polblogs"]
>>> g = gt.extract_largest_component(g, directed=False, prune=True)
>>> g.set_directed(False)
>>> ecc = gt.eccentricity(g)
>>> print(ecc.fa.min(), ecc.fa.max())
4 8
For a smaller network, the eccentricities can be visualized by coloring
the vertices:
>>> from matplotlib.colors import LinearSegmentedColormap
>>> g = gt.collection.data["karate"]
>>> ecc = gt.eccentricity(g)
>>> print(ecc.fa.min(), ecc.fa.max())
3 5
>>> cmap = LinearSegmentedColormap.from_list("ecc", ["#d9d9d9",
... "#7dabd1"])
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=ecc.copy("double"),
... vcmap=cmap,
... vertex_text=ecc, edge_color="#999999",
... output="eccentricity-karate.pdf")
<...>
.. testcleanup::
conv_png("eccentricity-karate.pdf")
.. figure:: eccentricity-karate.png
:align: center
:width: 50%
Eccentricities of the vertices of Zachary's karate club network,
given by the labels and by the colors, which range from gray
(eccentricity 3) to blue (eccentricity 5).
References
----------
.. [takes-computing-2013] Frank W. Takes and Walter A. Kosters, "Computing
the eccentricity distribution of large graphs", Algorithms 6, 100-118
(2013), :doi:`10.3390/a6010100`
"""
ecc = _ecc_map(g, weights)
libgraph_tool_structure.get_eccentricity(g, weights, ecc, 0, epsilon)
return ecc
[docs]
@_parallel
@_check_props(e=("weights",))
def diameter(g, weights=None, epsilon=1e-8):
r"""Compute the diameter of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Non-negative edge weights. If not supplied, every edge has unit length.
epsilon : ``float`` (optional, default: ``1e-8``)
Relative tolerance with which lower and upper bounds are considered
equal, if the weights are floating-point numbers.
Returns
-------
diameter : ``int`` or ``float``
The diameter of the graph.
end_points : pair of :class:`~graph_tool.Vertex`
Two vertices whose distance is the diameter.
See Also
--------
radius: Minimum eccentricity
eccentricity: Eccentricity of every vertex
pseudo_diameter: Fast lower bound on the diameter
harmonic_diameter: Diameter that accounts for disconnected pairs
periphery: Vertices of maximum eccentricity
Notes
-----
The
`diameter <https://en.wikipedia.org/wiki/Distance_(graph_theory)>`_
is the largest eccentricity of the vertices (see
:func:`eccentricity`), i.e. the length of the longest of the shortest
paths between any two vertices. Pairs of vertices that are not connected
by a path are ignored, so that the diameter of a disconnected graph is the
largest diameter of its components.
For undirected graphs, the algorithm of [takes-determining-2011]_ is used,
which bounds the eccentricities as in :func:`eccentricity`, but stops as
soon as the largest lower and upper bounds coincide, and does not search
from vertices that cannot change either of them. In large sparse networks,
this usually requires only a few searches, each taking time :math:`O(V+E)`,
or :math:`O((V+E)\log V)` with weights, although in the worst case
:math:`V` searches are needed. For directed graphs, a search is made from
every vertex.
The function :func:`pseudo_diameter` gives a lower bound with a few
searches, without a guarantee of exactness.
@parallel@
Examples
--------
>>> g = gt.collection.data["polblogs"]
>>> g = gt.extract_largest_component(g, directed=False, prune=True)
>>> g.set_directed(False)
>>> d, ends = gt.diameter(g)
>>> print(d)
8
References
----------
.. [takes-determining-2011] Frank W. Takes and Walter A. Kosters,
"Determining the diameter of small world networks", Proceedings of the
20th ACM International Conference on Information and Knowledge
Management (CIKM), 1191-1196 (2011), :doi:`10.1145/2063576.2063748`
"""
ecc = _ecc_map(g, weights)
d, s, t = libgraph_tool_structure.get_eccentricity(g, weights, ecc, 1, epsilon)
return d, (g.vertex(s), g.vertex(t))
[docs]
@_parallel
@_check_props(e=("weights",))
def radius(g, weights=None, epsilon=1e-8):
r"""Compute the radius of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Non-negative edge weights. If not supplied, every edge has unit length.
epsilon : ``float`` (optional, default: ``1e-8``)
Relative tolerance with which lower and upper bounds are considered
equal, if the weights are floating-point numbers.
Returns
-------
radius : ``int`` or ``float``
The radius of the graph.
center : :class:`~graph_tool.Vertex`
A vertex with eccentricity equal to the radius.
See Also
--------
diameter: Maximum eccentricity
eccentricity: Eccentricity of every vertex
center: Vertices of minimum eccentricity
Notes
-----
The
`radius <https://en.wikipedia.org/wiki/Distance_(graph_theory)>`_
is the smallest eccentricity of the vertices (see
:func:`eccentricity`). Since the eccentricity considers only reachable
vertices, the radius of a graph with an isolated vertex (or, if directed,
with a vertex without out-neighbors) is zero; for the radius of the
largest component, the function should be called on the output of
:func:`extract_largest_component`.
For undirected graphs, the eccentricities are bounded as in
:func:`eccentricity` [takes-determining-2011]_, and the searches stop as
soon as the smallest lower and upper bounds coincide. In the worst case,
:math:`V` searches are needed, each taking time :math:`O(V+E)`, or
:math:`O((V+E)\log V)` with weights. For directed graphs, a search is
made from every vertex.
@parallel@
Examples
--------
>>> g = gt.collection.data["polblogs"]
>>> g = gt.extract_largest_component(g, directed=False, prune=True)
>>> g.set_directed(False)
>>> r, c = gt.radius(g)
>>> print(r)
4
References
----------
.. [takes-determining-2011] Frank W. Takes and Walter A. Kosters,
"Determining the diameter of small world networks", Proceedings of the
20th ACM International Conference on Information and Knowledge
Management (CIKM), 1191-1196 (2011), :doi:`10.1145/2063576.2063748`
"""
ecc = _ecc_map(g, weights)
r, s, t = libgraph_tool_structure.get_eccentricity(g, weights, ecc, 2, epsilon)
return r, g.vertex(s)
[docs]
@_parallel
@_check_props(e=("weight",))
def random_walk(g, source, length, weight=None, p=1., q=1., edges=False,
restart=0., stuck="stop"):
r"""Sample random walks on the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex`, ``int``, or iterable of ``int``
Starting vertex of the walk, or of each walk.
length : ``int``
Number of steps of each walk.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Non-negative edge weights. If given, the steps are taken along each
out-edge with probability proportional to its weight; otherwise, all
out-edges are equally likely.
p : ``float`` (optional, default: ``1.``)
Return parameter of the second-order walk of node2vec (see below).
q : ``float`` (optional, default: ``1.``)
In-out parameter of the second-order walk of node2vec (see below).
edges : ``bool`` (optional, default: ``False``)
If ``True``, the walks are returned as sequences of edge indices,
instead of vertices.
restart : ``float`` (optional, default: ``0.``)
Probability with which every step is a jump back to the starting
vertex, instead of a move along an edge.
stuck : ``str`` (optional, default: ``"stop"``)
What happens when a walk reaches a vertex without out-edges: with
``"stop"`` the walk ends, with ``"restart"`` it jumps back to the
starting vertex, and with ``"error"`` a :class:`ValueError` is raised.
Returns
-------
walks : :class:`numpy.ndarray`
If ``source`` is a single vertex, an array with the ``length + 1``
visited vertices (or the ``length`` traversed edges, if ``edges ==
True``); otherwise a two-dimensional array with one walk per row. If
a walk reaches a vertex without out-edges and ``stuck == "stop"``,
the remaining entries are ``-1``. In the sequences of edges, the
jumps back to the starting vertex are ``-1``.
See Also
--------
loop_erased_random_walk: Random walk with its loops erased
random_shortest_path: Uniformly sampled shortest path
graph_tool.spectral.transition: Transition matrix of the random walk
Notes
-----
Each step moves from the current vertex :math:`v` to an out-neighbor
along an edge :math:`e` with probability :math:`w_e/\sum_{e'}w_{e'}`,
where the sum runs over the out-edges of :math:`v` (for undirected graphs,
all incident edges). If ``p`` or ``q`` differ from one, the walk is the
`second-order walk of node2vec <https://en.wikipedia.org/wiki/Node2vec>`_
[grover-node2vec-2016]_: the probability of
moving from :math:`v` to :math:`x`, having arrived at :math:`v` from
:math:`t`, is further multiplied by :math:`1/p` if :math:`x=t`, by
:math:`1` if :math:`x` is a neighbor of :math:`t`, and by :math:`1/q`
otherwise, so that small values of :math:`p` keep the walk local, and
small values of :math:`q` drive it away. These steps are sampled by
rejection, which requires :math:`O(\max(p, 1/p, q, 1/q))` attempts in
the worst case, each with a test of adjacency in time :math:`O(\log k)`.
With ``restart > 0``, the walk is a random walk with restart, whose
stationary distribution is the personalized PageRank of the starting
vertex (see :func:`~graph_tool.centrality.pagerank`), and a jump back
resets the node2vec memory of the previous vertex.
The walks are sampled in parallel. After an initial pass over the edges in
time :math:`O(E\log k)`, each step takes time :math:`O(1)`, or
:math:`O(\log k)` with weights, where :math:`k` is the degree of the
current vertex.
@parallel@
Examples
--------
.. testcode::
:hide:
np.random.seed(42)
gt.seed_rng(42)
>>> g = gt.collection.data["karate"]
>>> print(gt.random_walk(g, g.vertex(0), 10))
[ 0 13 1 17 0 10 5 10 0 13 0]
A common use is the generation of the "sentences" of vertex embeddings
such as DeepWalk and node2vec, by sampling several walks from every
vertex:
>>> walks = gt.random_walk(g, np.repeat(g.get_vertices(), 10), 20, p=0.5, q=2)
>>> print(walks.shape)
(340, 21)
With restarts, the walk stays near the starting vertex:
>>> print(gt.random_walk(g, g.vertex(0), 10, restart=0.5))
[ 0 0 0 0 31 0 6 0 5 0 11]
References
----------
.. [grover-node2vec-2016] Aditya Grover and Jure Leskovec, "node2vec:
Scalable feature learning for networks", Proceedings of the 22nd ACM
SIGKDD International Conference on Knowledge Discovery and Data Mining,
855-864 (2016), :doi:`10.1145/2939672.2939754`, :arxiv:`1607.00653`
"""
single = isinstance(source, (int, numpy.integer)) or \
not isinstance(source, collections.abc.Iterable)
sources = numpy.asarray([int(source)] if single else
[int(v) for v in source], dtype="int64")
if p <= 0 or q <= 0:
raise ValueError("p and q must be positive")
if not 0 <= restart <= 1:
raise ValueError("restart must be a probability")
stucks = {"stop": 0, "restart": 1, "error": 2}
if stuck not in stucks:
raise ValueError("invalid value for stuck: %s" % str(stuck))
if weight is not None:
_check_prop_scalar(weight, "weight")
if weight.fa.size > 0 and weight.fa.min() < 0:
raise ValueError("The edge weights must be non-negative.")
walks = libgraph_tool_structure.random_walk(g, sources, int(length),
weight, float(p), float(q),
edges, float(restart),
stucks[stuck], _get_rng())
walks = walks.reshape((len(sources), -1))
if single:
return walks[0]
return walks
[docs]
def is_bipartite(g, partition=False, find_odd_cycle=False):
"""Test if the graph is bipartite.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
partition : bool (optional, default: ``False``)
If ``True``, return the two partitions in case the graph is bipartite.
find_odd_cycle : bool (optional, default: ``False``)
If ``True``, return an odd cycle if the graph is not bipartite.
Returns
-------
is_bipartite : ``bool``
Whether or not the graph is bipartite.
partition : :class:`~graph_tool.VertexPropertyMap` (only if ``partition=True``)
A vertex property map with the graph partitioning. If the graph is not
bipartite, all its values are set to zero.
odd_cycle : list of vertices (only if ``find_odd_cycle=True``)
A list of vertices corresponding to an odd cycle, or ``None`` if none is
found.
See Also
--------
bipartite_vertex_cover: Minimum vertex cover of a bipartite graph
maximal_extendability: Maximal extendability of a bipartite graph
is_perfect: Test for perfect graphs
maximum_cardinality_matching: Maximum matching
Notes
-----
An undirected graph is bipartite if one can partition its set of vertices
into two sets, such that all edges go from one set to the other.
This algorithm runs in :math:`O(V + E)` time.
Examples
--------
>>> g = gt.lattice([10, 10])
>>> is_bi, part = gt.is_bipartite(g, partition=True)
>>> print(is_bi)
True
>>> gt.graph_draw(g, vertex_fill_color=part, output="bipartite.pdf")
<...>
.. testcleanup::
conv_png("bipartite.pdf")
.. figure:: bipartite.png
:align: center
:width: 40%
Bipartition of a 2D lattice.
References
----------
.. [boost-bipartite] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/coloring/is_bipartite.html
"""
if partition:
part = g.new_vertex_property("bool")
else:
part = None
g = GraphView(g, directed=False, skip_properties=True)
cycle = []
is_bi = libgraph_tool_structure.is_bipartite(g,
part,
find_odd_cycle, cycle)
if not is_bi and part is not None:
part.a = 0
if len(cycle) == 0:
cycle = None
else:
cycle.append(cycle[0])
if find_odd_cycle:
if partition:
return is_bi, part, cycle
else:
return is_bi, cycle
else:
if partition:
return is_bi, part
else:
return is_bi
[docs]
def is_planar(g, embedding=False, kuratowski=False):
"""
Test if the graph is planar.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
embedding : bool (optional, default: ``False``)
If true, return a mapping from vertices to the clockwise order of
out-edges in the planar embedding.
kuratowski : bool (optional, default: ``False``)
If true, the minimal set of edges that form the obstructing Kuratowski
subgraph will be returned as a property map, if the graph is not planar.
Returns
-------
is_planar : bool
Whether or not the graph is planar.
embedding : :class:`~graph_tool.VertexPropertyMap` (only if `embedding=True`)
A vertex property map with the out-edges indices in clockwise order in
the planar embedding.
kuratowski : :class:`~graph_tool.EdgePropertyMap` (only if `kuratowski=True`)
An edge property map with the minimal set of edges that form the
obstructing Kuratowski subgraph (if the value of kuratowski[e] is 1,
the edge belongs to the set)
See Also
--------
graph_tool.generation.make_maximal_planar: Maximal planar supergraph
planar_faces: Faces of a planar embedding
is_straight_line_drawing: Test for crossings in a straight-line drawing
graph_tool.draw.planar_layout: Straight-line planar layout
Notes
-----
A graph is planar if it can be drawn in two-dimensional space without any of
its edges crossing. This algorithm performs the Boyer-Myrvold planarity
testing [boyer-myrvold]_. See [boost-planarity]_ for more details.
This algorithm runs in :math:`O(V)` time.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> from numpy.random import random
>>> g = gt.triangulation(random((100,2)))[0]
>>> p, embed_order = gt.is_planar(g, embedding=True)
>>> print(p)
True
>>> print(list(embed_order[g.vertex(0)]))
[0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 1]
>>> g = gt.random_graph(100, lambda: 4, directed=False)
>>> p, kur = gt.is_planar(g, kuratowski=True)
>>> print(p)
False
>>> g.set_edge_filter(kur)
>>> gt.graph_draw(g, output="kuratowski.pdf")
<...>
.. testcleanup::
conv_png("kuratowski.pdf")
.. figure:: kuratowski.png
:align: center
:width: 40%
Obstructing Kuratowski subgraph of a random graph.
References
----------
.. [boyer-myrvold] John M. Boyer and Wendy J. Myrvold, "On the Cutting Edge:
Simplified O(n) Planarity by Edge Addition" Journal of Graph Algorithms
and Applications, 8(2): 241-273, 2004. http://www.emis.ams.org/journals/JGAA/accepted/2004/BoyerMyrvold2004.8.3.pdf
.. [boost-planarity] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/planar/boyer_myrvold.html
"""
if embedding:
embed = g.new_vertex_property("vector<int>")
else:
embed = None
if kuratowski:
kur = g.new_edge_property("bool")
else:
kur = None
u = GraphView(g, directed=False)
is_planar = libgraph_tool_structure.is_planar(u, embed, kur)
ret = [is_planar]
if embed is not None:
ret.append(embed)
if kur is not None:
ret.append(kur)
if len(ret) == 1:
return ret[0]
else:
return tuple(ret)
[docs]
def is_DAG(g):
"""
Return ``True`` if the graph is a directed acyclic graph (DAG).
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
See Also
--------
topological_sort: Topological ordering of a directed acyclic graph
transitive_reduction: Transitive reduction of a directed acyclic graph
feedback_arc_set: Edges whose removal leaves the graph acyclic
all_topological_sorts: All topological orderings
Notes
-----
The time complexity is :math:`O(V + E)`.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(42)
gt.seed_rng(42)
>>> g = gt.random_graph(30, lambda: (3, 3))
>>> print(gt.is_DAG(g))
False
>>> tree = gt.minimum_spanning_tree(g)
>>> g.set_edge_filter(tree)
>>> print(gt.is_DAG(g))
True
References
----------
.. [DAG-wiki] http://en.wikipedia.org/wiki/Directed_acyclic_graph
"""
topological_order = Vector_int32_t()
is_DAG = libgraph_tool_structure.\
topological_sort(g, topological_order)
return is_DAG
[docs]
@_check_props(v=("bipartite",))
def maximum_cardinality_matching(g, bipartite=False, init_match="extra_greedy",
heuristic=False, edges=False):
r"""Find a maximum cardinality matching in the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
bipartite : ``bool`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``False``)
If ``True``, the graph will be assumed to be bipartite, and the
algorithm for bipartite graphs will be used. If a
:class:`~graph_tool.VertexPropertyMap` is passed, it should correspond
to an existing bipartition. A ``ValueError`` is raised if the graph is
not bipartite, or if the bipartition is not valid.
init_match : ``string`` (optional, default: ``"extra_greedy"``)
Initial matching strategy. Can be one of: `"empty"`, `"greedy"`, or
`"extra_greedy"`. Ignored if ``heuristic == True`` or if ``bipartite``
is given.
heuristic : ``bool`` (optional, default: ``False``)
If ``True``, a maximal matching is found by a random greedy heuristic,
which runs in linear time, instead of a maximum one.
edges : ``bool`` (optional, default: ``False``)
If ``True``, an edge property map will be returned, instead of a vertex
property map. If a matched pair of vertices is connected by parallel
edges, only one of them is marked.
Returns
-------
match : :class:`~graph_tool.VertexPropertyMap`
Vertex property map with the vertex matched to each vertex (or the
largest value of ``int64_t`` for the unmatched ones). If ``edges ==
True`` a boolean-valued edge property map is returned instead.
See Also
--------
maximum_weight_matching: Matching of maximum total weight
approx_minimum_maximal_matching: Approximate minimum maximal matching
minimum_edge_cover: Minimum edge cover
bipartite_vertex_cover: Minimum vertex cover of a bipartite graph
k_factor: Spanning subgraph in which every vertex has degree k
Notes
-----
A
`matching <https://en.wikipedia.org/wiki/Matching_(graph_theory)>`_
is a set of edges no two of which share an endpoint, and a maximum
cardinality matching is one with the largest number of edges. It is found
with Edmonds' blossom algorithm [edmonds-paths-1965]_
[boost-max-matching]_, starting from the matching given by
``init_match``, in time :math:`O(EV\alpha(E,V))`, where
:math:`\alpha(E,V)` is the inverse Ackermann function, which is at most 4
for any feasible input. If ``bipartite`` is given, the algorithm of
Hopcroft and Karp [hopcroft-n52-1973]_ is used instead, which augments
the matching in phases along a maximal set of vertex-disjoint shortest
augmenting paths, found by a breadth-first search followed by depth-first
searches, and needs :math:`O(\sqrt{V})` phases of time :math:`O(V + E)`,
i.e. time :math:`O(E\sqrt{V})` in total. Self-loops are ignored in both
cases, since they cannot be part of a matching.
If ``heuristic == True``, the vertices are visited in random order, and
every unmatched vertex is matched to a randomly chosen unmatched
neighbor, if there is one [matching-heuristic]_. The result is a
`maximal matching <https://en.wikipedia.org/wiki/Maximal_matching>`_,
i.e. no edge can be added to it, which approximates the maximum one
within a factor two, since every edge of a maximum matching shares an
endpoint with an edge of any maximal matching. This takes time
:math:`O(V + E)`, and ``bipartite`` is then ignored.
Examples
--------
.. testcode::
:hide:
import matplotlib
import numpy.random
numpy.random.seed(43)
gt.seed_rng(43)
>>> g = gt.GraphView(gt.price_network(300), directed=False)
>>> w = gt.maximum_cardinality_matching(g, edges=True)
>>> gt.graph_draw(g, edge_color=w, edge_pen_width=w.t(lambda x: 2*x + 1),
... vertex_fill_color="grey", ecmap=matplotlib.cm.tab10,
... output="max_card_match.pdf")
<...>
.. testcleanup::
conv_png("max_card_match.pdf")
.. figure:: max_card_match.png
:align: center
:width: 80%
Edges belonging to the matching are drawn in orange.
For a bipartite graph, such as a square lattice, the algorithm for
bipartite graphs can be used, which gives a matching of the same size:
>>> g = gt.lattice([30, 30])
>>> m = gt.maximum_cardinality_matching(g, bipartite=True, edges=True)
>>> print(m.a.sum(), gt.maximum_cardinality_matching(g, edges=True).a.sum())
450 450
References
----------
.. [edmonds-paths-1965] Jack Edmonds, "Paths, trees, and flowers",
Canadian Journal of Mathematics 17, 449-467 (1965),
:doi:`10.4153/CJM-1965-045-4`
.. [hopcroft-n52-1973] John E. Hopcroft and Richard M. Karp, "An
:math:`n^{5/2}` algorithm for maximum matchings in bipartite graphs",
SIAM Journal on Computing 2, 225-231 (1973), :doi:`10.1137/0202019`
.. [boost-max-matching] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/network_flow/maximum_matching.html
.. [matching-heuristic] B. Hendrickson and R. Leland. "A Multilevel Algorithm
for Partitioning Graphs." In S. Karin, editor, Proc. Supercomputing ’95,
San Diego. ACM Press, New York, 1995, :doi:`10.1145/224170.224228`
"""
match = g.new_vp("int64_t")
u = GraphView(g, directed=False)
if not heuristic:
if bipartite is False:
libgraph_tool_structure.get_max_matching(u, init_match, match)
else:
if isinstance(bipartite, VertexPropertyMap):
_check_prop_scalar(bipartite, "bipartite")
partition = bipartite
else:
# self-loops cannot be matched, and do not prevent the
# bipartition of the other edges
loops = label_self_loops(u, mark_only=True)
nl = GraphView(u, efilt=loops.a == 0)
is_bip, partition = is_bipartite(nl, partition=True)
if not is_bip:
raise ValueError("Supplied graph is not bipartite")
libgraph_tool_structure.get_max_bip_matching(u, partition, match)
else:
libgraph_tool_structure.random_matching(u, None, match, False,
_get_rng())
if edges:
ematch = g.new_ep("bool")
libgraph_tool_structure.match_edges(u, match, ematch, None, False)
return ematch
return match
[docs]
@_check_props(v=("bipartite",), e=("weight",))
def maximum_weight_matching(g, weight, bipartite=False, minimize=False,
heuristic=False, edges=False, brute_force=False):
r"""Find a matching of maximum total weight in the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
weight : :class:`~graph_tool.EdgePropertyMap`
Edge weights.
bipartite : ``bool`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``False``)
If ``True``, the graph will be assumed to be bipartite, and the
algorithm for bipartite graphs will be used. If a
:class:`~graph_tool.VertexPropertyMap` is passed, it should correspond
to an existing bipartition.
minimize : ``bool`` (optional, default: ``False``)
If ``True``, a matching of minimum total weight among those of maximum
cardinality will be returned instead (see below).
heuristic : ``bool`` (optional, default: ``False``)
If ``True``, an approximate matching will be found by a random greedy
heuristic, which runs in linear time.
edges : ``bool`` (optional, default: ``False``)
If ``True``, an edge property map will be returned, instead of a vertex
property map. If a matched pair of vertices is connected by parallel
edges, only one of them is marked, the one with the best weight.
brute_force : ``bool`` (optional, default: ``False``)
If ``True``, and ``heuristic`` is ``False``, all matchings are
enumerated, which is feasible only for very small graphs.
Returns
-------
match : :class:`~graph_tool.VertexPropertyMap`
Vertex property map with the vertex matched to each vertex (or the
largest value of ``int64_t`` for the unmatched ones). If ``edges ==
True`` a boolean-valued edge property map is returned instead.
See Also
--------
maximum_cardinality_matching: Matching with the largest number of edges
approx_minimum_maximal_matching: Approximate minimum maximal matching
Notes
-----
A
`matching <https://en.wikipedia.org/wiki/Matching_(graph_theory)>`_
is a set of edges no two of which share an endpoint. With ``minimize ==
False``, the matching :math:`M` returned maximizes the total weight
:math:`\sum_{e\in M}w_e` among all matchings. It contains no edges of
negative weight, and it is in general not a maximum cardinality matching
(see :func:`maximum_cardinality_matching`), since an edge may be heavier
than two edges that share its endpoints.
With ``minimize == True``, the matching returned has the smallest total
weight among the matchings of maximum cardinality, since otherwise the
empty matching would be the minimum for nonnegative weights. It is
obtained by maximizing the total weight with the weights :math:`C - w_e`,
where :math:`C` is larger than twice the sum of :math:`|w_e|`, so that
every matching with more edges has a larger total. For floating-point
weights, matchings whose total weights differ by less than the rounding
error of :math:`C` may not be distinguished.
The weighted blossom algorithm of Edmonds [edmonds-maximum-1965]_
[galil-efficient-1986]_ [boost-max-weighted-matching]_ is used, which
takes time :math:`O(V^3)`. If ``bipartite`` is given, the Hungarian method
[kuhn-hungarian-1955]_ is used instead. With ``brute_force == True``, all
the matchings are enumerated, in time :math:`O(2^E)`. Self-loops are
ignored, and of the parallel edges between two vertices only the one with
the largest weight (the smallest with ``minimize == True``) is used.
If ``heuristic == True``, the vertices are visited in random order, and
every unmatched vertex is matched to an unmatched neighbor along an edge
of largest weight (smallest with ``minimize == True``), with ties broken
at random [matching-heuristic]_. The result is a maximal matching, i.e.
no edge can be added to it, which only approximates the optimal one, in
time :math:`O(V + E)`.
Examples
--------
The matching of maximum weight can have fewer edges than a maximum
cardinality matching, as in the following example, where the weights are
the differences between the indices of the endpoints:
>>> g = gt.collection.data["karate"]
>>> w = g.new_ep("double", vals=[abs(int(e.source()) - int(e.target()))
... for e in g.edges()])
>>> m = gt.maximum_weight_matching(g, w, edges=True)
>>> print(m.a.sum(), (m.a * w.a).sum())
11 177.0
>>> m = gt.maximum_weight_matching(g, w, minimize=True, edges=True)
>>> print(m.a.sum(), (m.a * w.a).sum())
13 96.0
>>> print(gt.maximum_cardinality_matching(g, edges=True).a.sum())
13
References
----------
.. [edmonds-maximum-1965] Jack Edmonds, "Maximum matching and a
polyhedron with 0,1-vertices", Journal of Research of the National
Bureau of Standards B 69, 125-130 (1965),
:doi:`10.6028/jres.069B.013`
.. [galil-efficient-1986] Zvi Galil, "Efficient algorithms for finding
maximum matching in graphs", ACM Computing Surveys 18, 23-38 (1986),
:doi:`10.1145/6462.6502`
.. [kuhn-hungarian-1955] Harold W. Kuhn, "The Hungarian method for the
assignment problem", Naval Research Logistics Quarterly 2, 83-97
(1955), :doi:`10.1002/nav.3800020109`
.. [boost-max-weighted-matching] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/network_flow/maximum_weighted_matching.html
.. [matching-heuristic] B. Hendrickson and R. Leland. "A Multilevel Algorithm
for Partitioning Graphs." In S. Karin, editor, Proc. Supercomputing ’95,
San Diego. ACM Press, New York, 1995, :doi:`10.1145/224170.224228`
"""
_check_prop_scalar(weight, "weight")
match = g.new_vp("int64_t")
u = GraphView(g, directed=False)
if heuristic:
libgraph_tool_structure.random_matching(u, weight, match, minimize,
_get_rng())
elif bipartite is False:
libgraph_tool_structure.get_max_weighted_matching(u, weight, match,
brute_force,
minimize)
else:
if isinstance(bipartite, VertexPropertyMap):
_check_prop_scalar(bipartite, "bipartite")
partition = bipartite
else:
is_bip, partition = is_bipartite(u, partition=True)
if not is_bip:
raise ValueError("Supplied graph is not bipartite")
libgraph_tool_structure.get_max_bip_weighted_matching(u, partition,
weight, match,
minimize)
if edges:
ematch = g.new_ep("bool")
# for parallel edges, the one with the best weight is marked
libgraph_tool_structure.match_edges(u, match, ematch, weight, minimize)
return ematch
return match
[docs]
@_check_props(v=("mivs",))
def maximal_independent_vertex_set(g, high_deg=False, mivs=None):
r"""Find a maximal independent vertex set in the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
high_deg : bool (optional, default: ``False``)
If ``True``, vertices with high degree will be included first in the
set, otherwise they will be included last.
mivs : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex property map where the vertex set will be specified.
Returns
-------
mivs : :class:`~graph_tool.VertexPropertyMap`
Boolean vertex property map where the set is specified.
See Also
--------
largest_independent_vertex_sets: Independent vertex sets of maximum size
maximal_independent_vertex_sets: All maximal independent vertex sets
independence_number: Size of the largest independent vertex set
clique_removal: Approximate maximum independent vertex set
Notes
-----
A maximal independent vertex set is an independent set such that adding any
other vertex to the set forces the set to contain an edge between two
vertices of the set.
This implements the algorithm described in [mivs-luby]_, which runs in time
:math:`O(V + E)`.
Examples
--------
.. testcode::
:hide:
import numpy.random
numpy.random.seed(43)
gt.seed_rng(43)
>>> g = gt.GraphView(gt.price_network(300), directed=False)
>>> res = gt.maximal_independent_vertex_set(g)
>>> gt.graph_draw(g, vertex_fill_color=res, output="mivs.pdf")
<...>
.. testcleanup::
conv_png("mivs.pdf")
.. figure:: mivs.png
:align: center
:width: 80%
Vertices belonging to the set are in yellow.
References
----------
.. [mivs-wikipedia] http://en.wikipedia.org/wiki/Independent_set_%28graph_theory%29
.. [mivs-luby] Luby, M., "A simple parallel algorithm for the maximal independent set problem",
Proc. 17th Symposium on Theory of Computing, Association for Computing Machinery, pp. 1-10, (1985)
:doi:`10.1145/22145.22146`.
"""
if mivs is None:
mivs = g.new_vertex_property("bool")
_check_prop_scalar(mivs, "mivs")
_check_prop_writable(mivs, "mivs")
u = GraphView(g, directed=False)
libgraph_tool_structure.\
maximal_vertex_set(u, mivs, high_deg,
_get_rng())
mivs = g.own_property(mivs)
return mivs
[docs]
@_parallel
@_check_props(e=("weight",))
def edge_reciprocity(g, weight=None, self_loops=False, kind="graph"):
r"""Calculate the edge reciprocity of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights.
self_loops : ``bool`` (optional, default: ``False``)
Whether self-loops should be considered.
kind : ``str`` (optional, default: ``"graph"``)
If ``"graph"``, the reciprocity of the whole graph is returned; if
``"vertex"`` or ``"edge"``, that of every vertex or edge.
Returns
-------
reciprocity : ``float``, :class:`~graph_tool.VertexPropertyMap`, or :class:`~graph_tool.EdgePropertyMap`
The reciprocity value, or the values of the vertices or edges.
See Also
--------
graph_tool.clustering.dyad_census: Counts of the dyad types
graph_tool.clustering.triad_census: Counts of the triad types
graph_tool.correlations.assortativity: Degree assortativity coefficient
Notes
-----
The edge [reciprocity]_ is defined as :math:`E^\leftrightarrow/E`, where
:math:`E^\leftrightarrow` and :math:`E` are the number of bidirectional and
all edges in the graph, respectively. If ``self_loops is False``, self-loops
are not considered in these counts.
If weights are provided, the number of edges is replaced by the sum of edge
weights.
With :math:`W_{uv}` the total weight of the edges from :math:`u` to
:math:`v`, the reciprocity of a vertex :math:`v` (``kind == "vertex"``)
is
.. math::
r_v = \frac{2\sum_u \min(W_{vu}, W_{uv})}{\sum_u W_{vu} + \sum_u W_{uv}},
which for unweighted graphs without parallel edges is the fraction of the
in- and out-neighbors of :math:`v` connected to it in both directions,
and that of an edge :math:`(u, v)`
(``kind == "edge"``) is :math:`\min(W_{uv}, W_{vu})/W_{uv}`, so that the
reciprocity of the graph is the weighted average of the edge values.
Vertices without edges, and excluded self-loops, get the value ``nan``.
The algorithm runs with complexity :math:`O(E + V)`.
@parallel@
Examples
--------
>>> g = gt.Graph()
>>> g.add_vertex(2)
<...>
>>> g.add_edge(g.vertex(0), g.vertex(1))
<...>
>>> gt.edge_reciprocity(g)
0.0
>>> g.add_edge(g.vertex(1), g.vertex(0))
<...>
>>> gt.edge_reciprocity(g)
1.0
>>> g = gt.collection.data["pgp-strong-2009"]
>>> gt.edge_reciprocity(g)
0.692196963163...
>>> r = gt.edge_reciprocity(g, kind="vertex")
>>> print(np.nanmean(r.fa))
0.705471920296...
References
----------
.. [reciprocity] S. Wasserman and K. Faust, "Social Network Analysis".
(Cambridge University Press, Cambridge, 1994)
.. [lopez-reciprocity-2007] Gorka Zamora-López, Vinko Zlatić, Changsong
Zhou, Hrvoje Štefančić, and Jürgen Kurths "Reciprocity of networks with
degree correlations and arbitrary degree sequences", Phys. Rev. E 77,
016106 (2008) :doi:`10.1103/PhysRevE.77.016106`, :arxiv:`0706.3372`
"""
if weight is not None:
_check_prop_scalar(weight, name="weight")
if kind == "graph":
return libgraph_tool_structure.reciprocity(g, weight, self_loops)
if kind == "vertex":
r = g.new_vp("double")
libgraph_tool_structure.local_reciprocity(g, weight, self_loops,
r, None)
elif kind == "edge":
r = g.new_ep("double")
libgraph_tool_structure.local_reciprocity(g, weight, self_loops,
None, r)
else:
raise ValueError("invalid kind: " + str(kind))
return r
[docs]
@_check_props(e=("weight",))
def tsp_tour(g, src, weight=None, method="mst", improve=None, t0=None,
alpha=0.99, niter=1000):
r"""Return a traveling salesman tour of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. The graph must be undirected.
src : :class:`~graph_tool.Vertex`
The source (and target) of the tour.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights.
method : ``str`` (optional, default: ``"mst"``)
Construction of the tour: ``"mst"`` (preorder of a minimum spanning
tree), ``"christofides"``, or ``"greedy"`` (nearest neighbor).
improve : ``str`` (optional, default: ``None``)
If given, the tour is improved with random 2-opt moves by
``"simulated_annealing"`` or ``"threshold_accepting"``.
t0 : ``float`` (optional, default: ``None``)
Initial temperature (or threshold) of the improvement; if not given,
5% of the mean length of a tour step.
alpha : ``float`` (optional, default: ``0.99``)
Factor by which the temperature (or threshold) is multiplied after
every :math:`V` moves.
niter : ``int`` (optional, default: ``1000``)
Number of sweeps of :math:`V` moves of the improvement.
Returns
-------
tour : :class:`numpy.ndarray`
List of vertex indices corresponding to the tour.
See Also
--------
eulerian_path: Path that traverses every edge once
tournament_hamiltonian_path: Hamiltonian path of a tournament
minimum_spanning_tree: Minimum spanning tree used by the approximation
Notes
-----
With ``method == "mst"``, the vertices are visited in the preorder of a
minimum spanning tree of the graph (not of its metric closure, so that
consecutive vertices need not be adjacent), which is guaranteed to be at
most twice as long as the optimal tour for complete graphs with metric
weights. The algorithm runs with :math:`O(E\log V)` complexity.
The other methods work on the metric closure, i.e. on the shortest-path
distances between all pairs of vertices, which take time
:math:`O(V E)` and memory :math:`O(V^2)`; consecutive vertices of the
tour are joined by shortest paths in the graph. Christofides' algorithm
[christofides-worst-1976]_ adds a minimum-weight perfect matching of the
odd-degree vertices of a minimum spanning tree and shortcuts an Eulerian
circuit, which is within a factor :math:`3/2` of the optimum, in time
:math:`O(V^3)`. The nearest-neighbor tour visits next the closest
unvisited vertex, in time :math:`O(V^2)`. Simulated annealing
[kirkpatrick-optimization-1983]_ and threshold accepting
[dueck-threshold-1990]_ reverse random segments of the tour, accepting
increases in length with the Metropolis probability or below a
threshold, both of which decrease geometrically; the best tour found is
returned.
Examples
--------
>>> g = gt.lattice([10, 10])
>>> tour = gt.tsp_tour(g, g.vertex(0))
>>> print(tour)
[ 0 1 2 11 12 21 22 31 32 41 42 51 52 61 62 71 72 81 82 83 73 63 53 43
33 23 13 3 4 5 6 7 8 9 19 29 39 49 59 69 79 89 14 24 34 44 54 64
74 84 91 92 93 94 95 85 75 65 55 45 35 25 15 16 17 18 27 28 37 38 47 48
57 58 67 68 77 78 87 88 97 98 99 26 36 46 56 66 76 86 96 10 20 30 40 50
60 70 80 90 0]
The other methods give shorter tours:
.. testsetup:: tsp
gt.seed_rng(42)
.. doctest:: tsp
>>> g = gt.lattice([10, 10])
>>> d = gt.shortest_distance(g).get_2d_array(range(100))
>>> length = lambda t: d[t[:-1], t[1:]].sum()
>>> for m in ["mst", "greedy", "christofides"]:
... print(m, length(gt.tsp_tour(g, 0, method=m)))
mst 160
greedy 108
christofides 108
>>> t = gt.tsp_tour(g, 0, method="christofides",
... improve="simulated_annealing")
>>> print(length(t))
100
The last tour can be drawn over the lattice:
.. doctest:: tsp
>>> pos = g.new_vp("vector<double>",
... vals=[(i % 10, i // 10) for i in range(100)])
>>> h = gt.Graph(list(zip(t[:-1], t[1:])), directed=False)
>>> gt.graph_draw(h, pos, vertex_fill_color="#cccccc",
... edge_color="#e41a1c", edge_pen_width=2,
... output="tsp_tour-lattice.pdf")
<...>
.. testcleanup:: tsp
conv_png("tsp_tour-lattice.pdf")
.. figure:: tsp_tour-lattice.png
:align: center
:width: 40%
Tour of a :math:`10\times 10` lattice obtained with the
Christofides algorithm and improved by simulated annealing, with its
edges shown in red.
References
----------
.. [tsp-bgl] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/utility/metric_tsp_approx.html
.. [tsp] http://en.wikipedia.org/wiki/Travelling_salesman_problem
.. [christofides-worst-1976] Nicos Christofides, "Worst-case analysis of
a new heuristic for the travelling salesman problem", Technical Report
388, Graduate School of Industrial Administration, Carnegie Mellon
University (1976).
.. [kirkpatrick-optimization-1983] S. Kirkpatrick, C. D. Gelatt and M. P.
Vecchi, "Optimization by simulated annealing", Science 220, 671-680
(1983), :DOI:`10.1126/science.220.4598.671`
.. [dueck-threshold-1990] Gunter Dueck and Tobias Scheuer, "Threshold
accepting: A general purpose optimization algorithm appearing superior
to simulated annealing", Journal of Computational Physics 90, 161-175
(1990), :DOI:`10.1016/0021-9991(90)90201-B`
"""
if g.is_directed():
raise ValueError("The graph must be undirected.")
if method not in ["mst", "christofides", "greedy"]:
raise ValueError(f"invalid method: {method}")
if improve not in [None, "simulated_annealing", "threshold_accepting"]:
raise ValueError(f"invalid improvement: {improve}")
def mst_tour():
# the tour of the minimum spanning tree heuristic, in the vertex
# indices of g
tour = libgraph_tool_structure.get_tsp(g, int(src), weight)
return tour.a.copy()
if method == "mst" and improve is None:
return mst_tour()
vs = g.get_vertices()
if len(label_components(g)[1]) > 1:
raise ValueError("The graph must be connected.")
D = shortest_distance(g, weights=weight).get_2d_array(vs).T
D = numpy.ascontiguousarray(D[:, vs], dtype="double")
idx = numpy.full(g.num_vertices(True), -1, dtype="int64")
idx[vs] = numpy.arange(len(vs))
s = int(idx[int(src)])
anneal = {None: 0, "simulated_annealing": 1,
"threshold_accepting": 2}[improve]
if t0 is None:
t0 = 0.05 * D.sum() / max(len(vs) * (len(vs) - 1), 1)
if method == "mst":
t = idx[mst_tour()]
tour = libgraph_tool_structure.tsp_improve(D, numpy.asarray(t,
"int64"),
anneal, float(t0),
float(alpha), int(niter),
_get_rng())
else:
m = 1 if method == "christofides" else 0
tour = libgraph_tool_structure.tsp_heuristic(D, s, m, anneal,
float(t0), float(alpha),
int(niter), _get_rng())
return vs[numpy.asarray(tour, dtype="int64")]
[docs]
@_check_props(v=("order", "color"))
def sequential_vertex_coloring(g, order=None, color=None, strategy=None):
r"""Returns a vertex coloring of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
order : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Scalar vertex property map with the rank of each vertex in the order
with which the vertices will be colored: vertices with smaller values
are colored first, and ties are broken by the vertex index. If not
given, the vertices are colored in the order of their indices.
color : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Integer-valued vertex property map to store the colors.
strategy : ``str`` (optional, default: ``None``)
If given, the order is determined by one of the strategies
``"largest_first"``, ``"smallest_last"``, ``"independent_set"``,
``"connected_sequential_bfs"``, ``"connected_sequential_dfs"``,
``"saturation_largest_first"``, or ``"random_sequential"`` (see below),
and ``order`` is ignored.
Returns
-------
color : :class:`~graph_tool.VertexPropertyMap`
Integer-valued vertex property map with the vertex colors.
See Also
--------
dsatur_vertex_coloring: Coloring with the DSatur heuristic
equitable_vertex_coloring: Coloring with color classes of nearly equal size
edge_coloring: Proper edge coloring
chromatic_polynomial: Number of proper colorings
Notes
-----
Each vertex receives the smallest color not used by its neighbors that
have already been colored. The direction of the edges is ignored, so
that adjacent vertices always receive different colors (except for
vertices with self-loops).
The time complexity is :math:`O(V(d+k))`, where :math:`V` is the number of
vertices, :math:`d` is the maximum degree of the vertices in the graph, and
:math:`k` is the number of colors used.
Every vertex gets the smallest color not used by its neighbors colored
before it. The strategies
order the vertices of the simple undirected graph underlying ``g`` as
follows, with ties broken by the smallest vertex index:
.. csv-table::
:header: "Strategy", "Order"
:widths: 10, 30
``"largest_first"``, "Decreasing degree [welsh-upper-1967]_."
``"smallest_last"``, "Reverse of the order in which a vertex of
smallest degree is removed repeatedly [matula-smallest-1983]_, which
uses at most one color more than the degeneracy."
``"independent_set"``, "Maximal independent sets, each built by
taking repeatedly a vertex of smallest degree among the remaining
candidates, are removed in turn."
``"connected_sequential_bfs"``, "Breadth-first order of every
connected component, from its smallest vertex."
``"connected_sequential_dfs"``, "Depth-first order of every connected
component, from its smallest vertex."
``"saturation_largest_first"``, "The DSatur order, in which the next
vertex has the most distinct colors among its neighbors (see
:func:`dsatur_vertex_coloring`)."
``"random_sequential"``, "Uniformly random order."
The strategies take time :math:`O((V + E)\log V)`, except
``"independent_set"``, which takes :math:`O(k(V + E)\log V)` for
:math:`k` colors.
Examples
--------
>>> g = gt.lattice([10, 10])
>>> colors = gt.sequential_vertex_coloring(g)
>>> print(colors.a)
[0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1
0 1 0 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 0 1 1 0 1 0
1 0 1 0 1 0 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0]
>>> g = gt.collection.data["football"]
>>> for s in ["largest_first", "smallest_last", "independent_set"]:
... c = gt.sequential_vertex_coloring(g, strategy=s)
... print(s, c.a.max() + 1)
largest_first 9
smallest_last 9
independent_set 10
The coloring with the largest-first strategy can be shown in a drawing:
>>> c = gt.sequential_vertex_coloring(g, strategy="largest_first")
>>> palette = np.array(["#9bbedc", "#f28c8e", "#a6d7a4", "#cba6d1",
... "#ffbf7f", "#ffff99", "#d2aa93", "#fbc0df",
... "#cccccc"])
>>> vcolor = g.new_vp("string", vals=palette[c.a])
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color="#999999",
... output="sequential_vertex_coloring-football.pdf")
<...>
.. testcleanup::
conv_png("sequential_vertex_coloring-football.pdf")
.. figure:: sequential_vertex_coloring-football.png
:align: center
:width: 60%
Vertex coloring with nine colors of the network of American college
football games obtained with the largest-first strategy.
References
----------
.. [welsh-upper-1967] D. J. A. Welsh and M. B. Powell, "An upper bound
for the chromatic number of a graph and its application to timetabling
problems", The Computer Journal 10, 85-86 (1967),
:doi:`10.1093/comjnl/10.1.85`
.. [matula-smallest-1983] David W. Matula and Leland L. Beck,
"Smallest-last ordering and clustering and graph coloring algorithms",
Journal of the ACM 30, 417-427 (1983), :doi:`10.1145/2402.322385`
.. [sgc-bgl] https://www.boost.org/doc/libs/latest/libs/graph/doc/html/graph/algorithms/coloring/sequential_vertex_coloring.html
.. [graph-coloring] http://en.wikipedia.org/wiki/Graph_coloring
"""
if color is None:
color = g.new_vertex_property("int")
if strategy is not None:
strategies = ["largest_first", "smallest_last", "independent_set",
"connected_sequential_bfs", "connected_sequential_dfs",
"random_sequential"]
if strategy == "saturation_largest_first":
c = dsatur_vertex_coloring(GraphView(g, directed=False))
color.fa = c.fa
return color
if strategy not in strategies:
raise ValueError("invalid strategy: " + str(strategy))
libgraph_tool_structure.strategy_coloring(g,
strategies.index(strategy),
color, _get_rng())
return color
if order is None:
order = g.vertex_index
else:
_check_prop_scalar(order, "order")
# The C++ function expects the i-th vertex to be colored at position i
# of the map, which is the inverse of the rank given by the user.
vs = g.get_vertices()
seq = vs[numpy.argsort(order.fa, kind="stable")]
mask = numpy.ones(g.num_vertices(True), dtype="bool")
mask[vs] = False
order = g.new_vertex_property("int64_t")
order.a = numpy.concatenate((seq, numpy.where(mask)[0]))
# the neighbors in both directions must receive different colors
if g.is_directed():
g = GraphView(g, directed=False)
libgraph_tool_structure.\
sequential_coloring(g,
order,
color)
return color
[docs]
def transitive_reduction(g, tr_map=None):
r"""Return the transitive reduction of a directed acyclic graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed acyclic graph to be used.
tr_map : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If provided, the edges of the reduction will be marked in this
property map.
Returns
-------
tr_map : :class:`~graph_tool.EdgePropertyMap`
Boolean edge property map marking the edges of the transitive
reduction.
See Also
--------
transitive_closure: Inverse operation
topological_sort: Topological ordering of a directed acyclic graph
graph_tool.generation.condensation_graph: Graph of the strong components
Notes
-----
The
`transitive reduction <https://en.wikipedia.org/wiki/Transitive_reduction>`_
[aho-transitive-1972]_ is the graph with the
fewest edges that has the same reachability as the original one. For a
directed acyclic graph it is unique, and consists of the edges
:math:`(u, v)` such that :math:`v` cannot be reached from :math:`u` by a
path of two or more edges. Of a set of parallel edges, only one is kept.
A search is made from every vertex, in parallel, with a total time of
:math:`O(VE)` in the worst case and :math:`O(V)` memory per thread.
@parallel@
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (0, 2), (2, 3), (0, 3)])
>>> tr = gt.transitive_reduction(g)
>>> print(gt.GraphView(g, efilt=tr).get_edges())
[[0 1]
[1 2]
[2 3]]
The edges kept and removed can be shown in a drawing:
>>> pos = g.new_vp("vector<double>", vals=[(0, 0), (1, 1), (2, 0),
... (3, 1)])
>>> ecolor = g.new_ep("string", vals=np.where(tr.a, "#e41a1c",
... "#999999"))
>>> gt.graph_draw(g, pos, vertex_text=g.vertex_index,
... vertex_fill_color="#cccccc", edge_color=ecolor,
... vertex_size=25, edge_pen_width=2,
... output="transitive_reduction-dag.pdf")
<...>
.. testcleanup::
conv_png("transitive_reduction-dag.pdf")
.. figure:: transitive_reduction-dag.png
:align: center
:width: 40%
Transitive reduction of a directed acyclic graph of four vertices.
The edges of the reduction are shown in red, and the edges removed in
gray.
References
----------
.. [aho-transitive-1972] Alfred V. Aho, Michael R. Garey and Jeffrey D.
Ullman, "The transitive reduction of a directed graph", SIAM Journal on
Computing 1, 131-137 (1972), :DOI:`10.1137/0201008`
.. [transitive-reduction-wiki] https://en.wikipedia.org/wiki/Transitive_reduction
"""
if not g.is_directed() or not is_DAG(g):
raise ValueError("The graph must be a directed acyclic graph.")
if tr_map is None:
tr_map = g.new_ep("bool")
_check_prop_writable(tr_map, name="tr_map")
libgraph_tool_structure.transitive_reduction(g,
tr_map)
return tr_map
[docs]
def eulerian_path(g, source=None, circuit=False, edges=False):
r"""Return an Eulerian path or circuit, i.e. one that traverses every edge
exactly once.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex` or ``int`` (optional, default: ``None``)
If given, the path will start at this vertex.
circuit : ``bool`` (optional, default: ``False``)
If ``True``, only a closed path (an Eulerian circuit) is returned.
edges : ``bool`` (optional, default: ``False``)
If ``True``, the path is returned as a sequence of edge indices instead
of vertices.
Returns
-------
path : :class:`numpy.ndarray` or ``None``
The vertices (:math:`E + 1` of them) or the edge indices of the path,
or ``None`` if there is no Eulerian path (or circuit) starting at
``source``.
See Also
--------
eulerize: Edges to duplicate to make a graph Eulerian
tsp_tour: Tour that visits every vertex
tournament_hamiltonian_path: Path that visits every vertex of a tournament
Notes
-----
An undirected graph has an
`Eulerian path <https://en.wikipedia.org/wiki/Eulerian_path>`_
if the vertices with edges are
connected and at most two of them have an odd degree, in which case the
path starts and ends at them; for a circuit, all degrees must be even. A
directed graph has one if the vertices with edges are weakly connected,
and the out-degree of every vertex equals its in-degree, except possibly
for a start vertex with one more out-edge and an end vertex with one more
in-edge. The path is found with the algorithm of Hierholzer
[hierholzer-moglichkeit-1873]_ in :math:`O(V + E)` time.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (2, 0), (0, 3), (3, 4), (4, 0)],
... directed=False)
>>> print(gt.eulerian_path(g, circuit=True))
[0 1 2 0 3 4 0]
The order in which the edges are traversed can be shown in a drawing:
>>> es = gt.eulerian_path(g, circuit=True, edges=True)
>>> step = g.new_ep("int")
>>> step.a[es] = np.arange(1, len(es) + 1)
>>> pos = g.new_vp("vector<double>", vals=[(0, 0), (-1, -1), (-1, 1),
... (1, 1), (1, -1)])
>>> gt.graph_draw(g, pos, vertex_text=g.vertex_index,
... vertex_fill_color="#cccccc", edge_color="#999999",
... edge_text=step, vertex_size=40, vertex_font_size=18,
... edge_font_size=18,
... output="eulerian_path-bowtie.pdf")
<...>
.. testcleanup::
conv_png("eulerian_path-bowtie.pdf")
.. figure:: eulerian_path-bowtie.png
:align: center
:width: 30%
Eulerian circuit of a graph of two triangles that share a vertex,
with the edges labeled by their position in the circuit.
References
----------
.. [hierholzer-moglichkeit-1873] Carl Hierholzer and Chr. Wiener, "Ueber
die Möglichkeit, einen Linienzug ohne Wiederholung und ohne
Unterbrechung zu umfahren", Mathematische Annalen 6, 30-32 (1873),
:DOI:`10.1007/BF01442866`
.. [eulerian-wiki] https://en.wikipedia.org/wiki/Eulerian_path
"""
source = -1 if source is None else int(source)
ret = libgraph_tool_structure.eulerian_path(g, source,
circuit)
if ret is None:
return None
return ret[1] if edges else ret[0]
[docs]
def feedback_arc_set(g, weight=None, fas=None, exact=False):
r"""Return a set of edges whose removal leaves the graph without cycles.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights. If given, a set with a small total weight is sought.
fas : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If provided, the edges of the set will be marked in this property map.
exact : ``bool`` (optional, default: ``False``)
If ``True``, a set of minimum weight is returned for directed graphs,
which is feasible only if the strongly connected components are small
(see below).
Returns
-------
fas : :class:`~graph_tool.EdgePropertyMap`
Boolean edge property map marking the edges of the feedback arc set.
See Also
--------
feedback_vertex_set: Vertex counterpart
is_DAG: Test for directed acyclic graphs
find_cycle: A single cycle of the graph
Notes
-----
For undirected graphs, the edges outside a maximum-weight spanning forest
are returned, which is a set of minimum weight.
For directed graphs, finding a minimum
`feedback arc set <https://en.wikipedia.org/wiki/Feedback_arc_set>`_
is NP-hard, and
the heuristic of Eades, Lin, and Smyth [eades-fast-1993]_ is used instead:
the vertices are arranged in a sequence by repeatedly moving the sinks to
its end and the sources to its start, and otherwise the vertex with the
largest difference between the total weight of its out- and in-edges to
its start; the edges that point backwards in the sequence form the set.
Self-loops are always part of it. The algorithm runs in time
:math:`O((V + E)\log V)`.
With ``exact == True``, a minimum set is found for directed graphs in
every strongly connected component separately, as the backward edges of
the ordering of its vertices that minimizes their total weight, by dynamic
programming over the subsets of vertices: the smallest cost of a set of
vertices placed first is the minimum, over its last vertex :math:`v`, of
the cost of the rest plus the weight of the edges from :math:`v` to it.
This takes time :math:`O(2^n n)` and memory :math:`O(2^n)` for a
component of :math:`n` vertices, and a :class:`ValueError` is raised if a
component has more than 24 vertices.
Examples
--------
>>> g = gt.collection.data["celegansneural"]
>>> fas = gt.feedback_arc_set(g)
>>> u = gt.GraphView(g, efilt=fas.fa == 0)
>>> print(fas.fa.sum(), gt.is_DAG(u))
499 True
For a small graph, the heuristic can be compared with the minimum set:
.. testcode::
:hide:
gt.seed_rng(43)
np.random.seed(43)
>>> g = gt.random_graph(20, lambda: (3, 3))
>>> print(gt.feedback_arc_set(g).fa.sum(),
... gt.feedback_arc_set(g, exact=True).fa.sum())
20 14
The minimum set can be shown in a drawing of this graph:
.. testcode::
:hide:
gt.seed_rng(42)
>>> fas = gt.feedback_arc_set(g, exact=True)
>>> pos = gt.sfdp_layout(g)
>>> ecolor = g.new_ep("string", vals=np.where(fas.a, "#e41a1c",
... "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(fas.a, 2.5, 1))
>>> gt.graph_draw(g, pos, vertex_fill_color="#cccccc", edge_color=ecolor,
... edge_pen_width=ewidth,
... output="feedback_arc_set-random.pdf")
<...>
.. testcleanup::
conv_png("feedback_arc_set-random.pdf")
.. figure:: feedback_arc_set-random.png
:align: center
:width: 50%
Minimum feedback arc set of a random directed graph of 20 vertices
with in- and out-degrees three, with its edges shown in red.
References
----------
.. [eades-fast-1993] Peter Eades, Xuemin Lin and W. F. Smyth, "A fast and
effective heuristic for the feedback arc set problem", Information
Processing Letters 47, 319-323 (1993),
:DOI:`10.1016/0020-0190(93)90079-O`
"""
if weight is None:
weight = g.new_ep("double", val=1)
if fas is None:
fas = g.new_ep("bool")
_check_prop_writable(fas, name="fas")
libgraph_tool_structure.feedback_arc_set(g,
weight,
fas, exact)
return fas
[docs]
def feedback_vertex_set(g, weight=None, fvs=None, exact=False):
r"""Return a set of vertices whose removal leaves the graph without cycles.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weight : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex weights. If given, a set with a small total weight is sought.
fvs : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, the vertices of the set will be marked in this property
map.
exact : ``bool`` (optional, default: ``False``)
If ``True``, a set of minimum weight is returned, which is feasible
only for small graphs (see below).
Returns
-------
fvs : :class:`~graph_tool.VertexPropertyMap`
Boolean vertex property map marking the vertices of the feedback
vertex set.
See Also
--------
feedback_arc_set: Edge counterpart
approx_minimum_vertex_cover: Approximate minimum vertex cover
find_cycle: A single cycle of the graph
Notes
-----
Finding a minimum
`feedback vertex set <https://en.wikipedia.org/wiki/Feedback_vertex_set>`_
is NP-hard, and a greedy heuristic
is used instead: the vertices that cannot lie on a cycle of the remaining
graph (those without in- or out-edges, or with at most one edge in
undirected graphs) are removed repeatedly, and otherwise the vertex with
the largest product of in- and out-degrees (or the largest degree, for
undirected graphs), divided by its weight, is put in the set and removed.
Vertices with self-loops are always in the set. The algorithm runs in
time :math:`O((V + E)\log V)`.
With ``exact == True``, the vertices with self-loops are put in the set,
the vertices that cannot lie on a cycle are removed as above, and in
every (strongly) connected component of the remaining graph the
complement of the induced acyclic subgraph of maximum weight is found by
enumerating the subsets of vertices, where a set is acyclic if it has a
vertex without out-neighbors in the rest of the set (or with at most one
edge to it, for undirected graphs), whose removal leaves an acyclic set.
This takes time :math:`O(2^n n)` and memory :math:`O(2^n)` bits for a
component of :math:`n` vertices, and a :class:`ValueError` is raised if a
component has more than 24 vertices.
Examples
--------
>>> g = gt.collection.data["celegansneural"]
>>> fvs = gt.feedback_vertex_set(g)
>>> u = gt.GraphView(g, vfilt=fvs.fa == 0)
>>> print(fvs.fa.sum(), gt.is_DAG(u))
96 True
.. testcode::
:hide:
gt.seed_rng(43)
np.random.seed(43)
>>> g = gt.random_graph(20, lambda: (3, 3))
>>> print(gt.feedback_vertex_set(g).fa.sum(),
... gt.feedback_vertex_set(g, exact=True).fa.sum())
11 6
"""
if weight is None:
weight = g.new_vp("double", val=1)
if fvs is None:
fvs = g.new_vp("bool")
_check_prop_writable(fvs, name="fvs")
libgraph_tool_structure.feedback_vertex_set(g,
weight,
fvs, exact)
return fvs
[docs]
@_parallel
def global_efficiency(g, weight=None):
r"""Return the global efficiency of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights (lengths). If not given, every edge has unit length.
Returns
-------
efficiency : ``float``
The global efficiency.
See Also
--------
local_efficiency: Efficiency of the neighborhood of every vertex
harmonic_diameter: Inverse of the average inverse distance
average_shortest_path_length: Average distance between pairs of vertices
graph_tool.centrality.closeness: Harmonic closeness centrality
Notes
-----
The
`global efficiency <https://en.wikipedia.org/wiki/Efficiency_(network_science)>`_
[latora-efficient-2001]_ is the average of the
inverse distances between all ordered pairs of distinct vertices,
.. math::
E = \frac{1}{V(V-1)}\sum_{u\ne v}\frac{1}{d(u,v)},
where :math:`1/d(u,v) = 0` if :math:`v` cannot be reached from :math:`u`.
The distances are computed with a search from every vertex, in parallel,
in time :math:`O(VE)` without weights, or :math:`O(V(E + V\log V))` with
them.
@parallel@
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.global_efficiency(g))
0.4920083...
References
----------
.. [latora-efficient-2001] Vito Latora and Massimo Marchiori, "Efficient
behavior of small-world networks", Physical Review Letters 87, 198701
(2001), :DOI:`10.1103/PhysRevLett.87.198701`,
:arxiv:`cond-mat/0101396`
"""
w = None if weight is None else weight
return libgraph_tool_structure.global_efficiency(g, w)
[docs]
@_parallel
def local_efficiency(g, weight=None, vprop=None):
r"""Return the local efficiency of every vertex.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights (lengths). If not given, every edge has unit length.
vprop : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, the local efficiencies will be stored in this property
map.
Returns
-------
efficiency : :class:`~graph_tool.VertexPropertyMap`
The local efficiency of every vertex.
See Also
--------
global_efficiency: Efficiency of the whole graph
graph_tool.clustering.local_clustering: Local clustering coefficient
Notes
-----
The
`local efficiency <https://en.wikipedia.org/wiki/Efficiency_(network_science)>`_
[latora-efficient-2001]_ of a vertex :math:`v` is the
global efficiency (see :func:`~graph_tool.structure.global_efficiency`) of
the subgraph induced by its neighbors, without :math:`v` itself, and is
zero if :math:`v` has fewer than two neighbors. For directed graphs, the
neighbors in both directions are used, and the distances among them follow
the directions of the edges. The algorithm runs in time
:math:`O(\sum_v k_v E_v)`, where :math:`E_v` is the number of edges among
the neighbors of :math:`v`, in parallel over the vertices.
@parallel@
Examples
--------
>>> g = gt.collection.data["karate"]
>>> eff = gt.local_efficiency(g)
>>> print(eff.fa.mean())
0.6451265...
The local efficiencies can be visualized by coloring the vertices:
>>> from matplotlib.colors import LinearSegmentedColormap
>>> cmap = LinearSegmentedColormap.from_list("eff", ["#d9d9d9",
... "#7dabd1"])
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=eff, vcmap=cmap,
... edge_color="#999999",
... output="local_efficiency-karate.pdf")
<...>
.. testcleanup::
conv_png("local_efficiency-karate.pdf")
.. figure:: local_efficiency-karate.png
:align: center
:width: 50%
Local efficiencies of the vertices of Zachary's karate club network.
The colors range from gray (zero) to blue (one).
References
----------
.. [latora-efficient-2001] Vito Latora and Massimo Marchiori, "Efficient
behavior of small-world networks", Physical Review Letters 87, 198701
(2001), :DOI:`10.1103/PhysRevLett.87.198701`,
:arxiv:`cond-mat/0101396`
"""
if vprop is None:
vprop = g.new_vp("double")
_check_prop_writable(vprop, name="vprop")
w = None if weight is None else weight
libgraph_tool_structure.local_efficiency(g, w,
vprop)
return vprop
[docs]
def vertex_ordering(g, method="rcm", weight=None, root=None):
r"""Return an ordering of the vertices that reduces the bandwidth of the
adjacency matrix.
Parameters
----------
g : :class:`~graph_tool.Graph`
Undirected graph to be used.
method : ``str`` (optional, default: ``"rcm"``)
Ordering algorithm: ``"cuthill-mckee"``, ``"rcm"`` (reverse
Cuthill-McKee), ``"king"``, ``"sloan"``, ``"min_degree"`` (multiple
minimum degree), ``"smallest_last"``, ``"max_adjacency"`` (maximum
adjacency search), ``"mcs"`` (maximum cardinality search), or
``"spectral"`` (Fiedler vector).
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights, used only by ``"max_adjacency"`` and ``"spectral"``.
root : :class:`~graph_tool.Vertex` or ``int`` (optional, default: ``None``)
First vertex, used only by ``"max_adjacency"`` and ``"mcs"``. If not
given, the first vertex is used.
Returns
-------
order : :class:`numpy.ndarray`
The vertices in their new order.
See Also
--------
bandwidth: Bandwidth and profile of a given ordering
treewidth: Elimination ordering that bounds the treewidth
Notes
-----
The
`Cuthill-McKee algorithm <https://en.wikipedia.org/wiki/Cuthill%E2%80%93McKee_algorithm>`_
[cuthill-reducing-1969]_ orders every connected
component by a breadth-first search from a pseudo-peripheral vertex, with
the neighbors of each vertex in order of increasing degree; its reverse
[george-computer-1981]_ usually gives a smaller profile. The algorithm of
King [king-algorithm-1970]_ chooses the next vertex so that the front of
the search grows as little as possible. The bandwidth and profile of the
resulting ordering are given by :func:`~graph_tool.structure.bandwidth`. The
running time is :math:`O(E\log k_{\max})` for the Cuthill-McKee orderings
and higher for King's.
Sloan's algorithm [sloan-algorithm-1986]_ reduces the profile and the
wavefront, and is applied to every connected component separately; the
candidate list is sorted at every step, so that it takes time
:math:`O(V^2\log V)` in the worst case. The
`multiple minimum degree ordering <https://en.wikipedia.org/wiki/Minimum_degree_algorithm>`_
[liu-modification-1985]_ reduces the fill-in of sparse Cholesky
factorizations, and the smallest-last ordering [matula-smallest-1983]_
removes a vertex of smallest remaining degree at a time and puts it last,
so that every vertex has at most :math:`k` neighbors before it, where
:math:`k` is the degeneracy (useful for
:func:`~graph_tool.structure.sequential_vertex_coloring`). Self-loops and
parallel edges are ignored by the last three methods.
The last two methods do not reduce the bandwidth, but are orderings of
searches used by other algorithms. Maximum adjacency search
[nagamochi-computing-1992]_ visits next the vertex with the largest total
weight of edges to the visited vertices, as in the minimum cut algorithm of
Stoer and Wagner (see :func:`~graph_tool.flow.minimum_cut`), and is
computed in time :math:`O(E\log V)`. Maximum cardinality search [tarjan-simple-1984]_
visits next the vertex with the most visited neighbors, in time
:math:`O(V + E)`; its reverse is a perfect elimination ordering if the
graph is chordal (see :func:`~graph_tool.structure.is_chordal`).
The spectral ordering [barnard-spectral-1995]_ sorts the vertices of
every connected component by their entries in the Fiedler vector of the
component, i.e. the eigenvector of the second smallest eigenvalue of its
Laplacian (see :func:`~graph_tool.spectral.algebraic_connectivity`),
with the components in the order of their labels in
:func:`~graph_tool.structure.label_components`. It tends to reduce the
envelope of the matrix, and places close together vertices that are
close in the graph. The sign of the Fiedler vector is arbitrary, so the
order of a component may be reversed.
Examples
--------
>>> g = gt.collection.data["power"]
>>> order = gt.vertex_ordering(g, "rcm")
>>> print(gt.bandwidth(g), gt.bandwidth(g, order))
4927 455
The effect of the ordering is seen in the nonzero entries of the
adjacency matrix, with the rows and columns in the order of the vertex
indices and in the reverse Cuthill-McKee order:
>>> import matplotlib.pyplot as plt
>>> A = gt.adjacency(g)
>>> fig, ax = plt.subplots(1, 2, figsize=(6, 3))
>>> ax[0].spy(A, markersize=.1, color="#377eb8")
<...>
>>> ax[1].spy(A[order, :][:, order], markersize=.1, color="#377eb8")
<...>
>>> for a in ax:
... a.tick_params(left=False, bottom=False, labelleft=False,
... labeltop=False, top=False)
>>> plt.tight_layout()
>>> plt.savefig("vertex_ordering-power.pdf")
.. testcleanup::
conv_png("vertex_ordering-power.pdf")
.. figure:: vertex_ordering-power.png
:align: center
:width: 70%
Nonzero entries of the adjacency matrix of the western US power
grid, with the vertices in the order of their indices (left) and in
the reverse Cuthill-McKee order (right).
References
----------
.. [cuthill-reducing-1969] E. Cuthill and J. McKee, "Reducing the bandwidth
of sparse symmetric matrices", Proceedings of the 24th National
Conference of the ACM, 157-172 (1969), :DOI:`10.1145/800195.805928`
.. [george-computer-1981] Alan George and Joseph W-H Liu, "Computer
Solution of Large Sparse Positive Definite Systems", Prentice-Hall
(1981).
.. [king-algorithm-1970] Ian P. King, "An automatic reordering scheme for
simultaneous equations derived from network systems", International
Journal for Numerical Methods in Engineering 2, 523-533 (1970),
:DOI:`10.1002/nme.1620020406`
.. [sloan-algorithm-1986] S. W. Sloan, "An algorithm for profile and
wavefront reduction of sparse matrices", International Journal for
Numerical Methods in Engineering 23, 239-251 (1986),
:DOI:`10.1002/nme.1620230208`
.. [liu-modification-1985] Joseph W. H. Liu, "Modification of the
minimum-degree algorithm by multiple elimination", ACM Transactions on
Mathematical Software 11, 141-153 (1985), :DOI:`10.1145/214392.214398`
.. [matula-smallest-1983] David W. Matula and Leland L. Beck,
"Smallest-last ordering and clustering and graph coloring
algorithms", Journal of the ACM 30, 417-427 (1983),
:DOI:`10.1145/2402.322385`
.. [nagamochi-computing-1992] Hiroshi Nagamochi and Toshihide Ibaraki,
"Computing edge-connectivity in multigraphs and capacitated graphs",
SIAM Journal on Discrete Mathematics 5, 54-66 (1992),
:DOI:`10.1137/0405004`
.. [barnard-spectral-1995] Stephen T. Barnard, Alex Pothen and Horst
Simon, "A spectral algorithm for envelope reduction of sparse
matrices", Numerical Linear Algebra with Applications 2, 317-334
(1995), :DOI:`10.1002/nla.1680020402`
.. [tarjan-simple-1984] Robert E. Tarjan and Mihalis Yannakakis, "Simple
linear-time algorithms to test chordality of graphs, test acyclicity
of hypergraphs, and selectively reduce acyclic hypergraphs", SIAM
Journal on Computing 13, 566-579 (1984), :DOI:`10.1137/0213035`
"""
if g.is_directed():
raise ValueError("The graph must be undirected.")
if method not in ["cuthill-mckee", "rcm", "king", "sloan", "min_degree",
"smallest_last", "max_adjacency", "mcs", "spectral"]:
raise ValueError(f"invalid method: {method}")
if method == "spectral":
from .. spectral import _spectral_ordering
return _spectral_ordering(g, weight)
if method == "max_adjacency":
if g.num_vertices() < 2:
return g.get_vertices()
if root is None:
root = g.get_vertices()[0]
return libgraph_tool_structure.max_adjacency_ordering(g, weight,
int(root))
if method == "mcs":
return libgraph_tool_structure.mcs_order(g,
-1 if root is None
else int(root))
return libgraph_tool_structure.vertex_ordering(g, method)
[docs]
def bandwidth(g, order=None, profile=False, wavefront=False):
r"""Return the bandwidth of the adjacency matrix with the given vertex
ordering.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
order : iterable of ``int`` (optional, default: ``None``)
The vertices in their order. If not given, the order of the vertex
indices is used.
profile : ``bool`` (optional, default: ``False``)
If ``True``, the profile is also returned.
wavefront : ``bool`` (optional, default: ``False``)
If ``True``, the maximum, mean, and root-mean-square wavefronts are
also returned.
Returns
-------
bandwidth : ``int``
The largest distance in the ordering between the endpoints of an
edge.
profile : ``int``
The sum, over the vertices :math:`v`, of the distance in the ordering
from :math:`v` back to its first neighbor (or to itself). Only returned
if ``profile == True``.
wavefronts : ``tuple`` of ``float``
The maximum, mean, and root-mean-square, over the positions :math:`i`
of the ordering, of the wavefront: the number of vertices at
positions :math:`j \ge i` that are equal to the vertex at :math:`i`
or adjacent to a vertex at a position :math:`\le i`. Only returned if
``wavefront == True``.
See Also
--------
vertex_ordering: Orderings that reduce the bandwidth
treewidth: Upper bound on the treewidth
Notes
-----
The bandwidth returned is that of the given ordering, and its minimum
over all orderings is the
`bandwidth of the graph <https://en.wikipedia.org/wiki/Graph_bandwidth>`_.
The wavefront is the size of the active front of a frontal solver of
sparse linear systems, which is reduced by Sloan's ordering (see
:func:`~graph_tool.structure.vertex_ordering`), as defined in the Boost
Graph Library. The algorithm runs in time :math:`O(V + E)`.
Examples
--------
>>> g = gt.lattice([10, 10])
>>> print(gt.bandwidth(g, profile=True))
(10, 909)
>>> print(gt.bandwidth(g, wavefront=True))
(10, (11.0, ..., ...))
"""
if order is None:
order = numpy.zeros(0, dtype="int64")
else:
order = numpy.asarray(order, dtype="int64")
bw, prof, wf = libgraph_tool_structure.bandwidth(g, order)
if not profile and not wavefront:
return bw
ret = [bw]
if profile:
ret.append(prof)
if wavefront:
ret.append(wf)
return tuple(ret)
[docs]
def edge_coloring(g, color=None):
r"""Return a proper edge coloring of a simple undirected graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Simple undirected graph to be used.
color : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If provided, the colors will be stored in this property map, which
must be of type ``int32_t``.
Returns
-------
color : :class:`~graph_tool.EdgePropertyMap`
The color of every edge, numbered from zero.
See Also
--------
sequential_vertex_coloring: Vertex coloring
maximum_cardinality_matching: Maximum matching
graph_tool.generation.line_graph: Line graph of a graph
Notes
-----
In a
`proper edge coloring <https://en.wikipedia.org/wiki/Edge_coloring>`_,
the edges incident on the same vertex have
distinct colors. The coloring uses at most :math:`\Delta + 1` colors,
where :math:`\Delta` is the largest degree, as guaranteed by
`Vizing's theorem <https://en.wikipedia.org/wiki/Vizing%27s_theorem>`_,
and is found with the algorithm of Misra and Gries
[misra-constructive-1992]_, in time :math:`O(VE)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> c = gt.edge_coloring(g)
>>> print(c.fa.max() + 1, g.get_total_degrees(g.get_vertices()).max())
17 17
The Petersen graph has maximum degree three, and its edges are colored
with four colors:
>>> g = gt.collection.petersen_graph()
>>> c = gt.edge_coloring(g)
>>> print(c.fa.max() + 1)
4
>>> a = np.pi / 2 + 2 * np.pi * np.arange(5) / 5
>>> pos = g.new_vp("vector<double>",
... vals=list(zip(np.cos(a), -np.sin(a))) +
... list(zip(.5 * np.cos(a), -.5 * np.sin(a))))
>>> palette = np.array(["#e41a1c", "#377eb8", "#4daf4a", "#984ea3"])
>>> ecolor = g.new_ep("string", vals=palette[c.a])
>>> gt.graph_draw(g, pos, vertex_fill_color="#cccccc", edge_color=ecolor,
... vertex_size=30, edge_pen_width=3,
... output="edge_coloring-petersen.pdf")
<...>
.. testcleanup::
conv_png("edge_coloring-petersen.pdf")
.. figure:: edge_coloring-petersen.png
:align: center
:width: 40%
Proper edge coloring of the Petersen graph with four colors.
References
----------
.. [misra-constructive-1992] Jayadev Misra and David Gries, "A
constructive proof of Vizing's theorem", Information Processing Letters
41, 131-133 (1992), :DOI:`10.1016/0020-0190(92)90041-S`
"""
if g.is_directed():
raise ValueError("The graph must be undirected.")
if numpy.any(label_self_loops(g, mark_only=True).fa):
raise ValueError("The graph must not have self-loops.")
if numpy.any(label_parallel_edges(g, mark_only=True).fa):
raise ValueError("The graph must not have parallel edges.")
if color is None:
color = g.new_ep("int32_t")
if color.value_type() != "int32_t":
raise ValueError("The color map must be of type int32_t.")
libgraph_tool_structure.edge_coloring(g, color)
return color
[docs]
def cycle_ratio(g, weight, time=None, maximum=True, cycle=False):
r"""Return the maximum (or minimum) ratio of the total weight to the total
time of the directed cycles.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed graph to be used.
weight : :class:`~graph_tool.EdgePropertyMap`
Edge weights.
time : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge times. If not given, every edge has unit time, and the cycle mean
is obtained.
maximum : ``bool`` (optional, default: ``True``)
If ``True``, the maximum ratio is returned, otherwise the minimum.
cycle : ``bool`` (optional, default: ``False``)
If ``True``, the edge indices of an optimal cycle are also returned.
Returns
-------
ratio : ``float``
The optimal ratio, or :math:`\mp\infty` if there are no cycles.
cycle : :class:`numpy.ndarray`
The edge indices of an optimal cycle. Only returned if ``cycle ==
True``.
See Also
--------
find_negative_cycle: Cycle of negative total weight
all_circuits: All cycles of a directed graph
Notes
-----
The value returned is the maximum (or minimum) cycle ratio
.. math::
\rho = \max_{C}\frac{\sum_{e\in C}w_e}{\sum_{e\in C}t_e},
where :math:`C` runs over the directed cycles of the graph, :math:`w_e`
is the weight and :math:`t_e` the time of edge :math:`e` (:math:`t_e =
1` if no times are given, so that :math:`\rho` is the maximum mean
weight of a cycle), which requires the total time of every cycle to be
positive. It is optimized with Howard's policy iteration algorithm
[dasdan-experimental-2004]_, which is typically fast, although its
worst-case complexity is not known to be polynomial.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (2, 0), (1, 0)])
>>> w = g.new_ep("double", vals=[1, 2, 3, 5])
>>> print(gt.cycle_ratio(g, w, cycle=True))
(3.0, array([0, 3], dtype=uint64))
References
----------
.. [dasdan-experimental-2004] Ali Dasdan, "Experimental analysis of the
fastest optimum cycle ratio and mean algorithms", ACM Transactions on
Design Automation of Electronic Systems 9, 385-418 (2004),
:DOI:`10.1145/1027084.1027085`
"""
if not g.is_directed():
raise ValueError("The graph must be directed.")
weight = weight.copy("double")
time = g.new_ep("double", val=1) if time is None else time.copy("double")
r, c = libgraph_tool_structure.cycle_ratio(g,
weight,
time, maximum)
if cycle:
return r, c
return r
[docs]
def steiner_tree(g, terminals, weights=None, tree_map=None):
r"""Return an approximate minimum Steiner tree connecting the given
terminal vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Undirected graph to be used.
terminals : iterable of :class:`~graph_tool.Vertex` or ``int``
The vertices to be connected.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Nonnegative edge weights. If not given, every edge has unit weight.
tree_map : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If provided, the edges of the tree will be marked in this property
map.
Returns
-------
tree_map : :class:`~graph_tool.EdgePropertyMap`
Boolean edge property map marking the edges of the tree.
See Also
--------
minimum_spanning_tree: Minimum spanning tree
voronoi_cells: Closest terminal of every vertex
connected_dominating_set: Connected set of vertices adjacent to all others
Notes
-----
A
`Steiner tree <https://en.wikipedia.org/wiki/Steiner_tree_problem>`_
of a set of terminals is a subtree of the graph that
contains all the terminals, and possibly other vertices, and a minimum
one minimizes the total weight :math:`\sum_e w_e` of its edges. Finding
it is NP-hard,
and the 2-approximation of Mehlhorn [mehlhorn-faster-1988]_ is used: the
vertices are assigned to their nearest terminal, the shortest connections
between the regions of neighboring terminals form a graph on the
terminals, whose minimum spanning tree is expanded into shortest paths,
and the minimum spanning tree of these paths is pruned of the leaves that
are not terminals. The total weight is at most twice the minimum. The
algorithm runs in time :math:`O(E + V\log V)`.
If the terminals are not all connected, a Steiner forest with a tree for
every connected component is returned.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> tree = gt.steiner_tree(g, [8, 16, 26])
>>> print(tree.fa.sum())
5
The tree can be highlighted in a drawing of the network:
>>> vcolor = g.new_vp("string", val="#cccccc")
>>> for v in [8, 16, 26]:
... vcolor[v] = "#f28c8e"
>>> ecolor = g.new_ep("string", vals=np.where(tree.a, "#e41a1c",
... "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(tree.a, 2.5, 1))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color=ecolor, edge_pen_width=ewidth,
... output="steiner_tree-karate.pdf")
<...>
.. testcleanup::
conv_png("steiner_tree-karate.pdf")
.. figure:: steiner_tree-karate.png
:align: center
:width: 50%
Approximate minimum Steiner tree of vertices 8, 16 and 26 of
Zachary's karate club network. The terminals are shown in red, and
the edges of the tree in red.
References
----------
.. [mehlhorn-faster-1988] Kurt Mehlhorn, "A faster approximation algorithm
for the Steiner problem in graphs", Information Processing Letters 27,
125-128 (1988), :DOI:`10.1016/0020-0190(88)90066-X`
"""
if g.is_directed():
raise ValueError("The graph must be undirected.")
if weights is None:
weights = g.new_ep("double", val=1)
if tree_map is None:
tree_map = g.new_ep("bool")
_check_prop_writable(tree_map, name="tree_map")
terminals = numpy.unique(numpy.asarray([int(v) for v in terminals],
dtype="int64"))
libgraph_tool_structure.steiner_tree(g, terminals,
weights,
tree_map)
return tree_map
[docs]
def approx_minimum_dominating_set(g, weight=None, dset=None):
r"""Return an approximate minimum (weighted) dominating set.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weight : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Positive vertex weights. If not given, every vertex has unit weight.
dset : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, the vertices of the set will be marked in this property
map.
Returns
-------
dset : :class:`~graph_tool.VertexPropertyMap`
Boolean vertex property map marking the vertices of the set.
See Also
--------
connected_dominating_set: Connected dominating set
approx_minimum_edge_dominating_set: Edge counterpart
approx_minimum_vertex_cover: Approximate minimum vertex cover
Notes
-----
A
`dominating set <https://en.wikipedia.org/wiki/Dominating_set>`_
contains, for every vertex, the vertex itself or one of
its neighbors (for directed graphs, one of its in-neighbors). Finding one
of minimum weight is NP-hard, and the greedy algorithm of Chvátal
[chvatal-greedy-1979]_ is used, which repeatedly adds the vertex that
dominates the most new vertices per unit weight. Its total weight is at
most :math:`H(\Delta + 1)\approx \ln \Delta` times the minimum, where
:math:`\Delta` is the largest degree. The algorithm runs in time
:math:`O((V + E)\log V)` in typical cases.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> d = gt.approx_minimum_dominating_set(g)
>>> print(d.fa.sum())
4
The set can be highlighted in a drawing of the network:
>>> vcolor = g.new_vp("string", vals=np.where(d.a, "#f28c8e", "#cccccc"))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color="#999999",
... output="approx_minimum_dominating_set-karate.pdf")
<...>
.. testcleanup::
conv_png("approx_minimum_dominating_set-karate.pdf")
.. figure:: approx_minimum_dominating_set-karate.png
:align: center
:width: 50%
Approximate minimum dominating set of Zachary's karate club network,
with its vertices shown in red.
References
----------
.. [chvatal-greedy-1979] Vašek Chvátal, "A greedy heuristic for the
set-covering problem", Mathematics of Operations Research 4, 233-235
(1979), :DOI:`10.1287/moor.4.3.233`
"""
if weight is None:
weight = g.new_vp("double", val=1)
if dset is None:
dset = g.new_vp("bool")
_check_prop_writable(dset, name="dset")
libgraph_tool_structure.dominating_set(g,
weight,
dset)
return dset
[docs]
def approx_minimum_vertex_cover(g, weight=None, cover=None):
r"""Return an approximate minimum (weighted) vertex cover.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weight : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Positive vertex weights. If not given, every vertex has unit weight.
cover : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, the vertices of the cover will be marked in this property
map.
Returns
-------
cover : :class:`~graph_tool.VertexPropertyMap`
Boolean vertex property map marking the vertices of the cover.
See Also
--------
bipartite_vertex_cover: Exact minimum vertex cover of a bipartite graph
maximal_independent_vertex_set: Complement of a vertex cover
minimum_edge_cover: Edge counterpart
approx_minimum_dominating_set: Approximate minimum dominating set
Notes
-----
A
`vertex cover <https://en.wikipedia.org/wiki/Vertex_cover>`_
contains at least one endpoint of every edge. Finding one
of minimum weight is NP-hard, and the local-ratio algorithm of Bar-Yehuda
and Even [bar-yehuda-linear-1981]_ is used, whose total weight is at most
twice the minimum: for every edge, the residual weights of both endpoints
are lowered by the smaller of them, and the vertices whose residual weight
reaches zero form the cover. The algorithm runs in time :math:`O(V + E)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> c = gt.approx_minimum_vertex_cover(g)
>>> print(c.fa.sum())
22
The cover can be highlighted in a drawing of the network:
>>> vcolor = g.new_vp("string", vals=np.where(c.a, "#f28c8e", "#cccccc"))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color="#999999",
... output="approx_minimum_vertex_cover-karate.pdf")
<...>
.. testcleanup::
conv_png("approx_minimum_vertex_cover-karate.pdf")
.. figure:: approx_minimum_vertex_cover-karate.png
:align: center
:width: 50%
Approximate minimum vertex cover of Zachary's karate club network,
with its vertices shown in red.
References
----------
.. [bar-yehuda-linear-1981] Reuven Bar-Yehuda and Shimon Even, "A
linear-time approximation algorithm for the weighted vertex cover
problem", Journal of Algorithms 2, 198-203 (1981),
:DOI:`10.1016/0196-6774(81)90020-1`
"""
if weight is None:
weight = g.new_vp("double", val=1)
if cover is None:
cover = g.new_vp("bool")
_check_prop_writable(cover, name="cover")
libgraph_tool_structure.vertex_cover(g,
weight,
cover)
return cover
[docs]
def approx_maximum_cut(g, weight=None, part=None):
r"""Return an approximate maximum cut.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used (the edge directions are ignored).
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Nonnegative edge weights. If not given, every edge has unit weight.
part : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, the side of every vertex will be stored in this property
map.
Returns
-------
cut : ``float``
The total weight of the edges between the two sides.
part : :class:`~graph_tool.VertexPropertyMap`
Boolean vertex property map with the side of every vertex.
See Also
--------
cut_size: Size of a given cut
graph_tool.flow.minimum_cut: Minimum cut
graph_tool.spectral.spectral_clustering: Partition based on the spectrum
Notes
-----
A cut is a partition of the vertices into two sides :math:`S` and
:math:`\bar S = V\setminus S`, and its weight is
.. math::
c(S) = \sum_{\{u,v\}\in E,\, u\in S,\, v\in\bar S} w_{uv},
the total weight of the edges with an endpoint on each side, ignoring
the edge directions (self-loops are never cut). A
`maximum cut <https://en.wikipedia.org/wiki/Maximum_cut>`_
maximizes
:math:`c(S)`. Finding it is NP-hard, and a local search is used instead:
starting from a random partition, vertices are moved to the other side
as long as this increases the weight of the cut. The result is a local
optimum, in which the cut edges incident on every vertex weigh at least
as much as the uncut ones (other than self-loops); summing over the
vertices, its weight is at least half of the total weight of the edges
that are not self-loops, and hence at least half of the maximum. Moving a
vertex :math:`v` takes time :math:`O(k_v)`, where :math:`k_v` is its
degree, and every move increases the weight of the cut, so that with
unit weights there are at most :math:`E` moves.
Examples
--------
.. testcode::
:hide:
gt.seed_rng(42)
>>> g = gt.collection.data["karate"]
>>> cut, part = gt.approx_maximum_cut(g)
>>> print(cut, g.num_edges())
55.0 78
The two sides and the edges of the cut can be shown in a drawing of the
network:
>>> vcolor = g.new_vp("string", vals=np.where(part.a, "#f28c8e",
... "#9bbedc"))
>>> s = gt.edge_endpoint_property(g, part, "source")
>>> t = gt.edge_endpoint_property(g, part, "target")
>>> ecolor = g.new_ep("string", vals=np.where(s.a != t.a, "#e41a1c",
... "#999999"))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color=ecolor, output="approx_maximum_cut-karate.pdf")
<...>
.. testcleanup::
conv_png("approx_maximum_cut-karate.pdf")
.. figure:: approx_maximum_cut-karate.png
:align: center
:width: 50%
Approximate maximum cut of Zachary's karate club network. The two
sides are shown in red and blue, and the edges of the cut in red.
"""
if weight is None:
weight = g.new_ep("double", val=1)
if part is None:
part = g.new_vp("bool")
_check_prop_writable(part, name="part")
cut = libgraph_tool_structure.max_cut(g,
weight,
part, _get_rng())
return cut, part
[docs]
def treewidth(g, method="min_fill", order=False):
r"""Return an upper bound on the treewidth of an undirected graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Undirected graph to be used.
method : ``str`` (optional, default: ``"min_fill"``)
Elimination heuristic: ``"min_fill"`` (minimum fill-in) or
``"min_degree"`` (minimum degree).
order : ``bool`` (optional, default: ``False``)
If ``True``, the elimination order is also returned.
Returns
-------
width : ``int``
An upper bound on the treewidth.
order : :class:`numpy.ndarray`
The elimination order of the vertices, which defines a tree
decomposition of the given width. Only returned if ``order == True``.
See Also
--------
junction_tree: Tree decomposition of a graph
chordal_completion: Minimal chordal completion
vertex_ordering: Orderings that reduce the bandwidth
Notes
-----
A
`tree decomposition <https://en.wikipedia.org/wiki/Tree_decomposition>`_
of a graph is a tree whose nodes are sets of
vertices (bags), such that every vertex belongs to some bag, both
endpoints of every edge belong to some bag, and the bags that contain any
given vertex form a connected subtree. Its width is the size of its
largest bag minus one, and the
`treewidth <https://en.wikipedia.org/wiki/Treewidth>`_
of the graph is the smallest
width of its tree decompositions.
Computing the treewidth is NP-hard. The heuristics eliminate the vertices
one at a time, connecting all the remaining neighbors of the eliminated
vertex to each other, and choose the vertex of smallest remaining degree,
or the one whose elimination adds the fewest edges
[bodlaender-treewidth-2010]_. The largest number of remaining
neighbors at elimination is the width of the corresponding tree
decomposition, and hence an upper bound on the treewidth. The minimum
fill-in heuristic usually gives smaller bounds, but is slower.
Examples
--------
>>> g = gt.lattice([5, 5])
>>> print(gt.treewidth(g), gt.treewidth(g, "min_degree"))
5 5
References
----------
.. [bodlaender-treewidth-2010] Hans L. Bodlaender and Arie M. C. A.
Koster, "Treewidth computations I. Upper bounds", Information and
Computation 208, 259-275 (2010), :DOI:`10.1016/j.ic.2009.03.008`
"""
if g.is_directed():
raise ValueError("The graph must be undirected.")
if method not in ["min_fill", "min_degree"]:
raise ValueError(f"invalid method: {method}")
w, o = libgraph_tool_structure.treewidth(g,
method == "min_fill")
if order:
return w, o
return w
[docs]
@_parallel
def simrank(g, c=0.8, max_iter=100, epsilon=1e-6, vertex_pairs=None,
sim_map=None):
r"""Return the SimRank similarity between pairs of vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
c : ``float`` (optional, default: ``0.8``)
Decay factor, in the interval :math:`(0, 1)`.
max_iter : ``int`` (optional, default: ``100``)
Maximum number of iterations.
epsilon : ``float`` (optional, default: ``1e-6``)
The iterations stop when no similarity changes by more than this
value.
vertex_pairs : iterable of pairs of integers (optional, default: ``None``)
Pairs of vertices to compute the similarity. If omitted, all pairs
will be considered.
sim_map : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If provided, and ``vertex_pairs is None``, the vertex similarities
will be stored in this vector-valued property. Otherwise, a new one
will be created.
Returns
-------
similarities : :class:`numpy.ndarray` or :class:`~graph_tool.VertexPropertyMap`
If ``vertex_pairs`` was supplied, this will be a
:class:`numpy.ndarray` with the corresponding similarities, otherwise
it will be a vector-valued vertex :class:`~graph_tool.VertexPropertyMap`,
with the similarities to all other vertices.
See Also
--------
vertex_similarity: Local similarity indices of pairs of vertices
panther_similarity: Approximate most similar vertices
Notes
-----
`SimRank <https://en.wikipedia.org/wiki/SimRank>`_
[jeh-simrank-2002]_ considers two vertices similar if their
in-neighbors (all neighbors, for undirected graphs) are similar, and is
defined for :math:`u \ne v` by
.. math::
s(u, v) = \frac{c}{k_u k_v}\sum_{a\in\Gamma(u)}\sum_{b\in\Gamma(v)}
s(a, b),
where :math:`\Gamma(u)` is the multiset of in-neighbors of :math:`u`
(with one entry per edge), :math:`k_u = |\Gamma(u)|` its in-degree, and
:math:`c` the decay factor, with :math:`s(u, u) = 1`, and :math:`s(u, v)
= 0` if :math:`u` or :math:`v` have no in-neighbors. It is computed by
iterating the equation from :math:`s(u, v) = \delta_{uv}`, until
``max_iter`` iterations are made or the largest change of a value is
smaller than ``epsilon``, in time :math:`O(VE)` per iteration
and memory :math:`O(V^2)`, even if only some pairs are requested, so that
it is feasible only for moderately sized graphs.
@parallel@
Examples
--------
>>> g = gt.collection.data["karate"]
>>> s = gt.simrank(g, vertex_pairs=[(0, 33), (5, 6)])
>>> print(s)
[0.1177797... 0.2540040...]
References
----------
.. [jeh-simrank-2002] Glen Jeh and Jennifer Widom, "SimRank: a measure of
structural-context similarity", Proceedings of the 8th ACM SIGKDD
International Conference on Knowledge Discovery and Data Mining,
538-543 (2002), :DOI:`10.1145/775047.775126`
"""
if vertex_pairs is not None:
vertex_pairs = numpy.asarray(vertex_pairs, dtype="int64").reshape(-1, 2)
return libgraph_tool_structure.simrank(g, float(c),
int(max_iter), float(epsilon),
vertex_pairs, None)
if sim_map is None:
sim_map = g.new_vp("vector<double>")
elif sim_map.value_type() != "vector<double>":
raise ValueError("sim_map must be of type vector<double>")
libgraph_tool_structure.simrank(g, float(c), int(max_iter),
float(epsilon), None, sim_map._get_any())
return sim_map
[docs]
def find_cycle(g, source=None, edges=False):
r"""Return a cycle of the graph, if there is one.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex` or ``int`` (optional, default: ``None``)
If given, only the cycles reachable from this vertex are considered.
edges : ``bool`` (optional, default: ``False``)
If ``True``, the edge indices of the cycle are returned instead of its
vertices.
Returns
-------
cycle : :class:`numpy.ndarray` or ``None``
The vertices of the cycle in order (the edge from the last to the
first vertex closes it), or its edge indices, or ``None`` if there is
no cycle.
See Also
--------
is_DAG: Test for directed acyclic graphs
girth: Length of the shortest cycle
cycle_basis: Basis of the cycle space
find_negative_cycle: Cycle of negative total weight
Notes
-----
A depth-first search is made, which stops at the first edge that closes a
`cycle <https://en.wikipedia.org/wiki/Cycle_(graph_theory)>`_:
for directed graphs, an edge to a vertex on the current search
path, and for undirected graphs, any edge to a visited vertex other than
the one through which the current vertex was reached. Self-loops are
cycles of length one, and parallel edges of undirected graphs cycles of
length two. The algorithm runs in time :math:`O(V + E)`. The shortest
cycle is given by :func:`~graph_tool.structure.girth`, and all of them by
:func:`~graph_tool.structure.all_circuits`.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (2, 3), (3, 1)])
>>> print(gt.find_cycle(g))
[1 2 3]
"""
s = -1 if source is None else int(source)
ret = libgraph_tool_structure.find_cycle(g, s)
if ret is None:
return None
return ret[1] if edges else ret[0]
[docs]
def chordless_cycles(g, max_length=0):
r"""Return an iterator over the chordless cycles of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
max_length : ``int`` (optional, default: ``0``)
If positive, only cycles with at most this number of vertices are
returned.
Returns
-------
cycle_iterator : iterator over :class:`numpy.ndarray`
The vertices of every chordless cycle, in order.
See Also
--------
all_circuits: All cycles of a directed graph
cycle_basis: Basis of the cycle space
is_chordal: Test for chordal graphs
Notes
-----
A
`chordless (or induced) cycle <https://en.wikipedia.org/wiki/Induced_path>`_
has no edge between two of its vertices
other than the edges of the cycle itself. Every cycle is found from its
vertex of smallest index :math:`s`, by extending paths over vertices
with larger indices, where a new vertex must not be adjacent to any
vertex of the path except the last one and :math:`s`; a vertex adjacent
to :math:`s` closes the cycle. For undirected graphs, every cycle is
returned once. For directed graphs, the cycles follow the edge
directions, and the adjacency for the chords ignores them, so that a
reciprocal pair of edges is a cycle of length two, and a chord of any
longer cycle. Self-loops and parallel edges are ignored. The
number of chordless cycles can grow exponentially with the size of the
graph, and the search may explore paths that do not close.
Examples
--------
>>> g = gt.lattice([3, 3])
>>> for c in gt.chordless_cycles(g):
... print(c)
[0 1 2 5 8 7 6 3]
[0 1 4 3]
[1 2 5 4]
[3 4 7 6]
[4 5 8 7]
"""
return libgraph_tool_structure.chordless_cycles(g,
max_length)
def _ecc_extreme(g, weights, largest):
ecc = eccentricity(g, weights=weights)
x = ecc.fa
if len(x) == 0:
return numpy.zeros(0, dtype="int64")
target = x.max() if largest else x.min()
return g.get_vertices()[numpy.isclose(x, target, rtol=1e-12, atol=0)]
[docs]
def center(g, weights=None):
r"""Return the center of the graph, i.e. the vertices of minimum
eccentricity.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights (lengths).
Returns
-------
center : :class:`numpy.ndarray`
The vertices whose eccentricity equals the radius.
See Also
--------
periphery: Vertices of maximum eccentricity
barycenter: Vertices of minimum total distance
eccentricity: Eccentricity of every vertex
radius: Minimum eccentricity
Notes
-----
The center is the set
.. math::
\{v : \epsilon(v) = \min_u \epsilon(u)\}, \qquad
\epsilon(v) = \max_{u} d(v, u),
where :math:`\epsilon(v)` is the
`eccentricity <https://en.wikipedia.org/wiki/Distance_(graph_theory)>`_
of :math:`v`, and
:math:`d(v, u)` the length of a shortest path from :math:`v` to
:math:`u` (directed, for directed graphs), with the maximum taken only
over the vertices reachable from :math:`v`. The eccentricities are
computed with :func:`~graph_tool.structure.eccentricity`, so that for
disconnected graphs the center is taken over all components (with
isolated vertices having eccentricity zero). Eccentricities that differ
by a relative amount of at most :math:`10^{-12}` are considered equal.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.center(g))
[ 0 1 2 3 8 13 19 31]
The center can be highlighted in a drawing of the network:
>>> vcolor = g.new_vp("string", val="#cccccc")
>>> for v in gt.center(g):
... vcolor[v] = "#f28c8e"
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color="#999999", output="center-karate.pdf")
<...>
.. testcleanup::
conv_png("center-karate.pdf")
.. figure:: center-karate.png
:align: center
:width: 50%
Center of Zachary's karate club network, with its vertices shown in
red.
"""
return _ecc_extreme(g, weights, False)
[docs]
def periphery(g, weights=None):
r"""Return the periphery of the graph, i.e. the vertices of maximum
eccentricity.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights (lengths).
Returns
-------
periphery : :class:`numpy.ndarray`
The vertices whose eccentricity equals the diameter.
See Also
--------
center: Vertices of minimum eccentricity
eccentricity: Eccentricity of every vertex
diameter: Maximum eccentricity
Notes
-----
The periphery is the set
.. math::
\{v : \epsilon(v) = \max_u \epsilon(u)\}, \qquad
\epsilon(v) = \max_{u} d(v, u),
where :math:`\epsilon(v)` is the
`eccentricity <https://en.wikipedia.org/wiki/Distance_(graph_theory)>`_
of :math:`v`, and
:math:`d(v, u)` the length of a shortest path from :math:`v` to
:math:`u` (directed, for directed graphs), with the maximum taken only
over the vertices reachable from :math:`v`. The eccentricities are
computed with :func:`~graph_tool.structure.eccentricity`, and those that
differ by a relative amount of at most :math:`10^{-12}` are considered
equal.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.periphery(g))
[14 15 16 18 20 22 23 26 29]
The periphery can be highlighted in a drawing of the network:
>>> vcolor = g.new_vp("string", val="#cccccc")
>>> for v in gt.periphery(g):
... vcolor[v] = "#f28c8e"
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color="#999999", output="periphery-karate.pdf")
<...>
.. testcleanup::
conv_png("periphery-karate.pdf")
.. figure:: periphery-karate.png
:align: center
:width: 50%
Periphery of Zachary's karate club network, with its vertices shown
in red.
"""
return _ecc_extreme(g, weights, True)
[docs]
def barycenter(g, weights=None):
r"""Return the barycenter of the graph, i.e. the vertices with the
smallest sum of distances to all others.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used, which must be connected (strongly connected, if
directed).
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights (lengths).
Returns
-------
barycenter : :class:`numpy.ndarray`
The vertices that minimize :math:`\sum_u d(v, u)`.
See Also
--------
center: Vertices of minimum eccentricity
wiener_index: Sum of the distances between all pairs
graph_tool.centrality.closeness: Closeness centrality
Notes
-----
The sums of distances are obtained from
:func:`~graph_tool.centrality.closeness`, with a search from every
vertex in parallel, in time :math:`O(VE)` without weights.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.barycenter(g))
[0]
"""
from .. centrality import closeness
comp, hist = label_components(g)
if len(hist) > 1:
raise ValueError("The graph must be (strongly) connected.")
c = closeness(g, weight=weights, norm=False).fa
if len(c) == 0:
return numpy.zeros(0, dtype="int64")
total = 1 / c
return g.get_vertices()[numpy.isclose(total, total.min(), rtol=1e-12,
atol=0)]
[docs]
def widest_distance(g, source, weights, pred_map=False):
r"""Return the width of the widest paths from a source vertex to all
others.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex` or ``int``
Source vertex.
weights : :class:`~graph_tool.EdgePropertyMap`
Edge weights (capacities).
pred_map : ``bool`` (optional, default: ``False``)
If ``True``, a predecessor map of a tree of widest paths is also
returned.
Returns
-------
width : :class:`~graph_tool.VertexPropertyMap`
The largest bottleneck (smallest edge weight along the path) of a path
from the source to every vertex, which is :math:`+\infty` for the
source and :math:`-\infty` for unreachable vertices.
pred : :class:`~graph_tool.VertexPropertyMap`
Predecessor of every vertex in a tree of widest paths (the vertex
itself for the source and unreachable vertices). Only returned if
``pred_map == True``.
See Also
--------
widest_path: A single widest path
shortest_distance: Shortest distances
Notes
-----
The width (or bottleneck) of a path :math:`P` is the smallest weight
of its edges, and the value returned for vertex :math:`v` is
.. math::
b(v) = \max_{P:\,s\to v}\;\min_{e\in P} w_e,
where the maximum runs over the paths from the source :math:`s` to
:math:`v` (directed paths, for directed graphs), with :math:`b(s) =
+\infty` and :math:`b(v) = -\infty` if :math:`v` cannot be reached.
The
`widest (or maximum bottleneck, or maximum capacity) paths <https://en.wikipedia.org/wiki/Widest_path_problem>`_
are found
with the variant of Dijkstra's algorithm that maximizes the smallest
edge weight instead of minimizing the sum [pollack-maximum-1960]_, in
time :math:`O((V + E)\log V)`.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (0, 2)], directed=False)
>>> w = g.new_ep("double", vals=[5, 4, 2])
>>> print(gt.widest_distance(g, 0, w).a)
[inf 5. 4.]
References
----------
.. [pollack-maximum-1960] Maurice Pollack, "The maximum capacity through
a network", Operations Research 8, 733-736 (1960),
:DOI:`10.1287/opre.8.5.733`
"""
width = g.new_vp("double")
pred = g.new_vp("int64_t")
libgraph_tool_structure.widest_paths(g, int(source),
weights, width, pred)
if pred_map:
return width, pred
return width
[docs]
def widest_path(g, source, target, weights):
r"""Return a widest path from a source to a target vertex.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex` or ``int``
Source vertex.
target : :class:`~graph_tool.Vertex` or ``int``
Target vertex.
weights : :class:`~graph_tool.EdgePropertyMap`
Edge weights (capacities).
Returns
-------
vertex_list : ``list`` of :class:`~graph_tool.Vertex`
The vertices of the path, empty if the target cannot be reached.
edge_list : ``list`` of :class:`~graph_tool.Edge`
The edges of the path (for parallel edges, one of largest weight).
width : ``float``
The smallest edge weight along the path.
See Also
--------
widest_distance: Widths of the widest paths to all vertices
shortest_path: Shortest path
Notes
-----
A
`widest path <https://en.wikipedia.org/wiki/Widest_path_problem>`_
from :math:`s` to :math:`t` is a path :math:`P` (a
directed one, for directed graphs) that maximizes its width
:math:`\min_{e\in P} w_e`, the smallest weight of its edges. The path is
obtained from the tree of :func:`~graph_tool.structure.widest_distance`,
in time
:math:`O((V + E)\log V)`.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (0, 2)], directed=False)
>>> w = g.new_ep("double", vals=[5, 4, 2])
>>> vs, es, width = gt.widest_path(g, 0, 2, w)
>>> print([int(v) for v in vs], width)
[0, 1, 2] 4.0
"""
width, pred = widest_distance(g, source, weights, pred_map=True)
s, t = g.vertex(int(source)), g.vertex(int(target))
if not numpy.isfinite(width[t]) and t != s:
return [], [], -numpy.inf
vs, es = libgraph_tool_structure.widest_path(g, int(s),
int(t), weights._get_any(),
pred._get_any())
return list(vs), list(es), float(width[t])
[docs]
def voronoi_cells(g, seeds, weights=None, tiebreak=None, radius=None):
r"""Assign every vertex to its closest seed vertex.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
seeds : iterable of :class:`~graph_tool.Vertex` or ``int``
The seed vertices.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights (lengths). If not given, every edge has unit length.
tiebreak : ``str`` (optional, default: ``None``)
Assignment of the vertices equidistant to several seeds: to the
first of them in ``seeds`` (``"first"``), to the last one
(``"last"``), or to one chosen uniformly at random (``"random"``). If
not given, the order of the search decides (see below).
radius : ``float`` (optional, default: ``None``)
If given, the vertices farther than this from every seed are not
assigned.
Returns
-------
cell : :class:`~graph_tool.VertexPropertyMap`
The closest seed of every vertex (``-1`` if no seed reaches it).
dist : :class:`~graph_tool.VertexPropertyMap`
The distance to the closest seed.
See Also
--------
shortest_distance: Distances from a set of sources
steiner_tree: Approximate minimum tree connecting a subset of vertices
Notes
-----
The graph Voronoi cells [erwig-graph-2000]_ are obtained with a single
breadth-first search, or Dijkstra search with weights, started from all the
seeds at once, in time :math:`O(V + E)` or :math:`O((V + E)\log V)`. For
directed graphs, the distances are from the seeds. If ``tiebreak is None``,
ties between equidistant seeds are broken by the order of the search.
Otherwise, a second search is done from every seed, visiting only the
vertices to which it is a closest seed (which suffices, since the vertices
on a shortest path from a closest seed have it as a closest seed too), so
that the closest seeds of every vertex are counted, and the random choice
is made by reservoir sampling. This multiplies the time by the largest
number of seeds equidistant to a vertex. With weights, distances that
differ by a relative amount of at most :math:`10^{-10}` are considered
equal.
Examples
--------
>>> g = gt.lattice([5, 1])
>>> cell, dist = gt.voronoi_cells(g, [0, 4])
>>> print(cell.a, dist.a)
[0 0 0 4 4] [0. 1. 2. 1. 0.]
>>> cell, dist = gt.voronoi_cells(g, [4, 0], tiebreak="first", radius=1)
>>> print(cell.a, dist.a)
[ 0 0 -1 4 4] [ 0. 1. inf 1. 0.]
In a larger example, the cells of four seeds partition the Delaunay
triangulation of random points in the plane:
.. testcode::
:hide:
np.random.seed(42)
>>> points = np.random.random((200, 2)) * 4
>>> g, pos = gt.triangulation(points, type="delaunay")
>>> seeds = [0, 1, 2, 3]
>>> cell, dist = gt.voronoi_cells(g, seeds)
>>> palette = {0: "#f28c8e", 1: "#9bbedc", 2: "#a6d7a4", 3: "#cba6d1"}
>>> vcolor = g.new_vp("string", vals=[palette[c] for c in cell.a])
>>> vsize = g.new_vp("double", val=10)
>>> for s in seeds:
... vsize[s] = 20
>>> gt.graph_draw(g, pos, vertex_fill_color=vcolor, vertex_size=vsize,
... edge_color="#cccccc", output="voronoi_cells-triang.pdf")
<...>
.. testcleanup::
conv_png("voronoi_cells-triang.pdf")
.. figure:: voronoi_cells-triang.png
:align: center
:width: 60%
Voronoi cells of four seed vertices in the Delaunay triangulation of
200 random points. The colors of the vertices indicate their cells,
and the seeds are shown larger.
References
----------
.. [erwig-graph-2000] Martin Erwig, "The graph Voronoi diagram with
applications", Networks 36, 156-163 (2000),
:DOI:`10.1002/1097-0037(200010)36:3<156::AID-NET2>3.0.CO;2-L`
"""
seeds = numpy.asarray([int(v) for v in seeds], dtype="int64")
cell = g.new_vp("int64_t")
dist = g.new_vp("double")
ties = {None: -1, "first": 0, "last": 1, "random": 2}
if tiebreak not in ties:
raise ValueError("invalid tiebreak: " + str(tiebreak))
libgraph_tool_structure.voronoi_cells(g, seeds, weights,
cell, dist,
numpy.inf if radius is None
else float(radius),
ties[tiebreak], _get_rng())
return cell, dist
def _distance_sums(g, weights):
return libgraph_tool_structure.distance_sums(g, weights)
[docs]
@_parallel
def average_shortest_path_length(g, weights=None):
r"""Return the average shortest path length between the pairs of
vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights (lengths).
Returns
-------
ell : ``float``
The average of :math:`d(u, v)` over the ordered pairs of distinct
vertices such that :math:`v` can be reached from :math:`u`.
See Also
--------
wiener_index: Sum of the distances between all pairs
global_efficiency: Average inverse distance
graph_tool.stats.distance_histogram: Distribution of the distances
Notes
-----
This is the
`average path length <https://en.wikipedia.org/wiki/Average_path_length>`_
of the graph. Unreachable pairs are excluded from the average, so that
the graph need not be connected. The distances are computed with a
search from every vertex, in parallel, in time :math:`O(VE)` without
weights.
@parallel@
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.average_shortest_path_length(g))
2.4081996...
"""
sd, sinv, n = _distance_sums(g, weights)
return sd / n if n > 0 else 0.
[docs]
@_parallel
def wiener_index(g, weights=None):
r"""Return the Wiener index of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights (lengths).
Returns
-------
W : ``float``
The sum of the distances between all pairs of vertices
[wiener-structural-1947]_ (unordered pairs for undirected graphs,
ordered ones for directed graphs), or :math:`\infty` if some pair is
not connected.
See Also
--------
hyper_wiener_index: Wiener index that also includes squared distances
schultz_index: Degree-weighted variant
gutman_index: Degree-product-weighted variant
average_shortest_path_length: Average distance between pairs of vertices
Notes
-----
The
`Wiener index <https://en.wikipedia.org/wiki/Wiener_index>`_
[wiener-structural-1947]_ of an undirected graph is
.. math::
W = \sum_{u<v} d(u, v),
where the sum runs over the unordered pairs of distinct vertices, and
:math:`d(u, v)` is the length of a shortest path between :math:`u` and
:math:`v` (the number of its edges, or the sum of their weights). For
directed graphs, the sum runs over the ordered pairs :math:`u \ne v`,
and :math:`d(u, v)` is the length of a shortest directed path from
:math:`u` to :math:`v`. If some vertex cannot be reached from another,
:math:`W = \infty`. The algorithm runs in time :math:`O(VE)` without
weights, in parallel.
@parallel@
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.wiener_index(g))
1351.0
References
----------
.. [wiener-structural-1947] Harry Wiener, "Structural determination of
paraffin boiling points", Journal of the American Chemical Society 69,
17-20 (1947), :DOI:`10.1021/ja01193a005`
"""
sd, sinv, n = _distance_sums(g, weights)
N = g.num_vertices()
if n < N * (N - 1):
return numpy.inf
return sd if g.is_directed() else sd / 2
[docs]
@_parallel
def harmonic_diameter(g, weights=None):
r"""Return the harmonic diameter of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights (lengths).
Returns
-------
D : ``float``
The harmonic mean of the distances over all ordered pairs of distinct
vertices, :math:`V(V-1)/\sum_{u\ne v}1/d(u,v)`, with :math:`1/d = 0`
for unreachable pairs [marchiori-harmony-2000]_.
See Also
--------
diameter: Maximum distance
global_efficiency: Average inverse distance
average_shortest_path_length: Average distance between pairs of vertices
Notes
-----
It is the inverse of the :func:`~graph_tool.structure.global_efficiency`.
The algorithm runs in time :math:`O(VE)` without weights, in parallel.
@parallel@
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.harmonic_diameter(g))
2.0324859...
References
----------
.. [marchiori-harmony-2000] Massimo Marchiori and Vito Latora, "Harmony
in the small-world", Physica A 285, 539-546 (2000),
:DOI:`10.1016/S0378-4371(00)00311-3`, :arxiv:`cond-mat/0008357`
"""
sd, sinv, n = _distance_sums(g, weights)
N = g.num_vertices()
return N * (N - 1) / sinv if sinv > 0 else numpy.inf
[docs]
def ego_graph(g, center, radius=1, weights=None, undirected=False):
r"""Return the subgraph induced by the vertices within a given distance
of a vertex.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
center : :class:`~graph_tool.Vertex` or ``int``
The central vertex.
radius : ``float`` (optional, default: ``1``)
The largest distance from the center.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights (lengths).
undirected : ``bool`` (optional, default: ``False``)
If ``True``, the distances in directed graphs ignore the edge
directions; otherwise they are measured from the center.
Returns
-------
u : :class:`~graph_tool.GraphView`
The ego network of the center.
See Also
--------
label_out_component: Vertices reachable from a given vertex
shortest_distance: Distances from a source vertex
graph_tool.search.bfs_iterator: Breadth-first traversal from a vertex
Notes
-----
The ego graph of the center :math:`c` with radius :math:`r` is the
subgraph induced by the vertices :math:`\{u : d(c, u) \le r\}`, where
:math:`d(c, u)` is the length of a shortest path from :math:`c` to
:math:`u` (the number of its edges, or the sum of their weights),
following the edge directions for directed graphs unless
``undirected == True``. The distances are computed with
:func:`~graph_tool.structure.shortest_distance`, with the search stopped
at ``radius``, so that the time depends only on the size of the
neighborhood.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> u = gt.ego_graph(g, 0)
>>> print(u.num_vertices(), u.num_edges())
17 34
The ego graph can be highlighted in a drawing of the network:
>>> inego = g.new_vp("bool")
>>> inego.a[u.get_vertices()] = True
>>> vcolor = g.new_vp("string", vals=np.where(inego.a, "#9bbedc",
... "#cccccc"))
>>> vcolor[0] = "#f28c8e"
>>> s = gt.edge_endpoint_property(g, inego, "source")
>>> t = gt.edge_endpoint_property(g, inego, "target")
>>> ecolor = g.new_ep("string", vals=np.where(s.a & t.a, "#377eb8",
... "#999999"))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color=ecolor, output="ego_graph-karate.pdf")
<...>
.. testcleanup::
conv_png("ego_graph-karate.pdf")
.. figure:: ego_graph-karate.png
:align: center
:width: 50%
Ego graph of radius one of vertex 0 (in red) of Zachary's karate club
network. The other vertices and the edges of the ego graph are shown
in blue.
"""
h = GraphView(g, directed=False) if undirected and g.is_directed() else g
d = shortest_distance(h, source=center, weights=weights, max_dist=radius)
mask = g.new_vp("bool")
mask.fa = d.fa <= radius
return GraphView(g, vfilt=mask)
[docs]
def clique_number(g):
r"""Return the clique number, i.e. the number of vertices of a largest
clique.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used (the edge directions are ignored).
Returns
-------
omega : ``int``
The clique number.
See Also
--------
largest_cliques: Cliques of maximum size
maximal_cliques: All maximal cliques
large_clique_size: Fast lower bound on the clique number
independence_number: Size of a largest independent vertex set
Notes
-----
A
`clique <https://en.wikipedia.org/wiki/Clique_(graph_theory)>`_
is a set of vertices every two of which are adjacent, ignoring
the edge directions, and the clique number is
.. math::
\omega(G) = \max\{|C| : C \text{ is a clique of } G\}.
The maximal cliques are enumerated with the Bron--Kerbosch algorithm
with pivoting [tomita-worst-case-2006]_, split into one independent
subproblem per vertex along a degeneracy order
[eppstein-listing-2010]_, which are solved in parallel. The branches that
cannot contain a clique larger than the largest one found so far are
pruned. The time is exponential in the worst case.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.clique_number(g))
5
References
----------
.. [tomita-worst-case-2006] Etsuji Tomita, Akira Tanaka, and Haruhisa
Takahashi, "The worst-case time complexity for generating all maximal
cliques and computational experiments", Theoretical Computer Science
363, 28-42 (2006), :doi:`10.1016/j.tcs.2006.06.015`
.. [eppstein-listing-2010] David Eppstein, Maarten Löffler, and Darren
Strash, "Listing all maximal cliques in sparse graphs in near-optimal
time", ISAAC 2010, :DOI:`10.1007/978-3-642-17517-6_36`,
:arxiv:`1006.5440`
"""
return libgraph_tool_structure.clique_number(
GraphView(g, directed=False))
[docs]
def kcore_subgraph(g, k=None, kind="core", core=None):
r"""Return the :math:`k`-core, :math:`k`-shell, :math:`k`-crust, or
:math:`k`-corona of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
k : ``int`` (optional, default: ``None``)
The value of :math:`k`. If not given, the largest core number is used.
kind : ``str`` (optional, default: ``"core"``)
``"core"`` (vertices with core number at least :math:`k`),
``"shell"`` (exactly :math:`k`), ``"crust"`` (at most :math:`k`), or
``"corona"`` (vertices of the :math:`k`-core with exactly :math:`k`
neighbors in it).
core : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Core numbers, as given by
:func:`~graph_tool.structure.kcore_decomposition`. If not given, they
are computed.
Returns
-------
u : :class:`~graph_tool.GraphView`
The subgraph induced by the selected vertices.
See Also
--------
kcore_decomposition: Core number of every vertex
onion_decomposition: Refinement of the k-core decomposition into layers
Notes
-----
With :math:`c_v` the core number of vertex :math:`v`, the subgraph is
induced by the vertices with :math:`c_v \ge k` (core), :math:`c_v = k`
(shell) or :math:`c_v \le k` (crust), or by the vertices with :math:`c_v
\ge k` whose total degree in the :math:`k`-core is exactly :math:`k`
(corona). The core, shell, and crust are those defined in
[carmi-model-2007]_, where the :math:`k`-crust is the union of the
shells with indices smaller than or equal to :math:`k` (the remainder of
the graph after the :math:`(k+1)`-core is removed). The algorithm runs in
time :math:`O(V + E)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.kcore_subgraph(g).num_vertices(),
... gt.kcore_subgraph(g, 2, "shell").num_vertices())
10 11
The largest core can be highlighted in a drawing of the network:
>>> u = gt.kcore_subgraph(g)
>>> inc = g.new_vp("bool")
>>> inc.a[u.get_vertices()] = True
>>> vcolor = g.new_vp("string", vals=np.where(inc.a, "#f28c8e",
... "#cccccc"))
>>> s = gt.edge_endpoint_property(g, inc, "source")
>>> t = gt.edge_endpoint_property(g, inc, "target")
>>> ecolor = g.new_ep("string", vals=np.where(s.a & t.a, "#e41a1c",
... "#999999"))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color=ecolor, output="kcore_subgraph-karate.pdf")
<...>
.. testcleanup::
conv_png("kcore_subgraph-karate.pdf")
.. figure:: kcore_subgraph-karate.png
:align: center
:width: 50%
Largest core (the 4-core) of Zachary's karate club network, with its
vertices and edges shown in red.
References
----------
.. [carmi-model-2007] Shai Carmi, Shlomo Havlin, Scott Kirkpatrick, Yuval
Shavitt and Eran Shir, "A model of Internet topology using k-shell
decomposition", Proceedings of the National Academy of Sciences 104,
11150-11154 (2007), :DOI:`10.1073/pnas.0701175104`
"""
if core is None:
core = kcore_decomposition(g)
c = core.a.astype("int64")
if k is None:
k = int(core.fa.max())
mask = g.new_vp("bool")
if kind == "core":
mask.a = c >= k
elif kind == "shell":
mask.a = c == k
elif kind == "crust":
mask.a = c <= k
elif kind == "corona":
u = GraphView(g, vfilt=c >= k)
deg = u.degree_property_map("total")
mask.a = (c >= k) & (deg.a == k)
else:
raise ValueError(f"invalid kind: {kind}")
return GraphView(g, vfilt=mask)
[docs]
def maximum_common_subgraphs(g1, g2, vertex_label=None, edge_label=None,
connected=True, max_n=0):
r"""Return the maximum common induced subgraphs of two graphs.
Parameters
----------
g1 : :class:`~graph_tool.Graph`
First graph.
g2 : :class:`~graph_tool.Graph`
Second graph, with the same directedness.
vertex_label : pair of :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If given, only vertices with equal labels are matched.
edge_label : pair of :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
If given, only edges with equal labels are matched.
connected : ``bool`` (optional, default: ``True``)
If ``True``, only connected common subgraphs are considered.
max_n : ``int`` (optional, default: ``0``)
If positive, at most this number of subgraphs is returned.
Returns
-------
maps : ``list`` of :class:`~graph_tool.VertexPropertyMap`
For every maximum common subgraph, a map from the vertices of ``g1``
to their counterparts in ``g2`` (``-1`` for the vertices outside the
subgraph).
See Also
--------
subgraph_isomorphism: Embeddings of a graph as a subgraph of another
graph_edit_distance: Edit distance between two graphs
isomorphism: Isomorphism test between two graphs
Notes
-----
The
`common subgraphs <https://en.wikipedia.org/wiki/Maximum_common_induced_subgraph>`_
are induced subgraphs of both graphs that are
isomorphic under the given map (with equal labels, if given), and the
maximum ones are those with the largest number of vertices. They are
found with McGregor's backtracking
algorithm [mcgregor-backtrack-1982]_, which explores the whole search space
before returning the largest ones, so that the time is exponential in the
sizes of the graphs; it is feasible only for small graphs (a few tens of
vertices). Parallel edges and self-loops are ignored.
Examples
--------
>>> g1 = gt.Graph([(0, 1), (1, 2), (2, 0), (2, 3)], directed=False)
>>> g2 = gt.Graph([(0, 1), (1, 2), (2, 3), (3, 0)], directed=False)
>>> ms = gt.maximum_common_subgraphs(g1, g2)
>>> print(len(ms), (ms[0].a >= 0).sum())
16 3
References
----------
.. [mcgregor-backtrack-1982] James J. McGregor, "Backtrack search
algorithms and the maximal common subgraph problem", Software:
Practice and Experience 12, 23-34 (1982),
:DOI:`10.1002/spe.4380120103`
"""
if g1.is_directed() != g2.is_directed():
raise ValueError("The graphs must have the same directedness.")
codes = [None] * 4
if vertex_label is not None and None not in vertex_label:
codes[0] = _label_codes(g1, vertex_label[0], "v")
codes[1] = _label_codes(g2, vertex_label[1], "v")
if edge_label is not None and None not in edge_label:
codes[2] = _label_codes(g1, edge_label[0], "e")
codes[3] = _label_codes(g2, edge_label[1], "e")
maps = libgraph_tool_structure.max_common_subgraphs(g1,
g2,
*codes, connected,
max_n)
return [_vprop_from_array(g1, m) for m in maps]
[docs]
def graph_edit_distance(g1, g2, vertex_label=None, edge_label=None,
vertex_cost=1., edge_cost=1., vertex_subst_cost=1.,
edge_subst_cost=1., exact=False, upper_bound=None,
roots=None, timeout=None, return_map=False):
r"""Return the edit distance between two graphs.
Parameters
----------
g1 : :class:`~graph_tool.Graph`
First graph.
g2 : :class:`~graph_tool.Graph`
Second graph, with the same directedness.
vertex_label : pair of :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex labels of both graphs. If given, the substitution of a vertex
by another with a different label has cost ``vertex_subst_cost``.
edge_label : pair of :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge labels of both graphs. If given, the substitution of an edge by
another with a different label has cost ``edge_subst_cost``.
vertex_cost : ``float`` or pair of :class:`~graph_tool.VertexPropertyMap` (optional, default: ``1.``)
Cost of the insertion or deletion of a vertex, or the costs of the
deletion of every vertex of ``g1`` and of the insertion of every
vertex of ``g2``.
edge_cost : ``float`` or pair of :class:`~graph_tool.EdgePropertyMap` (optional, default: ``1.``)
Cost of the insertion or deletion of an edge, or the costs of the
deletion of every edge of ``g1`` and of the insertion of every edge
of ``g2``.
vertex_subst_cost : ``float`` (optional, default: ``1.``)
Cost of the substitution of a vertex by another with a different
label.
edge_subst_cost : ``float`` (optional, default: ``1.``)
Cost of the substitution of an edge by another with a different
label.
exact : ``bool`` (optional, default: ``False``)
If ``True``, the exact distance is computed, in time exponential in
the number of vertices. Otherwise, an approximation is returned,
which is an upper bound.
upper_bound : ``float`` (optional, default: ``None``)
If given, ``None`` is returned if the distance exceeds this value.
With ``exact == False``, this happens only if a lower bound of the
distance exceeds it.
roots : pair of :class:`~graph_tool.Vertex` (optional, default: ``None``)
If given, the first vertex, of ``g1``, is mapped to the second, of
``g2``, and the distance is the minimum over the edit paths with this
correspondence.
timeout : ``float`` (optional, default: ``None``)
If given, the exact search stops after this number of seconds, and
the best distance found so far, which is an upper bound, is returned,
with a :class:`RuntimeWarning`. Ignored if ``exact == False``.
return_map : ``bool`` (optional, default: ``False``)
If ``True``, the vertex map that yields the distance is also returned.
Returns
-------
d : ``float``
The edit distance (or its upper bound, if ``exact == False`` or the
search timed out), or ``None`` if it exceeds ``upper_bound``.
vmap : :class:`~graph_tool.VertexPropertyMap`
Map from the vertices of ``g1`` to their counterparts in ``g2``
(``-1`` for the deleted vertices). Only returned if
``return_map == True``.
See Also
--------
maximum_common_subgraphs: Maximum common induced subgraphs
isomorphism: Isomorphism test between two graphs
similarity: Adjacency similarity between two graphs
Notes
-----
The
`edit distance <https://en.wikipedia.org/wiki/Graph_edit_distance>`_
[sanfeliu-distance-1983]_ is the minimum total cost
of the vertex and edge insertions, deletions, and substitutions that
transform :math:`G_1` into a graph isomorphic to :math:`G_2`. Every edit
path corresponds to a map :math:`f` from the vertices of :math:`G_1` to
those of :math:`G_2` and to deletions, in which the vertices of
:math:`G_2` outside the image are inserted, and the edges between every
pair of vertices :math:`(u, v)` are transformed into those between
:math:`(f(u), f(v))` with the minimum number of operations (which
accounts for parallel edges and self-loops). The distance is symmetric,
and is a metric if the costs are positive. If the insertion and deletion
costs differ between the edges, the edges between a pair of vertices are
transformed by an optimal assignment, which is trivial in the absence of
parallel edges.
With ``exact == False``, the map is obtained from an optimal assignment
between the vertices of both graphs and the deletions and insertions, where
the cost of each assignment includes half the cost of matching the incident
edges [riesen-approximate-2009]_ [blumenthal-improved-2018]_. The
assignment is solved with the Hungarian algorithm [kuhn-hungarian-1955]_,
in time :math:`O((V_1+V_2)^3)` and memory :math:`O((V_1+V_2)^2)`. Since it
accounts for the edges only through the degrees (and labels), the map is
then improved by exchanging the images of pairs of vertices while the cost
decreases [riesen-improving-2015]_, in time
:math:`O((V_1+V_2)^2\left<k\right>)` per pass, and by iterated
linearization: the assignment problem is solved again with the cost of
every assignment computed with the other vertices at their current images,
while this lowers the exact cost (the integer step of the IPFP method
[bougleux-graph-2017]_, at most 20 times); the exact cost of the final map
is returned.
With ``exact == True``, the vertices of the smaller graph are assigned
one at a time by depth-first branch and bound, where the remaining cost
is bounded from below by the same assignment problem restricted to the
remaining vertices [blumenthal-improved-2018]_, and the assignments it
returns provide upper bounds. The time is exponential in the number of
vertices in the worst case, which makes the computation feasible only for
small graphs (a few tens of vertices). An ``upper_bound`` close to the
distance prunes the search further, so that deciding whether the distance
is at most a given value can be much faster than computing it. If the
edge costs differ, the bound uses the smallest edge cost of every vertex
for the edges to the remaining vertices, which makes it less tight.
Examples
--------
>>> g1 = gt.complete_graph(4)
>>> g2 = gt.circular_graph(5)
>>> d, m = gt.graph_edit_distance(g1, g2, exact=True, return_map=True)
>>> print(d, m.a)
6.0 [...]
The approximation can exceed the exact distance for unlabeled graphs
that differ only slightly, as for this network with three edges removed:
>>> g1 = gt.collection.data["karate"]
>>> g2 = gt.Graph(g1.get_edges()[3:], directed=False)
>>> print(gt.graph_edit_distance(g1, g2),
... gt.graph_edit_distance(g1, g2, exact=True))
9.0 3.0
With an upper bound, the computation decides whether the distance is at
most this value, and returns ``None`` otherwise:
>>> print(gt.graph_edit_distance(g1, g2, exact=True, upper_bound=2))
None
References
----------
.. [sanfeliu-distance-1983] Alberto Sanfeliu and King-Sun Fu, "A distance
measure between attributed relational graphs for pattern
recognition", IEEE Transactions on Systems, Man, and Cybernetics 13,
353-362 (1983), :DOI:`10.1109/TSMC.1983.6313167`
.. [riesen-approximate-2009] Kaspar Riesen and Horst Bunke, "Approximate
graph edit distance computation by means of bipartite graph
matching", Image and Vision Computing 27, 950-959 (2009),
:DOI:`10.1016/j.imavis.2008.04.004`
.. [blumenthal-improved-2018] David B. Blumenthal and Johann Gamper,
"Improved lower bounds for graph edit distance", IEEE Transactions on
Knowledge and Data Engineering 30, 503-516 (2018),
:DOI:`10.1109/TKDE.2017.2772243`
.. [kuhn-hungarian-1955] Harold W. Kuhn, "The Hungarian method for the
assignment problem", Naval Research Logistics Quarterly 2, 83-97
(1955), :DOI:`10.1002/nav.3800020109`
.. [riesen-improving-2015] Kaspar Riesen and Horst Bunke, "Improving
bipartite graph edit distance approximation using various search
strategies", Pattern Recognition 48, 1349-1363 (2015),
:DOI:`10.1016/j.patcog.2014.11.002`
.. [bougleux-graph-2017] Sébastien Bougleux, Luc Brun, Vincenzo
Carletti, Pasquale Foggia, Benoit Gaüzère and Mario Vento, "Graph edit
distance as a quadratic assignment problem", Pattern Recognition
Letters 87, 38-46 (2017), :DOI:`10.1016/j.patrec.2016.10.001`
"""
if g1.is_directed() != g2.is_directed():
raise ValueError("The graphs must have the same directedness.")
codes = [None] * 4
if vertex_label is not None and None not in vertex_label:
codes[0] = _label_codes(g1, vertex_label[0], "v")
codes[1] = _label_codes(g2, vertex_label[1], "v")
if edge_label is not None and None not in edge_label:
codes[2] = _label_codes(g1, edge_label[0], "e")
codes[3] = _label_codes(g2, edge_label[1], "e")
# per-element costs, as arrays indexed by the vertex and edge indices
def element_costs(c, name):
if not isinstance(c, (tuple, list)):
return float(c), [None, None]
out = []
for p in c:
_check_prop_scalar(p, name)
if numpy.any(p.fa < 0):
raise ValueError("The costs must be nonnegative.")
out.append(numpy.array(p.a, dtype="float"))
return 1., out
cmaps = [None] * 4
cv, cmaps[:2] = element_costs(vertex_cost, "vertex_cost")
ce, cmaps[2:] = element_costs(edge_cost, "edge_cost")
costs = [cv, ce, float(vertex_subst_cost), float(edge_subst_cost)]
if min(costs) < 0:
raise ValueError("The costs must be nonnegative.")
r1 = r2 = -1
if roots is not None:
r1, r2 = int(g1.vertex(roots[0])), int(g2.vertex(roots[1]))
ub = numpy.inf if upper_bound is None else float(upper_bound)
tmax = 0. if timeout is None else float(timeout)
if tmax < 0:
raise ValueError("The time limit must be nonnegative.")
d, lb, f, timed_out = \
libgraph_tool_structure.graph_edit_distance(g1,
g2,
*codes, *cmaps, *costs,
exact, r1, r2, ub, tmax)
if timed_out:
warnings.warn("The time limit was reached; the distance is an " +
"upper bound.", RuntimeWarning)
if d == numpy.inf:
d = None
if not return_map:
return d
return d, _vprop_from_array(g1, f)
[docs]
def resource_constrained_path(g, source, target, cost, resources, limits,
pareto=False):
r"""Return a shortest path subject to constraints on the resources it
consumes.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex` or ``int``
Source vertex.
target : :class:`~graph_tool.Vertex` or ``int``
Target vertex.
cost : :class:`~graph_tool.EdgePropertyMap`
Nonnegative edge costs, whose sum along the path is minimized.
resources : ``list`` of :class:`~graph_tool.EdgePropertyMap`
Nonnegative consumption of each resource by each edge.
limits : iterable of ``float``
Upper limit of the total consumption of each resource along the path.
pareto : ``bool`` (optional, default: ``False``)
If ``True``, all Pareto-optimal paths are returned (see below).
Returns
-------
path : :class:`numpy.ndarray` or ``None``
The edge indices of a feasible path of minimum cost (``None`` if there
is none).
cost : ``float``
Its cost.
consumption : :class:`numpy.ndarray`
Its consumption of each resource.
If ``pareto == True``, a list of such ``(path, cost, consumption)``
tuples is returned instead, ordered by cost, and then lexicographically
by consumption.
See Also
--------
shortest_path: Unconstrained shortest path
k_shortest_paths: The k shortest simple paths
Notes
-----
With :math:`c_e` the cost of edge :math:`e`, :math:`r^i_e` its
consumption of resource :math:`i`, and :math:`L_i` the limit of that
resource, the problem solved is
.. math::
\min_{P:\,s\to t}\sum_{e\in P}c_e \quad\text{subject to}\quad
\sum_{e\in P}r^i_e \le L_i \text{ for every } i,
where :math:`P` runs over the paths from the source :math:`s` to the
target :math:`t`. With ``pareto == True``, the feasible paths returned
are the Pareto-optimal ones, i.e. those for which no other feasible path
has a cost and a consumption of every resource that are all at most as
large, with at least one of them smaller. Of several Pareto-optimal paths
with the same cost and the same consumption of every resource, only one
is returned, which depends on the order in which the partial paths are
extended. If ``pareto == False``, the first of these paths is returned,
i.e. among the feasible paths of minimum cost, one whose consumption
vector is the smallest in lexicographic order.
The paths are found with the labeling algorithm for resource-constrained
shortest paths [irnich-shortest-2005]_, which extends partial paths along
the edges, discards the infeasible ones, and keeps only those not dominated
by another partial path at the same vertex. The problem is NP-hard, and the
number of labels, and hence the running time, can grow exponentially; it is
typically fast for few resources and tight limits. For undirected graphs,
both directions of every edge can be used.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 3), (0, 2), (2, 3)])
>>> c = g.new_ep("double", vals=[1, 1, 2, 2])
>>> r = g.new_ep("double", vals=[3, 3, 1, 1])
>>> path, cost, used = gt.resource_constrained_path(g, 0, 3, c, [r], [4])
>>> print(path, cost, used)
[2 3] 4.0 [2.]
References
----------
.. [irnich-shortest-2005] Stefan Irnich and Guy Desaulniers, "Shortest
path problems with resource constraints", in Column Generation,
Springer, 33-65 (2005), :DOI:`10.1007/0-387-25486-2_2`
"""
limits = numpy.asarray(limits, dtype="double")
if len(limits) != len(resources):
raise ValueError("There must be one limit per resource.")
c = numpy.asarray(cost.a, dtype="double")
R = numpy.zeros((len(c), len(limits)))
for k, r in enumerate(resources):
R[:, k] = r.a
paths, costs, used = libgraph_tool_structure.rcsp(g, c, R,
limits, int(source),
int(target))
sols = list(zip(paths, costs, used))
if pareto:
return sols
if len(sols) == 0:
return None, numpy.inf, None
return sols[0]
[docs]
def planar_faces(g, edges=False):
r"""Return the faces of a planar embedding of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used (the edge directions are ignored).
edges : ``bool`` (optional, default: ``False``)
If ``True``, the faces are returned as sequences of edge indices
instead of vertices.
Returns
-------
faces : ``list`` of :class:`numpy.ndarray` or ``None``
The vertices (or edges) around every face, in cyclic order, or
``None`` if the graph is not planar.
See Also
--------
is_planar: Planarity test and embedding
graph_tool.generation.make_maximal_planar: Maximal planar supergraph
graph_tool.draw.planar_layout: Straight-line planar drawing
Notes
-----
A
`planar embedding <https://en.wikipedia.org/wiki/Planar_graph>`_
is found with the Boyer-Myrvold algorithm
[boyer-cutting-2004]_, and its faces are traversed, in time
:math:`O(V + E)`. By Euler's formula, a connected planar graph has
:math:`E - V + 2` faces, including the outer face; a bridge appears twice
along the face that contains it. Parallel edges and self-loops are ignored.
Examples
--------
>>> g = gt.lattice([3, 3])
>>> faces = gt.planar_faces(g)
>>> print(len(faces), sorted(len(f) for f in faces))
5 [4, 4, 4, 4, 8]
References
----------
.. [boyer-cutting-2004] John M. Boyer and Wendy J. Myrvold, "On the
cutting edge: simplified O(n) planarity by edge addition", Journal of
Graph Algorithms and Applications 8(3), 241-273 (2004),
:DOI:`10.7155/jgaa.00091`
"""
ret = libgraph_tool_structure.planar_faces(
GraphView(g, directed=False))
if ret is None:
return None
vf, ef = ret
return list(ef) if edges else list(vf)
[docs]
def tutte_polynomial(g):
r"""Return the Tutte polynomial of a graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
T : :class:`numpy.ndarray`
Two-dimensional array of the coefficients, where ``T[i, j]`` is the
coefficient of :math:`x^iy^j`.
See Also
--------
chromatic_polynomial: Specialization that counts proper colorings
graph_tool.spectral.num_spanning_trees: Number of spanning trees
Notes
-----
The
`Tutte polynomial <https://en.wikipedia.org/wiki/Tutte_polynomial>`_
[tutte-contribution-1954]_ is
.. math::
T_G(x, y) = \sum_{A\subseteq E}(x-1)^{k(A)-k(E)}(y-1)^{k(A)+|A|-|V|},
where :math:`k(A)` is the number of connected components of the
spanning subgraph with edges :math:`A`. Many invariants are evaluations
of it: :math:`T_G(1,1)` is the number of spanning trees (of a connected
graph), :math:`T_G(2,1)` the number of spanning forests, :math:`T_G(2,0)`
the number of acyclic orientations, and the chromatic polynomial (see
:func:`~graph_tool.structure.chromatic_polynomial`) is :math:`T_G(1-k, 0)`
up to a factor.
The polynomial is computed by deletion and contraction,
:math:`T_G = T_{G-e} + T_{G/e}`, applied to whole classes of parallel
edges at once, with the product over the blocks (biconnected components)
of the graph taken at every step, and with a cache of the blocks already
computed, keyed by their canonical forms (computed with bliss for blocks
with ten or more classes of parallel edges), so that isomorphic minors
are computed once, as in [haggard-computing-2010]_. The edges are removed
along a breadth-first front of the vertices (numbered from a vertex of
minimum degree), which keeps the number of distinct minors small. The
time is exponential in the number of edges in the worst case, which
makes the computation feasible only for graphs with a few tens of edges
in the blocks (e.g. the Tutte polynomial of a :math:`6\times 6` grid,
with 60 edges, takes under one second); trees and other graphs with
small blocks are fast.
Examples
--------
>>> g = gt.complete_graph(4)
>>> T = gt.tutte_polynomial(g)
>>> print(T)
[[0 2 3 1]
[2 4 0 0]
[3 0 0 0]
[1 0 0 0]]
>>> print(T.sum()) # T(1, 1), the number of spanning trees
16
References
----------
.. [tutte-contribution-1954] William T. Tutte, "A contribution to the
theory of chromatic polynomials", Canadian Journal of Mathematics 6,
80-91 (1954), :DOI:`10.4153/CJM-1954-010-9`
.. [haggard-computing-2010] Gary Haggard, David J. Pearce and Gordon
Royle, "Computing Tutte polynomials", ACM Transactions on
Mathematical Software 37, 24 (2010), :DOI:`10.1145/1824801.1824802`
"""
vs = g.get_vertices()
idx = numpy.full(g.num_vertices(True), -1, dtype="int64")
idx[vs] = numpy.arange(len(vs))
es = numpy.ascontiguousarray(idx[g.get_edges()[:, :2]], dtype="int64")
c, nx, ny = libgraph_tool_structure.tutte_polynomial(len(vs), es, True)
return numpy.array(c, dtype="int64").reshape(nx, ny)
[docs]
def chromatic_polynomial(g):
r"""Return the chromatic polynomial of a graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
P : :class:`numpy.ndarray`
The coefficients, where ``P[i]`` is the coefficient of :math:`k^i`.
See Also
--------
tutte_polynomial: Tutte polynomial
sequential_vertex_coloring: Greedy vertex coloring
Notes
-----
The
`chromatic polynomial <https://en.wikipedia.org/wiki/Chromatic_polynomial>`_
[birkhoff-determinant-1912]_
[read-introduction-1968]_ :math:`P_G(k)` is the number of proper
colorings of the vertices with :math:`k` colors, i.e. those in which the
endpoints of every edge have different colors. It is obtained from the
Tutte polynomial as
.. math::
P_G(k) = (-1)^{|V|-c}\,k^c\,T_G(1-k, 0),
where :math:`c` is the number of connected components, with
:math:`T_G(x, 0)` computed as in
:func:`~graph_tool.structure.tutte_polynomial`, but with parallel edges
reduced to single ones and the complete blocks evaluated directly. The
polynomial vanishes for graphs with self-loops. The time is exponential
in the number of edges.
The polynomial can be evaluated with
:func:`numpy.polynomial.polynomial.polyval`.
Examples
--------
>>> g = gt.circular_graph(5)
>>> P = gt.chromatic_polynomial(g)
>>> print(P)
[ 0 4 -10 10 -5 1]
>>> print(np.polynomial.polynomial.polyval(3, P)) # 3-colorings
30.0
References
----------
.. [birkhoff-determinant-1912] George D. Birkhoff, "A determinant formula
for the number of ways of coloring a map", Annals of Mathematics 14,
42-46 (1912), :DOI:`10.2307/1967597`
.. [read-introduction-1968] Ronald C. Read, "An introduction to chromatic
polynomials", Journal of Combinatorial Theory 4, 52-71 (1968),
:DOI:`10.1016/S0021-9800(68)80087-0`
"""
vs = g.get_vertices()
n = len(vs)
idx = numpy.full(g.num_vertices(True), -1, dtype="int64")
idx[vs] = numpy.arange(n)
es = numpy.ascontiguousarray(idx[g.get_edges()[:, :2]], dtype="int64")
c = len(label_components(GraphView(g, directed=False))[1]) if n > 0 else 0
P = libgraph_tool_structure.chromatic_polynomial(n, c, es)
if isinstance(P, list):
return numpy.array([int(x) for x in P], dtype="object")
return P
[docs]
def is_chordal(g):
r"""Check whether a graph is chordal.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
chordal : ``bool``
``True`` if the graph is chordal.
See Also
--------
chordal_completion: Minimal chordal completion
chordal_cliques: Maximal cliques of a chordal graph
chordless_cycles: All chordless cycles
is_perfect: Test for perfect graphs
Notes
-----
A graph is `chordal <https://en.wikipedia.org/wiki/Chordal_graph>`_ if
every cycle of four or more vertices has a chord, i.e. an edge between two
of its vertices that are not consecutive in the cycle. Equivalently, it has
a perfect elimination ordering, in which the neighbors of every vertex
that come after it form a clique. Such an ordering is the reverse of the
order of maximum cardinality search, which visits each time the vertex
with the most visited neighbors, and it is checked with the zero fill-in
test of Tarjan and Yannakakis [tarjan-simple-1984]_, in time
:math:`O(V + E)`.
Examples
--------
>>> g = gt.lattice([3, 3])
>>> print(gt.is_chordal(g))
False
>>> g.add_edge_list(gt.chordal_completion(g))
>>> print(gt.is_chordal(g))
True
References
----------
.. [tarjan-simple-1984] Robert E. Tarjan and Mihalis Yannakakis, "Simple
linear-time algorithms to test chordality of graphs, test acyclicity
of hypergraphs, and selectively reduce acyclic hypergraphs", SIAM
Journal on Computing 13, 566-579 (1984), :DOI:`10.1137/0213035`
"""
return libgraph_tool_structure.is_chordal(g)
[docs]
def chordal_completion(g, order=False):
r"""Return the edges of a minimal chordal completion of a graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
order : ``bool`` (optional, default: ``False``)
If ``True``, a perfect elimination ordering of the completed graph is
also returned.
Returns
-------
fill : :class:`numpy.ndarray`
Array of shape ``(k, 2)`` with the endpoints of the edges whose
addition makes the graph chordal (see
:func:`~graph_tool.structure.is_chordal`).
order : :class:`numpy.ndarray`
The vertices in a perfect elimination ordering of the completed graph.
Only returned if ``order == True``.
See Also
--------
is_chordal: Test for chordal graphs
treewidth: Upper bound on the treewidth
junction_tree: Junction tree of a graph
Notes
-----
A
`chordal completion <https://en.wikipedia.org/wiki/Chordal_graph>`_
of a graph :math:`G = (V, E)` is a set :math:`F` of
pairs of non-adjacent vertices such that :math:`(V, E\cup F)` is chordal.
The completion is minimal, i.e. no proper subset of the added edges makes
the graph chordal, but it need not have the smallest number of edges,
which is an NP-hard problem. It is computed with the MCS-M algorithm
[berry-maximum-2004]_, which numbers the vertices as maximum cardinality
search does, but with weights that also count the vertices reachable
through paths of unnumbered vertices of smaller weight, which are joined
by the added edges. The algorithm runs in time :math:`O(VE)`.
Examples
--------
>>> g = gt.circular_graph(6)
>>> print(gt.chordal_completion(g))
[[1 5]
[5 2]
[2 4]]
The edges added can be shown in a drawing of the completed graph:
>>> fill = gt.chordal_completion(g)
>>> g.add_edge_list(fill)
>>> a = 2 * np.pi * np.arange(6) / 6
>>> pos = g.new_vp("vector<double>", vals=list(zip(np.cos(a), np.sin(a))))
>>> ecolor = g.new_ep("string", vals=["#999999"] * 6 +
... ["#e41a1c"] * len(fill))
>>> gt.graph_draw(g, pos, vertex_fill_color="#cccccc", edge_color=ecolor,
... vertex_size=30, edge_pen_width=2,
... output="chordal_completion-cycle.pdf")
<...>
.. testcleanup::
conv_png("chordal_completion-cycle.pdf")
.. figure:: chordal_completion-cycle.png
:align: center
:width: 30%
Minimal chordal completion of a cycle of six vertices. The edges of
the cycle are shown in gray, and those added in red.
References
----------
.. [berry-maximum-2004] Anne Berry, Jean R. S. Blair, Pinar Heggernes and
Barry W. Peyton, "Maximum cardinality search for computing minimal
triangulations of graphs", Algorithmica 39, 287-298 (2004),
:DOI:`10.1007/s00453-004-1084-3`
"""
fill, o = libgraph_tool_structure.chordal_completion(g)
fill = numpy.asarray(fill, dtype="int64").reshape(-1, 2)
if order:
return fill, numpy.asarray(o)[::-1].copy()
return fill
[docs]
def chordal_cliques(g):
r"""Return the maximal cliques of a chordal graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Chordal graph to be used. Edge directions are ignored.
Returns
-------
cliques : ``list`` of :class:`numpy.ndarray`
The vertices of every maximal clique.
See Also
--------
is_chordal: Test for chordal graphs
maximal_cliques: Maximal cliques of a general graph
junction_tree: Tree of the maximal cliques of a chordal completion
Notes
-----
A
`chordal graph <https://en.wikipedia.org/wiki/Chordal_graph>`_
has at most :math:`V` maximal cliques, which are found
from the order of maximum cardinality search [blair-introduction-1993]_ in
time :math:`O(V + E)`. The treewidth of a chordal graph is the size of its
largest clique minus one. A ``ValueError`` is raised if the graph is not
chordal (see :func:`~graph_tool.structure.is_chordal`); the maximal cliques
of general graphs are given by :func:`~graph_tool.structure.maximal_cliques`.
Examples
--------
>>> g = gt.circular_graph(6)
>>> g.add_edge_list(gt.chordal_completion(g))
>>> cs = gt.chordal_cliques(g)
>>> print(len(cs), max([len(c) for c in cs]) - 1)
4 2
References
----------
.. [blair-introduction-1993] Jean R. S. Blair and Barry Peyton, "An
introduction to chordal graphs and clique trees", in Graph Theory and
Sparse Matrix Computation, Springer, 1-29 (1993),
:DOI:`10.1007/978-1-4613-8369-7_1`
"""
cs = libgraph_tool_structure.chordal_cliques(g)
if cs is None:
raise ValueError("The graph is not chordal.")
return [numpy.asarray(c) for c in cs]
[docs]
def find_induced_nodes(g, s, t, treewidth_bound=None):
r"""Return the vertices on induced paths between two vertices of a chordal
graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Chordal graph to be used. Edge directions are ignored.
s : :class:`~graph_tool.Vertex` or ``int``
First vertex.
t : :class:`~graph_tool.Vertex` or ``int``
Second vertex.
treewidth_bound : ``int`` (optional, default: ``None``)
If given, a ``ValueError`` is raised as soon as the treewidth of the
intermediate graphs exceeds this value.
Returns
-------
nodes : :class:`numpy.ndarray`
The vertices on induced paths between ``s`` and ``t``, including
them, or an empty array if there are none besides the edge between
them.
See Also
--------
is_chordal: Test for chordal graphs
all_paths: All simple paths between two vertices
Notes
-----
An
`induced path <https://en.wikipedia.org/wiki/Induced_path>`_
is a path without chords, i.e. no edge of the graph
joins two of its vertices that are not consecutive along it. The method
of Elidan and Gould [elidan-learning-2008]_ adds the edge
:math:`(s, t)` and repeatedly finds, with maximum cardinality search from
:math:`s`, a triple :math:`(u, v, w)` of vertices that breaks chordality
(with :math:`u` and :math:`w` adjacent to :math:`v` but not to each
other), which is added to the result and joined to :math:`s`. It is used
to learn bounded-treewidth graphical models. A ``ValueError`` is raised
if the graph is not chordal.
Examples
--------
>>> g = gt.Graph([(i, i + 1) for i in range(9)], directed=False)
>>> print(gt.find_induced_nodes(g, 1, 9, treewidth_bound=2))
[1 2 3 4 5 6 7 8 9]
References
----------
.. [elidan-learning-2008] Gal Elidan and Stephen Gould, "Learning bounded
treewidth Bayesian networks", Journal of Machine Learning Research 9,
2699-2731 (2008), https://jmlr.org/papers/v9/elidan08a.html
"""
if not is_chordal(g):
raise ValueError("The graph is not chordal.")
if treewidth_bound is None:
treewidth_bound = numpy.iinfo("int64").max
return libgraph_tool_structure.find_induced_nodes(g,
int(s), int(t),
int(treewidth_bound))
[docs]
def is_perfect(g):
r"""Check whether a graph is perfect.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
perfect : ``bool``
``True`` if the graph is perfect.
See Also
--------
is_chordal: Test for chordal graphs
clique_number: Size of a largest clique
Notes
-----
A graph is `perfect <https://en.wikipedia.org/wiki/Perfect_graph>`_ if
the chromatic number of every induced subgraph equals the size of its
largest clique. By the
`strong perfect graph theorem <https://en.wikipedia.org/wiki/Strong_perfect_graph_theorem>`_
[chudnovsky-strong-2006]_, this holds if and only if neither the graph
nor its complement has an induced cycle of odd length larger than three.
Bipartite and chordal graphs are perfect, and are recognized directly;
otherwise, the induced cycles of the graph and of its complement are
enumerated as with :func:`~graph_tool.structure.chordless_cycles`, in
parallel from the different starting vertices, until an odd one is found,
which takes exponential time in the worst case.
(Polynomial algorithms exist [chudnovsky-recognizing-2005]_, but are
impractical.)
Examples
--------
>>> print(gt.is_perfect(gt.circular_graph(5)),
... gt.is_perfect(gt.circular_graph(6)))
False True
References
----------
.. [chudnovsky-strong-2006] Maria Chudnovsky, Neil Robertson, Paul
Seymour and Robin Thomas, "The strong perfect graph theorem", Annals of
Mathematics 164, 51-229 (2006), :DOI:`10.4007/annals.2006.164.51`
.. [chudnovsky-recognizing-2005] Maria Chudnovsky, Gérard Cornuéjols,
Xinming Liu, Paul Seymour and Kristina Vušković, "Recognizing Berge
graphs", Combinatorica 25, 143-186 (2005),
:DOI:`10.1007/s00493-005-0012-8`
"""
u = GraphView(g, directed=False)
if is_bipartite(u) or is_chordal(u):
return True
from .. generation import complement_graph
c = complement_graph(Graph(u, prune=True))
if is_bipartite(c) or is_chordal(c):
return True
return not (libgraph_tool_structure.has_odd_hole(u) or
libgraph_tool_structure.has_odd_hole(c))
[docs]
def find_asteroidal_triple(g):
r"""Return an asteroidal triple of a graph, if there is one.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
triple : ``tuple`` of ``int`` or ``None``
Three vertices forming an asteroidal triple, or ``None`` if the graph
is AT-free.
See Also
--------
is_chordal: Test for chordal graphs
Notes
-----
An asteroidal triple is a set of three pairwise non-adjacent vertices
such that every two of them are joined by a path that avoids the
neighborhood of the third. Graphs without them (
`AT-free graphs <https://en.wikipedia.org/wiki/Asteroidal_triple-free_graph>`_)
include
the interval, permutation, and cocomparability graphs. For every vertex,
the connected components of the graph without its closed neighborhood
are found (in parallel), in time :math:`O(V(V+E))` and memory
:math:`O(V^2)`, and then the triples of non-adjacent vertices are checked
against them, in time :math:`O(V^3)` in the worst case
[kohler-recognizing-2004]_. AT-free graphs are characterized in
[corneil-asteroidal-1997]_.
Examples
--------
>>> g = gt.circular_graph(6)
>>> print(gt.find_asteroidal_triple(g))
(0, 2, 4)
>>> print(gt.find_asteroidal_triple(gt.lattice([2, 4])))
None
References
----------
.. [kohler-recognizing-2004] Ekkehard Köhler, "Recognizing graphs without
asteroidal triples", Journal of Discrete Algorithms 2, 439-452 (2004),
:DOI:`10.1016/j.jda.2004.04.005`
.. [corneil-asteroidal-1997] Derek G. Corneil, Stephan Olariu and Lorna
Stewart, "Asteroidal triple-free graphs", SIAM Journal on Discrete
Mathematics 10, 399-430 (1997), :DOI:`10.1137/S0895480193250125`
"""
return libgraph_tool_structure.find_asteroidal_triple(g)
def _vmask(g, vs):
m = numpy.zeros(g.num_vertices(True), dtype="uint8")
if vs is None:
return m
if isinstance(vs, (int, numpy.integer)) or hasattr(vs, "out_degree"):
vs = [vs]
idx = numpy.asarray([int(v) for v in vs], dtype="int64")
m[idx] = 1
return m
[docs]
def is_d_separator(g, x, y, z):
r"""Check whether a set of vertices d-separates two others in a directed
acyclic graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed acyclic graph.
x : iterable of ``int`` or :class:`~graph_tool.Vertex`, or a single vertex
First set of vertices.
y : iterable of ``int`` or :class:`~graph_tool.Vertex`, or a single vertex
Second set of vertices.
z : iterable of ``int`` or :class:`~graph_tool.Vertex`, or a single vertex
Conditioning set of vertices.
Returns
-------
separated : ``bool``
``True`` if :math:`Z` d-separates :math:`X` from :math:`Y`.
See Also
--------
find_minimal_d_separator: Minimal d-separator of two sets of vertices
is_minimal_d_separator: Test for minimal d-separators
graph_tool.generation.moral_graph: Moral graph of a directed acyclic graph
graph_tool.flow.is_separator: Vertex separator test for undirected graphs
Notes
-----
In a Bayesian network, :math:`Z`
`d-separates <https://en.wikipedia.org/wiki/Bayesian_network#d-separation>`_
:math:`X` from :math:`Y` if
every trail (path ignoring the edge directions) between them is blocked,
which implies that :math:`X` and :math:`Y` are conditionally independent
given :math:`Z`. A trail is blocked by a vertex :math:`v` on it if
:math:`v` is a collider (both trail edges point to it) and neither
:math:`v` nor any of its descendants is in :math:`Z`, or if :math:`v` is
not a collider and is in :math:`Z` [pearl-probabilistic-1988]_. The
active trails from :math:`X` are explored with the "Bayes ball" search
[shachter-bayes-1998]_, in time :math:`O(V + E)`. The three sets must be
disjoint.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (3, 1)])
>>> print(gt.is_d_separator(g, 0, 2, [1]), gt.is_d_separator(g, 0, 3, []),
... gt.is_d_separator(g, 0, 3, [2]))
True True False
References
----------
.. [pearl-probabilistic-1988] Judea Pearl, "Probabilistic Reasoning in
Intelligent Systems", Morgan Kaufmann (1988).
.. [shachter-bayes-1998] Ross D. Shachter, "Bayes-ball: The rational
pastime (for determining irrelevance and requisite information in
belief networks and influence diagrams)", Proceedings of the
Fourteenth Conference on Uncertainty in Artificial Intelligence,
480-487 (1998), :arxiv:`1301.7412`
"""
_check_dag_sets(g, [x, y, z])
return libgraph_tool_structure.is_d_separator(g,
_vmask(g, x), _vmask(g, y),
_vmask(g, z))
def _check_dag_sets(g, sets):
if not g.is_directed() or not is_DAG(g):
raise ValueError("The graph must be a directed acyclic graph.")
ms = [_vmask(g, s) for s in sets]
for i in range(len(ms)):
for j in range(i + 1, len(ms)):
if (ms[i] & ms[j]).any():
raise ValueError("The vertex sets must be disjoint.")
[docs]
def find_minimal_d_separator(g, x, y, included=None, restricted=None):
r"""Return a minimal d-separator of two sets of vertices in a directed
acyclic graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed acyclic graph.
x : iterable of ``int`` or :class:`~graph_tool.Vertex`, or a single vertex
First set of vertices.
y : iterable of ``int`` or :class:`~graph_tool.Vertex`, or a single vertex
Second set of vertices.
included : iterable of ``int`` or :class:`~graph_tool.Vertex` (optional, default: ``None``)
Vertices that must belong to the separator.
restricted : iterable of ``int`` or :class:`~graph_tool.Vertex` (optional, default: ``None``)
If given, the separator may contain only these vertices.
Returns
-------
z : :class:`numpy.ndarray` or ``None``
The vertices of a minimal d-separator (see
:func:`~graph_tool.structure.is_d_separator`), or ``None`` if there is
none within the constraints.
See Also
--------
is_d_separator: Test for d-separators
is_minimal_d_separator: Test for minimal d-separators
graph_tool.generation.moral_graph: Moral graph of a directed acyclic graph
Notes
-----
A set :math:`Z`
`d-separates <https://en.wikipedia.org/wiki/Bayesian_network#d-separation>`_
:math:`X` from :math:`Y`
[pearl-probabilistic-1988]_ if every trail (path ignoring the edge
directions) between a vertex of :math:`X` and one of :math:`Y` is
blocked by :math:`Z`, i.e. contains a vertex :math:`v` that either is a
collider (both trail edges point to it) such that neither :math:`v` nor
any of its descendants is in :math:`Z`, or is not a collider and is in
:math:`Z` (see :func:`~graph_tool.structure.is_d_separator`).
The separator is minimal with respect to inclusion among those that
contain ``included``: no vertex outside ``included`` can be removed from
it. It is found with the algorithm of van der Zander and Liśkiewicz
[zander-finding-2020]_, which restricts the candidates to the ancestors
of :math:`X \cup Y \cup I` and removes those not reachable by active
trails from both sides, in time :math:`O(V + E)`.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (2, 3), (1, 3)])
>>> print(gt.find_minimal_d_separator(g, 0, 3))
[1]
>>> print(gt.find_minimal_d_separator(g, 0, 3, restricted=[2]))
None
References
----------
.. [pearl-probabilistic-1988] Judea Pearl, "Probabilistic Reasoning in
Intelligent Systems", Morgan Kaufmann (1988).
.. [zander-finding-2020] Benito van der Zander and Maciej Liśkiewicz,
"Finding minimal d-separators in linear time and applications",
Proceedings of the 35th Conference on Uncertainty in Artificial
Intelligence, PMLR 115, 637-647 (2020),
https://proceedings.mlr.press/v115/van-der-zander20a.html
"""
_check_dag_sets(g, [x, y, included])
inc = _vmask(g, included)
if restricted is None:
res = numpy.ones(g.num_vertices(True), dtype="uint8")
else:
res = _vmask(g, restricted)
if (inc & ~res.astype(bool)).any():
raise ValueError("The included vertices must be in restricted.")
z = libgraph_tool_structure.find_minimal_d_separator(g,
_vmask(g, x),
_vmask(g, y), inc, res)
if z is None:
return None
return numpy.flatnonzero(numpy.asarray(z))
[docs]
def is_minimal_d_separator(g, x, y, z, included=None):
r"""Check whether a set of vertices is a minimal d-separator of two others
in a directed acyclic graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed acyclic graph.
x : iterable of ``int`` or :class:`~graph_tool.Vertex`, or a single vertex
First set of vertices.
y : iterable of ``int`` or :class:`~graph_tool.Vertex`, or a single vertex
Second set of vertices.
z : iterable of ``int`` or :class:`~graph_tool.Vertex`, or a single vertex
Candidate separator.
included : iterable of ``int`` or :class:`~graph_tool.Vertex` (optional, default: ``None``)
Vertices that the separator must contain, which are not required to
be removable.
Returns
-------
minimal : ``bool``
``True`` if :math:`Z` d-separates :math:`X` from :math:`Y` and no
vertex of :math:`Z` outside ``included`` can be removed while keeping
this property.
See Also
--------
is_d_separator: Test for d-separators
find_minimal_d_separator: Minimal d-separator of two sets of vertices
Notes
-----
A set :math:`Z`
`d-separates <https://en.wikipedia.org/wiki/Bayesian_network#d-separation>`_
:math:`X` from :math:`Y`
[pearl-probabilistic-1988]_ if every trail (path ignoring the edge
directions) between a vertex of :math:`X` and one of :math:`Y` is
blocked by :math:`Z`, i.e. contains a vertex :math:`v` that either is a
collider (both trail edges point to it) such that neither :math:`v` nor
any of its descendants is in :math:`Z`, or is not a collider and is in
:math:`Z` (see :func:`~graph_tool.structure.is_d_separator`).
The set :math:`Z` is a minimal d-separator if it d-separates :math:`X`
from :math:`Y` and no proper subset of it that contains ``included``
does. The test of van der Zander and Liśkiewicz [zander-finding-2020]_
runs in time :math:`O(V + E)`.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (0, 3), (3, 2), (2, 4)])
>>> print(gt.is_minimal_d_separator(g, 0, 4, [2]),
... gt.is_minimal_d_separator(g, 0, 4, [1, 3]),
... gt.is_minimal_d_separator(g, 0, 4, [1, 2]))
True True False
References
----------
.. [pearl-probabilistic-1988] Judea Pearl, "Probabilistic Reasoning in
Intelligent Systems", Morgan Kaufmann (1988).
.. [zander-finding-2020] Benito van der Zander and Maciej Liśkiewicz,
"Finding minimal d-separators in linear time and applications",
Proceedings of the 35th Conference on Uncertainty in Artificial
Intelligence, PMLR 115, 637-647 (2020),
https://proceedings.mlr.press/v115/van-der-zander20a.html
"""
_check_dag_sets(g, [x, y, z])
inc = _vmask(g, included)
zm = _vmask(g, z)
if (inc & ~zm.astype(bool)).any():
raise ValueError("The included vertices must be in z.")
return libgraph_tool_structure.is_minimal_d_separator(g,
_vmask(g, x),
_vmask(g, y), zm,
inc)
[docs]
def is_tournament(g):
r"""Check whether a directed graph is a tournament.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed graph.
Returns
-------
tournament : ``bool``
``True`` if there is exactly one edge between every pair of distinct
vertices, and no self-loops.
See Also
--------
tournament_hamiltonian_path: Hamiltonian path of a tournament
graph_tool.generation.generate_tournament: Random tournament
Notes
-----
A `tournament <https://en.wikipedia.org/wiki/Tournament_(graph_theory)>`_
is an orientation of a complete graph, i.e. a directed graph without
self-loops in which every pair of distinct vertices is joined by exactly
one edge, in one of the two directions. Its score sequence is given by
the out-degrees. The time is :math:`O(V + E)`.
Examples
--------
>>> g = gt.Graph([(i, j) if (i + j) % 2 else (j, i)
... for i in range(6) for j in range(i + 1, 6)])
>>> print(gt.is_tournament(g))
True
"""
if not g.is_directed():
return False
return libgraph_tool_structure.is_tournament(g)
[docs]
def tournament_hamiltonian_path(g):
r"""Return a Hamiltonian path of a tournament.
Parameters
----------
g : :class:`~graph_tool.Graph`
Tournament (see :func:`~graph_tool.structure.is_tournament`).
Returns
-------
path : :class:`numpy.ndarray`
The vertices in the order of a directed path that visits all of them.
See Also
--------
is_tournament: Test for tournaments
tsp_tour: Traveling salesman tour
Notes
-----
Every tournament has a
`Hamiltonian path <https://en.wikipedia.org/wiki/Hamiltonian_path>`_
[redei-kombinatorischer-1934]_. It
is built by inserting every vertex at the front, at the back, or, found by
binary search, between two consecutive vertices :math:`u \to v` of the
path such that :math:`u \to w \to v`, with :math:`O(V\log V)` adjacency
tests after the edges are hashed in time :math:`O(E)`. A ``ValueError``
is raised if the graph is not a tournament.
Examples
--------
>>> g = gt.Graph([(i, j) if (i + j) % 2 else (j, i)
... for i in range(6) for j in range(i + 1, 6)])
>>> p = gt.tournament_hamiltonian_path(g)
>>> print(p, all(g.edge(u, v) is not None for u, v in zip(p[:-1], p[1:])))
[4 2 0 5 3 1] True
References
----------
.. [redei-kombinatorischer-1934] László Rédei, "Ein kombinatorischer Satz",
Acta Litterarum ac Scientiarum Szeged 7, 39-43 (1934).
"""
if not is_tournament(g):
raise ValueError("The graph is not a tournament.")
return libgraph_tool_structure.tournament_hamiltonian_path(g)
[docs]
def loop_erased_random_walk(g, source, targets, weight=None):
r"""Return a loop-erased random walk from a vertex to a set of targets.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex` or ``int``
Starting vertex.
targets : iterable of ``int`` or :class:`~graph_tool.Vertex`
Vertices at which the walk stops.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights. If given, the next edge is chosen with probability
proportional to its weight; otherwise, uniformly.
Returns
-------
path : :class:`numpy.ndarray`
The vertices of the walk after its loops are erased, from ``source``
to the first target reached.
See Also
--------
random_walk: Simple and biased random walks
random_spanning_tree: Uniformly sampled spanning tree
Notes
-----
The random walk starts at ``source`` and moves at each step along an
out-edge of the current vertex, chosen uniformly at random, or with
probability proportional to its weight, until it reaches a target. Its
`loop erasure <https://en.wikipedia.org/wiki/Loop-erased_random_walk>`_
[lawler-self-1980]_ is obtained chronologically: every time
the walk returns to a vertex already on the path, the loop formed since
the previous visit is erased from the path. The result is a self-avoiding
path; the loop-erased walks from every vertex to the tree built so far
yield a uniform random spanning tree in Wilson's algorithm (see
:func:`~graph_tool.structure.random_spanning_tree`). The expected time is
the hitting time of the targets. A ``ValueError`` is raised if the walk
reaches a vertex without out-edges.
Examples
--------
.. testsetup:: lerw
gt.seed_rng(42)
.. doctest:: lerw
>>> g = gt.lattice([10, 10])
>>> path = gt.loop_erased_random_walk(g, 0, [99])
>>> print(path[0], path[-1], len(set(path)) == len(path))
0 99 True
The path can be shown in a drawing of the lattice:
.. doctest:: lerw
>>> pos = g.new_vp("vector<double>",
... vals=[(i % 10, i // 10) for i in range(100)])
>>> onpath = g.new_ep("bool")
>>> for u, v in zip(path[:-1], path[1:]):
... onpath[g.edge(u, v)] = True
>>> inpath = g.new_vp("bool")
>>> inpath.a[path] = True
>>> vcolor = g.new_vp("string", vals=np.where(inpath.a, "#f28c8e",
... "#cccccc"))
>>> ecolor = g.new_ep("string", vals=np.where(onpath.a, "#e41a1c",
... "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(onpath.a, 3, 1))
>>> gt.graph_draw(g, pos, vertex_fill_color=vcolor, edge_color=ecolor,
... edge_pen_width=ewidth,
... output="loop_erased_random_walk-lattice.pdf")
<...>
.. testcleanup:: lerw
conv_png("loop_erased_random_walk-lattice.pdf")
.. figure:: loop_erased_random_walk-lattice.png
:align: center
:width: 40%
Loop-erased random walk from the corner vertex 0 to the opposite
corner of a :math:`10\times 10` lattice, with its vertices and edges
shown in red.
References
----------
.. [lawler-self-1980] Gregory F. Lawler, "A self-avoiding random walk",
Duke Mathematical Journal 47, 655-693 (1980),
:DOI:`10.1215/S0012-7094-80-04741-9`
"""
target = numpy.zeros(g.num_vertices(True), dtype="uint8")
target[numpy.asarray([int(v) for v in targets], dtype="int64")] = 1
return libgraph_tool_structure.lerw(g, int(source), target, weight,
_get_rng())
[docs]
def common_spanning_trees(g1, g2):
r"""Return an iterator over the spanning trees common to two graphs with
corresponding edges.
Parameters
----------
g1 : :class:`~graph_tool.Graph`
First graph. Edge directions are ignored.
g2 : :class:`~graph_tool.Graph`
Second graph, with the same number of vertices and edges.
Returns
-------
trees : iterator over :class:`numpy.ndarray`
For every common spanning tree, a boolean array over the edges, in
the order of their indices, marking those in the tree.
See Also
--------
all_spanning_arborescences: Spanning arborescences in order of weight
random_spanning_tree: Uniformly sampled spanning tree
Notes
-----
The edges of ``g1`` and ``g2`` correspond in the order of their indices
(:attr:`~graph_tool.Graph.edge_index`), and a set of edges is a
`common spanning tree <https://en.wikipedia.org/wiki/Spanning_tree>`_
if it forms a spanning tree of both graphs. Such pairs of
graphs arise as the current and voltage graphs of electrical networks
with controlled sources, whose common spanning trees give the terms of
the network determinant [mayeda-generation-1965]_. For simple graphs,
they are enumerated with the algorithm of Mayeda and Seshu
[mayeda-generation-1965]_, and for multigraphs instead
by binary branching over the edges [read-bounds-1975]_, where an edge is
included only if it closes no cycle in either graph, and a branch is
abandoned as soon as the remaining edges cannot connect both graphs. The
number of trees can grow exponentially.
Examples
--------
>>> g1 = gt.Graph([(0, 1), (1, 2), (2, 0)], directed=False)
>>> g2 = gt.Graph([(0, 1), (0, 2), (2, 1)], directed=False)
>>> for t in gt.common_spanning_trees(g1, g2):
... print(t)
[ True True False]
[ True False True]
[False True True]
References
----------
.. [mayeda-generation-1965] Wataru Mayeda and Sundaram Seshu, "Generation
of trees without duplications", IEEE Transactions on Circuit Theory
12, 181-185 (1965), :DOI:`10.1109/TCT.1965.1082432`
.. [read-bounds-1975] Ronald C. Read and Robert E. Tarjan, "Bounds on
backtrack algorithms for listing cycles, paths, and spanning trees",
Networks 5, 237-252 (1975), :DOI:`10.1002/net.1975.5.3.237`
"""
if g1.num_vertices() != g2.num_vertices() or \
g1.num_edges() != g2.num_edges():
raise ValueError("The graphs must have the same numbers of vertices " +
"and edges.")
def compact(g):
vs = g.get_vertices()
idx = numpy.full(g.num_vertices(True), -1, dtype="int64")
idx[vs] = numpy.arange(len(vs))
es = g.get_edges([g.edge_index])
es = es[numpy.argsort(es[:, 2], kind="stable")]
return numpy.ascontiguousarray(idx[es[:, :2]],
dtype="int64").reshape(-1, 2)
for t in libgraph_tool_structure.common_spanning_trees(g1.num_vertices(),
compact(g1),
compact(g2)):
yield numpy.asarray(t, dtype="bool")
[docs]
def is_straight_line_drawing(g, pos):
r"""Check whether a drawing of a graph with straight edges on an integer
grid has no edge crossings.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
pos : :class:`~graph_tool.VertexPropertyMap`
Vector-valued vertex positions, which must have integer values.
Returns
-------
planar : ``bool``
``True`` if no two edges, drawn as straight segments, cross or
overlap, other than at common endpoints.
See Also
--------
is_planar: Planarity test
graph_tool.draw.planar_layout: Straight-line planar drawing
Notes
-----
Two edges cross if they intersect at a point other than a common endpoint,
or if one passes through an endpoint of the other, as decided exactly with
integer orientation predicates. After sorting the edges by their leftmost
coordinate, only the pairs whose horizontal and vertical ranges overlap are
tested, which takes time :math:`O(E\log E)` plus the number of such pairs,
:math:`O(E^2)` in the worst case. It verifies the output of
:func:`~graph_tool.draw.planar_layout`, whose coordinates are integers.
Examples
--------
>>> g = gt.lattice([4, 4])
>>> pos = g.new_vp("vector<double>",
... vals=[(i % 4, i // 4) for i in range(16)])
>>> print(gt.is_straight_line_drawing(g, pos))
True
>>> pos[0] = (3, 3)
>>> print(gt.is_straight_line_drawing(g, pos))
False
"""
return libgraph_tool_structure.is_straight_line_drawing(
GraphView(g, directed=False), pos._get_any())
[docs]
def make_connected(g):
r"""Add edges to a graph to make it connected.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be modified. Edge directions are ignored.
Returns
-------
edges : :class:`numpy.ndarray`
Array of shape ``(k, 2)`` with the endpoints of the added edges.
See Also
--------
label_components: Connected components
graph_tool.flow.k_edge_augmentation: Edges for k-edge-connectivity
Notes
-----
The
`components <https://en.wikipedia.org/wiki/Component_(graph_theory)>`_
are ordered by their vertices of lowest index, ignoring
the edge directions, and an edge is added from the vertex of highest
index of every component to the vertex of lowest index of the next one,
so that :math:`C - 1` edges
connect :math:`C` components, in time :math:`O(V + E)`.
Examples
--------
>>> g = gt.Graph([(0, 1), (2, 3), (4, 5)], directed=False)
>>> print(gt.make_connected(g))
[[1 2]
[3 4]]
>>> print(gt.label_components(g)[1])
[6]
"""
vs = g.get_vertices()
idx = numpy.full(g.num_vertices(True), -1, dtype="int64")
idx[vs] = numpy.arange(len(vs))
es = numpy.ascontiguousarray(idx[g.get_edges()[:, :2]],
dtype="int64").reshape(-1, 2)
added = numpy.asarray(libgraph_tool_structure.make_connected(len(vs), es),
dtype="int64").reshape(-1, 2)
added = vs[added]
g.add_edge_list(added, parallel=False)
return added
[docs]
def all_cliques(g, min_size=1, max_size=None):
r"""Return an iterator over all cliques of a graph, maximal or not.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions, self-loops, and parallel edges are
ignored.
min_size : ``int`` (optional, default: ``1``)
Smallest size of the cliques returned.
max_size : ``int`` (optional, default: ``None``)
If given, largest size of the cliques returned.
Returns
-------
cliques : iterator over :class:`numpy.ndarray`
The vertices of every clique.
See Also
--------
maximal_cliques: Maximal cliques only
largest_cliques: Cliques of maximum size
graph_tool.clustering.motifs: Counts of connected subgraphs
Notes
-----
Unlike :func:`~graph_tool.structure.maximal_cliques`, which returns only the
maximal cliques, every
`complete subgraph <https://en.wikipedia.org/wiki/Clique_(graph_theory)>`_
is returned once. The vertices
are ordered by degeneracy (smallest-last), and each clique is generated
from its first vertex in this order by adding later common neighbors, so
that the time is :math:`O(d)` per clique vertex, where :math:`d` is the
degeneracy. The number of cliques can grow exponentially with
:math:`d`.
Examples
--------
>>> g = gt.complete_graph(4)
>>> print(len(list(gt.all_cliques(g))))
15
>>> print(sorted(len(c) for c in gt.all_cliques(g, min_size=3)))
[3, 3, 3, 3, 4]
"""
# the edge directions are ignored
if g.is_directed():
g = GraphView(g, directed=False)
if max_size is None:
max_size = 0
for c in libgraph_tool_structure.all_cliques(g,
int(min_size),
int(max_size)):
yield numpy.asarray(c)
[docs]
def largest_cliques(g):
r"""Return all the cliques of maximum size of a graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
cliques : ``list`` of :class:`numpy.ndarray`
The vertices of every clique of maximum size.
See Also
--------
maximal_cliques: All maximal cliques
clique_number: Size of a largest clique
maximum_weight_clique: Clique of maximum total vertex weight
approx_maximum_clique: Approximate maximum clique
Notes
-----
A
`clique <https://en.wikipedia.org/wiki/Clique_(graph_theory)>`_
is a set of vertices every two of which are adjacent, ignoring
the edge directions, and the cliques returned are those of size
:math:`\omega(G)`, the clique number. The maximal cliques are enumerated
as in :func:`~graph_tool.structure.clique_number`, in parallel and in a
single pass, pruning the branches that cannot reach the size of the
largest clique found so far; the time is exponential in the worst case.
Every clique is returned with its vertices in increasing order, and the
cliques in lexicographic order.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(sorted(sorted(c.tolist()) for c in gt.largest_cliques(g)))
[[0, 1, 2, 3, 7], [0, 1, 2, 3, 13]]
The cliques can be highlighted in a drawing of the network:
>>> inc = g.new_vp("bool")
>>> ine = g.new_ep("bool")
>>> for c in gt.largest_cliques(g):
... inc.a[c] = True
... for i, u in enumerate(c):
... for v in c[i + 1:]:
... ine[g.edge(u, v)] = True
>>> vcolor = g.new_vp("string", vals=np.where(inc.a, "#f28c8e",
... "#cccccc"))
>>> ecolor = g.new_ep("string", vals=np.where(ine.a, "#e41a1c",
... "#999999"))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color=ecolor, output="largest_cliques-karate.pdf")
<...>
.. testcleanup::
conv_png("largest_cliques-karate.pdf")
.. figure:: largest_cliques-karate.png
:align: center
:width: 50%
Largest cliques of Zachary's karate club network, two cliques of five
vertices that share four of them, with their vertices and edges shown
in red.
"""
return libgraph_tool_structure.largest_cliques(
GraphView(g, directed=False))
[docs]
def maximum_weight_clique(g, weight=None, all=False):
r"""Return a clique of maximum total vertex weight.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
weight : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Nonnegative vertex weights. If not given, every vertex has weight one,
and a maximum clique is returned.
all : ``bool`` (optional, default: ``False``)
If ``True``, all the cliques of maximum weight are returned.
Returns
-------
clique : :class:`numpy.ndarray` or ``list`` of :class:`numpy.ndarray`
The vertices of the clique, or a list with the vertices of every
clique of maximum weight, if ``all == True``.
w : ``float``
The total weight.
See Also
--------
largest_cliques: Cliques of maximum size
approx_maximum_clique: Approximate maximum clique
Notes
-----
The
`clique <https://en.wikipedia.org/wiki/Clique_problem>`_
is found by branch and bound, in which the vertices that can
extend the current clique are bounded by a greedy weighted coloring:
each color class contributes the smallest residual weight of its
vertices, and the vertices covered by classes whose total weight does not
exceed the margin to the best clique found need no branching
[warren-combinatorial-2006]_. With ``all == True``, only the branches
whose bound is smaller than the best weight are pruned, and every clique
whose weight equals the best one (up to a relative difference of
:math:`10^{-10}`) is kept. Vertices of weight zero are ignored, also in
the cliques returned. The time is exponential in the worst case.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> w = g.degree_property_map("total")
>>> c, cw = gt.maximum_weight_clique(g, w)
>>> print(sorted(c.tolist()), cw)
[0, 1, 2, 3, 13] 46.0
>>> cs, cw = gt.maximum_weight_clique(g, all=True)
>>> print(sorted(sorted(c.tolist()) for c in cs), cw)
[[0, 1, 2, 3, 7], [0, 1, 2, 3, 13]] 5.0
References
----------
.. [warren-combinatorial-2006] Jeffrey S. Warren and Illya V. Hicks,
"Combinatorial branch-and-bound for the maximum weight independent set
problem", Technical report, Texas A&M University (2006).
"""
if g.is_directed():
g = GraphView(g, directed=False)
cs, w = libgraph_tool_structure.max_weight_clique(g, weight, all)
if all:
return [numpy.asarray(c) for c in cs], w
return numpy.asarray(cs[0]), w
[docs]
def independence_number(g):
r"""Return the size of the largest independent vertex set of a graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
alpha : ``int``
The independence number.
See Also
--------
largest_independent_vertex_sets: Independent vertex sets of maximum size
clique_number: Size of a largest clique
clique_removal: Approximate maximum independent vertex set
Notes
-----
An
`independent vertex set <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_
is a set of vertices no two of which are
adjacent (ignoring the edge directions), and the independence number is
.. math::
\alpha(G) = \max\{|I| : I \text{ is an independent set of } G\}.
It is the clique number of the complement graph
(see :func:`~graph_tool.generation.complement_graph` and
:func:`~graph_tool.structure.clique_number`), which is computed in time
exponential in the worst case, after the complement is built in time
:math:`O(V^2)`.
Examples
--------
>>> print(gt.independence_number(gt.circular_graph(7)))
3
"""
return clique_number(_simple_complement(g)[0])
def _simple_complement(g):
from .. generation import complement_graph
u = Graph(GraphView(g, directed=False), prune=True)
remove_parallel_edges(u)
remove_self_loops(u)
return complement_graph(u), g.get_vertices()
[docs]
def largest_independent_vertex_sets(g):
r"""Return all the independent vertex sets of maximum size of a graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
sets : ``list`` of :class:`numpy.ndarray`
The vertices of every independent set of maximum size.
See Also
--------
maximal_independent_vertex_sets: All maximal independent vertex sets
independence_number: Size of a largest independent vertex set
maximal_independent_vertex_set: A single maximal independent vertex set
largest_cliques: Cliques of maximum size
Notes
-----
An
`independent vertex set <https://en.wikipedia.org/wiki/Independent_set_(graph_theory)>`_
is a set of vertices no two of which are
adjacent (ignoring the edge directions), and the sets returned are those
of the largest size, :math:`\alpha(G)` (see
:func:`~graph_tool.structure.independence_number`). They are the largest
cliques of the complement graph (see
:func:`~graph_tool.structure.largest_cliques`); the time is exponential in
the worst case. A single maximal (not necessarily maximum) independent
set is found in linear time by
:func:`~graph_tool.structure.maximal_independent_vertex_set`.
Examples
--------
>>> print(len(gt.largest_independent_vertex_sets(gt.circular_graph(6))))
2
"""
c, vs = _simple_complement(g)
return [vs[x] for x in largest_cliques(c)]
[docs]
def maximal_independent_vertex_sets(g):
r"""Return an iterator over all maximal independent vertex sets of a
graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
sets : iterator over :class:`numpy.ndarray`
The vertices of every maximal independent set.
See Also
--------
maximal_independent_vertex_set: A single maximal independent vertex set
largest_independent_vertex_sets: Independent vertex sets of maximum size
maximal_cliques: All maximal cliques
Notes
-----
An independent vertex set is a set of vertices no two of which are
adjacent (ignoring the edge directions), and it is
`maximal <https://en.wikipedia.org/wiki/Maximal_independent_set>`_
if no other
vertex can be added to it, i.e. if every vertex outside it is adjacent
to one of its vertices. The sets are the maximal cliques of the
complement graph (see
:func:`~graph_tool.structure.maximal_cliques`), whose number can grow
exponentially with the size of the graph.
Examples
--------
>>> g = gt.circular_graph(6)
>>> print(len(list(gt.maximal_independent_vertex_sets(g))))
5
"""
c, vs = _simple_complement(g)
# maximal_cliques() omits the isolated vertices, which are singleton maximal
# cliques
for v in c.get_vertices()[c.get_out_degrees(c.get_vertices()) == 0]:
yield vs[[v]]
for x in maximal_cliques(c):
yield vs[numpy.asarray(x, dtype="int64")]
[docs]
def dsatur_vertex_coloring(g, color=None):
r"""Return a vertex coloring obtained with the DSatur heuristic.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
color : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If given, the colors are stored in this property map, which must be of
type ``int32_t``.
Returns
-------
color : :class:`~graph_tool.VertexPropertyMap`
The color of every vertex, numbered from zero.
See Also
--------
sequential_vertex_coloring: Greedy coloring in a given order
equitable_vertex_coloring: Coloring with color classes of nearly equal size
Notes
-----
The coloring is proper, i.e. adjacent vertices receive different colors,
and DSatur seeks one with few colors. The
`DSatur algorithm <https://en.wikipedia.org/wiki/DSatur>`_
[brelaz-new-1979]_ colors next the uncolored vertex
with the largest number of distinct colors among its neighbors (its
saturation), with ties broken by the number of uncolored neighbors, and
gives it the smallest color not used by its neighbors. It is exact for
bipartite graphs and usually needs fewer colors than the static orders of
:func:`~graph_tool.structure.sequential_vertex_coloring`. The time is
:math:`O((V + E)\log V)`.
Examples
--------
>>> g = gt.collection.data["football"]
>>> c = gt.dsatur_vertex_coloring(g)
>>> print(c.a.max() + 1)
9
The coloring can be shown in a drawing of the network:
>>> palette = np.array(["#9bbedc", "#f28c8e", "#a6d7a4", "#cba6d1",
... "#ffbf7f", "#ffff99", "#d2aa93", "#fbc0df",
... "#cccccc"])
>>> vcolor = g.new_vp("string", vals=palette[c.a])
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color="#999999",
... output="dsatur_vertex_coloring-football.pdf")
<...>
.. testcleanup::
conv_png("dsatur_vertex_coloring-football.pdf")
.. figure:: dsatur_vertex_coloring-football.png
:align: center
:width: 60%
Vertex coloring with nine colors of the network of American college
football games obtained with DSatur.
References
----------
.. [brelaz-new-1979] Daniel Brélaz, "New methods to color the vertices of
a graph", Communications of the ACM 22, 251-256 (1979),
:DOI:`10.1145/359094.359101`
"""
if color is None:
color = g.new_vp("int32_t")
_check_prop_writable(color, name="color")
_check_prop_scalar(color, name="color")
if color.value_type() != "int32_t":
raise ValueError("The color property map must be of type int32_t.")
libgraph_tool_structure.dsatur_coloring(g, color)
return color
[docs]
def equitable_vertex_coloring(g, k=None, color=None):
r"""Return an equitable vertex coloring with ``k`` colors.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
k : ``int`` (optional, default: ``None``)
Number of colors, which must be larger than the maximum degree
:math:`\Delta`. If not given, :math:`k = \Delta + 1` is used.
color : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If given, the colors are stored in this property map, which must be of
type ``int32_t``.
Returns
-------
color : :class:`~graph_tool.VertexPropertyMap`
The color of every vertex, from :math:`0` to :math:`k-1`.
See Also
--------
sequential_vertex_coloring: Greedy coloring in a given order
dsatur_vertex_coloring: Coloring with the DSatur heuristic
Notes
-----
A coloring is
`equitable <https://en.wikipedia.org/wiki/Equitable_coloring>`_
if adjacent vertices have different colors and
the numbers of vertices with each color differ by at most one. The
Hajnal–Szemerédi theorem guarantees that one exists for every
:math:`k > \Delta`, and the algorithm of Kierstead, Kostochka, Mydlarz and
Szemerédi [kierstead-fast-2010]_ finds it. The edges are added one at a
time to an equitable coloring of the empty graph, and whenever an edge
joins two vertices of the same color, the coloring is repaired by moving
vertices between color classes. Self-loops and parallel edges are
ignored, and a ``ValueError`` is raised if :math:`k \le \Delta`.
The time is :math:`O(kV^2)` and the memory :math:`O(kV)`.
Examples
--------
>>> g = gt.collection.data["football"]
>>> c = gt.equitable_vertex_coloring(g)
>>> print(c.a.max() + 1, np.bincount(c.a))
13 [9 9 9 9 9 9 9 9 9 9 9 8 8]
A square lattice has maximum degree :math:`\Delta = 4`, and hence is
colored equitably with five colors, as shown in the figure below:
>>> g = gt.lattice([8, 8])
>>> c = gt.equitable_vertex_coloring(g)
>>> print(np.bincount(c.a))
[13 13 13 13 12]
>>> pos = g.new_vp("vector<double>",
... vals=[(v % 8, v // 8) for v in g.get_vertices()])
>>> cmap = matplotlib.colors.ListedColormap(["#9bbedc", "#f28c8e",
... "#a6d7a4", "#cba7d1",
... "#ffbf80"])
>>> gt.graph_draw(g, pos, vertex_fill_color=c, vcmap=cmap,
... output="equitable_vertex_coloring-lattice.pdf")
<...>
.. testcleanup::
conv_png("equitable_vertex_coloring-lattice.pdf")
.. figure:: equitable_vertex_coloring-lattice.png
:align: center
:width: 40%
Equitable coloring of a :math:`8\times 8` square lattice with five
colors, which are used by 13, 13, 13, 13, and 12 vertices.
References
----------
.. [kierstead-fast-2010] Henry A. Kierstead, Alexandr V. Kostochka, Marcelo
Mydlarz and Endre Szemerédi, "A fast algorithm for equitable coloring",
Combinatorica 30, 217-224 (2010), :DOI:`10.1007/s00493-010-2483-5`
"""
if color is None:
color = g.new_vp("int32_t")
_check_prop_writable(color, name="color")
_check_prop_scalar(color, name="color")
if color.value_type() != "int32_t":
raise ValueError("The color property map must be of type int32_t.")
if k is None:
k = 0
elif k < 1:
raise ValueError("The number of colors must be positive.")
libgraph_tool_structure.equitable_coloring(
GraphView(g, directed=False), int(k), color._get_any())
return color
[docs]
def minimum_edge_cover(g):
r"""Return an edge cover of minimum size.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
cover : :class:`~graph_tool.EdgePropertyMap`
Boolean edge property map marking the edges of the cover.
See Also
--------
maximum_cardinality_matching: Maximum matching, extended to the cover
approx_minimum_vertex_cover: Vertex counterpart
Notes
-----
An
`edge cover <https://en.wikipedia.org/wiki/Edge_cover>`_
is a set of edges such that every vertex is incident to at
least one of them. A minimum one is obtained from a maximum matching (see
:func:`~graph_tool.structure.maximum_cardinality_matching`) by adding, for
every unmatched vertex, one of its edges [gallai-uber-1959]_, so that it
has :math:`V - M` edges, where :math:`M` is the size of the matching.
Self-loops are not used. A ``ValueError`` is raised if there are
isolated vertices.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> c = gt.minimum_edge_cover(g)
>>> print(c.a.sum())
21
The cover can be highlighted in a drawing of the network:
>>> ecolor = g.new_ep("string", vals=np.where(c.a, "#e41a1c", "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(c.a, 2.5, 1))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color="#cccccc",
... edge_color=ecolor, edge_pen_width=ewidth,
... output="minimum_edge_cover-karate.pdf")
<...>
.. testcleanup::
conv_png("minimum_edge_cover-karate.pdf")
.. figure:: minimum_edge_cover-karate.png
:align: center
:width: 50%
Minimum edge cover of Zachary's karate club network, with its edges
shown in red.
References
----------
.. [gallai-uber-1959] Tibor Gallai, "Über extreme Punkt- und
Kantenmengen", Annales Universitatis Scientiarum Budapestinensis de
Rolando Eötvös Nominatae, Sectio Mathematica 2, 133-138 (1959).
"""
u = GraphView(g, directed=False)
nl = GraphView(u, efilt=label_self_loops(u, mark_only=True).a == 0)
if (nl.get_total_degrees(nl.get_vertices()) == 0).any():
raise ValueError("The graph has isolated vertices.")
cover = maximum_cardinality_matching(nl, edges=True)
libgraph_tool_structure.complete_edge_cover(nl,
cover._get_any())
return g.own_property(cover)
[docs]
def k_factor(g, k):
r"""Return a :math:`k`-factor of a graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Simple undirected graph to be used.
k : ``int``
Degree of every vertex in the factor.
Returns
-------
factor : :class:`~graph_tool.EdgePropertyMap` or ``None``
Boolean edge property map marking the edges of a spanning subgraph in
which every vertex has degree :math:`k`, or ``None`` if there is none.
See Also
--------
maximum_cardinality_matching: Maximum matching, i.e. a 1-factor if perfect
minimum_edge_cover: Edge cover of minimum size
Notes
-----
Every vertex :math:`v` of degree :math:`d` is replaced by a gadget of
Tutte [tutte-short-1954]_: :math:`d` outer vertices, one per incident
edge, joined to the outer vertex of the other endpoint; and, if
:math:`k \ge d/2`, :math:`d - k` core vertices joined to all outer ones,
or otherwise :math:`d` inner vertices matched to the outer ones and
:math:`k` core vertices joined to all inner ones. The graph has a
:math:`k`-factor if and only if the gadget graph has a perfect matching
(found with Edmonds' algorithm, as in
:func:`~graph_tool.structure.maximum_cardinality_matching`), whose edges
between outer vertices give the
`factor <https://en.wikipedia.org/wiki/Graph_factorization>`_.
The gadget graph has
:math:`O(E k)` vertices and :math:`O(\sum_v k_v^2)` edges.
Examples
--------
>>> g = gt.lattice([4, 4], periodic=True)
>>> f = gt.k_factor(g, 2)
>>> h = gt.GraphView(g, efilt=f)
>>> print(set(h.get_total_degrees(h.get_vertices()).tolist()))
{2}
References
----------
.. [tutte-short-1954] William T. Tutte, "A short proof of the factor
theorem for finite graphs", Canadian Journal of Mathematics 6,
347-352 (1954), :DOI:`10.4153/CJM-1954-033-3`
"""
if k < 0:
raise ValueError("k must be non-negative")
factor = g.new_ep("bool")
if not libgraph_tool_structure.k_factor(g, int(k),
factor._get_any()):
return None
return factor
[docs]
def topological_generations(g):
r"""Return the topological generation of every vertex of a directed
acyclic graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed acyclic graph.
Returns
-------
gen : :class:`~graph_tool.VertexPropertyMap`
The generation of every vertex: zero for the vertices without
in-edges, and otherwise the length of the longest path from one of
them.
See Also
--------
topological_sort: A topological ordering
dag_longest_path: Longest path of a directed acyclic graph
antichains: All antichains of a directed acyclic graph
Notes
-----
The generations partition the vertices into layers such that every edge
goes from a layer to a later one, as used e.g. by
:func:`~graph_tool.draw.layered_layout`. They are computed with
`Kahn's algorithm <https://en.wikipedia.org/wiki/Topological_sorting>`_
[kahn-topological-1962]_ in time :math:`O(V + E)`. A
``ValueError`` is raised if the graph has a cycle.
Examples
--------
>>> g = gt.Graph([(0, 1), (0, 2), (1, 3), (2, 3), (3, 4), (0, 4)])
>>> print(gt.topological_generations(g).a)
[0 1 1 2 3]
References
----------
.. [kahn-topological-1962] Arthur B. Kahn, "Topological sorting of large
networks", Communications of the ACM 5, 558-562 (1962),
:DOI:`10.1145/368996.369025`
"""
if not g.is_directed():
raise ValueError("The graph must be directed.")
order, gen = libgraph_tool_structure.topological_generations(g)
p = g.new_vp("int64_t")
p.a = numpy.asarray(gen, dtype="int64")[:len(p.a)]
return p
[docs]
def dag_longest_path(g, weight=None):
r"""Return a longest path of a directed acyclic graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed acyclic graph.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge lengths. If not given, every edge has length one.
Returns
-------
path : :class:`numpy.ndarray`
The vertices of the path.
length : ``float``
Its total length.
See Also
--------
topological_sort: A topological ordering
topological_generations: Topological generation of every vertex
shortest_path: Shortest path
Notes
-----
The path returned is a directed path :math:`P` that maximizes its length
:math:`\sum_{e\in P} w_e`, where :math:`w_e` is the length of edge
:math:`e` (one, if no lengths are given), among all directed paths of the
graph, including those of a single vertex, which have length zero. The
`longest distances <https://en.wikipedia.org/wiki/Longest_path_problem>`_
are computed by dynamic programming in topological
order, in time :math:`O(V + E)`. Paths of negative length are never
extended (the longest path to a vertex is then the vertex itself), so that
the path can start anywhere. The problem is NP-hard for graphs with
cycles, for which a ``ValueError`` is raised.
Examples
--------
>>> g = gt.Graph([(0, 1), (0, 2), (1, 3), (2, 3), (3, 4), (0, 4)])
>>> print(gt.dag_longest_path(g))
(array([0, 1, 3, 4], dtype=uint64), 3.0)
"""
if not g.is_directed():
raise ValueError("The graph must be directed.")
path, l = libgraph_tool_structure.dag_longest_path(g, weight)
return numpy.asarray(path), l
[docs]
def all_topological_sorts(g):
r"""Return an iterator over all topological orderings of a directed
acyclic graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed acyclic graph.
Returns
-------
orders : iterator over :class:`numpy.ndarray`
Every ordering of the vertices in which all edges point forward.
See Also
--------
topological_sort: A single topological ordering
antichains: All antichains of a directed acyclic graph
Notes
-----
The
`orderings <https://en.wikipedia.org/wiki/Topological_sorting>`_
are generated by backtracking over the vertices without
remaining in-edges [knuth-structured-1974]_, in time :math:`O(V)` per
ordering. Their number can grow factorially with the number of vertices.
A ``ValueError`` is raised if the graph has a cycle.
Examples
--------
>>> g = gt.Graph([(0, 1), (0, 2), (1, 3), (2, 3)])
>>> for o in gt.all_topological_sorts(g):
... print(o)
[0 1 2 3]
[0 2 1 3]
References
----------
.. [knuth-structured-1974] Donald E. Knuth and Jayme L. Szwarcfiter, "A
structured program to generate all topological sorting arrangements",
Information Processing Letters 2, 153-157 (1974),
:DOI:`10.1016/0020-0190(74)90001-5`
"""
if not g.is_directed():
raise ValueError("The graph must be directed.")
for o in libgraph_tool_structure.all_topological_sorts(g):
yield numpy.asarray(o)
[docs]
def antichains(g):
r"""Return an iterator over all antichains of a directed acyclic graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed acyclic graph.
Returns
-------
antichains : iterator over :class:`numpy.ndarray`
Every set of vertices no two of which are joined by a directed path,
including the empty set.
See Also
--------
all_topological_sorts: All topological orderings
topological_generations: Topological generation of every vertex
transitive_closure: Transitive closure of a graph
Notes
-----
Comparability is given by the transitive closure, stored as bitsets in
memory :math:`O(V^2)`, and the
`antichains <https://en.wikipedia.org/wiki/Antichain>`_
are generated by extending each
one with later vertices incomparable to all of its own, in topological
order [freese-free-1995]_. Their number can grow exponentially.
Examples
--------
>>> g = gt.Graph([(0, 1), (0, 2), (1, 3), (2, 3)])
>>> print(sorted(sorted(a.tolist()) for a in gt.antichains(g)))
[[], [0], [1], [1, 2], [2], [3]]
References
----------
.. [freese-free-1995] Ralph Freese, Jaroslav Ježek and J. B. Nation, "Free
Lattices", American Mathematical Society (1995),
:DOI:`10.1090/surv/042`
"""
if not g.is_directed():
raise ValueError("The graph must be directed.")
for a in libgraph_tool_structure.antichains(g):
yield numpy.asarray(a, dtype="int64")
[docs]
def is_aperiodic(g):
r"""Check whether a strongly connected directed graph is aperiodic.
Parameters
----------
g : :class:`~graph_tool.Graph`
Strongly connected directed graph.
Returns
-------
aperiodic : ``bool``
``True`` if the greatest common divisor of the cycle lengths is one.
See Also
--------
label_components: Strongly connected components
is_DAG: Test for directed acyclic graphs
Notes
-----
A random walk on a strongly connected graph converges to its stationary
distribution if and only if the graph is
`aperiodic <https://en.wikipedia.org/wiki/Aperiodic_graph>`_.
With the
breadth-first levels :math:`l` from any vertex, the greatest common
divisor of the cycle lengths equals that of :math:`l(u) + 1 - l(v)` over
the edges :math:`(u, v)` [jarvis-graph-1996]_, which is computed in time
:math:`O(V + E)`. A ``ValueError`` is raised if the graph is not strongly
connected.
Examples
--------
>>> print(gt.is_aperiodic(gt.circular_graph(4, directed=True)))
False
>>> g = gt.circular_graph(4, directed=True)
>>> g.add_edge(0, 2)
<...>
>>> print(gt.is_aperiodic(g))
True
References
----------
.. [jarvis-graph-1996] J. P. Jarvis and D. R. Shier, "Graph-theoretic
analysis of finite Markov chains", in Applied Mathematical Modeling: A
Multidisciplinary Approach, CRC Press (1996).
"""
if not g.is_directed():
raise ValueError("The graph must be directed.")
if len(label_components(g)[1]) != 1:
raise ValueError("The graph is not strongly connected.")
return libgraph_tool_structure.is_aperiodic(g)
[docs]
def dominance_frontiers(g, root):
r"""Return the dominance frontier of every vertex of a directed graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed graph.
root : :class:`~graph_tool.Vertex` or ``int``
Entry vertex.
Returns
-------
df : :class:`~graph_tool.VertexPropertyMap`
Vector-valued vertex property map with the frontier of every vertex.
See Also
--------
dominator_tree: Immediate dominator of every vertex
Notes
-----
A vertex :math:`u`
`dominates <https://en.wikipedia.org/wiki/Dominator_(graph_theory)>`_
:math:`v` if every path from the root to
:math:`v` passes through :math:`u` (every vertex dominates itself), and
strictly dominates it if, in addition, :math:`u \ne v`. The dominance
frontier of :math:`u` is the set of vertices :math:`v` such that
:math:`u` dominates a predecessor (in-neighbor) of :math:`v` but does
not strictly dominate :math:`v` (see
:func:`~graph_tool.structure.dominator_tree`); it gives the placement of
:math:`\phi`-functions in static single-assignment form
[cytron-efficiently-1991]_. It is computed from the dominator tree by
walking up from the predecessors of every vertex with two or more of
them [cooper-simple-2001]_, in time :math:`O(E + \sum |DF|)`.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (1, 3), (2, 4), (3, 4), (4, 5)])
>>> df = gt.dominance_frontiers(g, 0)
>>> print([list(df[v]) for v in g.vertices()])
[[], [], [4], [4], [], []]
References
----------
.. [cytron-efficiently-1991] Ron Cytron, Jeanne Ferrante, Barry K.
Rosen, Mark N. Wegman and F. Kenneth Zadeck, "Efficiently computing
static single assignment form and the control dependence graph", ACM
Transactions on Programming Languages and Systems 13, 451-490 (1991),
:DOI:`10.1145/115372.115320`
.. [cooper-simple-2001] Keith D. Cooper, Timothy J. Harvey and Ken
Kennedy, "A simple, fast dominance algorithm", Software Practice and
Experience 4, 1-10 (2001).
"""
dom = dominator_tree(g, root)
df = g.new_vp("vector<int64_t>")
libgraph_tool_structure.dominance_frontiers(g,
dom._get_any(), int(root),
df._get_any())
return df
[docs]
def lowest_common_ancestors(g, pairs):
r"""Return the lowest common ancestors of pairs of vertices of a rooted
tree or of a directed acyclic graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed acyclic graph, with the edges pointing away from the roots.
pairs : iterable of pairs of ``int``
The pairs of vertices.
Returns
-------
lca : :class:`numpy.ndarray`
The lowest common ancestor of every pair, or ``-1`` if the two
vertices have none.
See Also
--------
dominator_tree: Immediate dominator of every vertex
topological_sort: Topological ordering of a directed acyclic graph
Notes
-----
Every vertex is its own
`ancestor <https://en.wikipedia.org/wiki/Lowest_common_ancestor>`_.
If every vertex has at most one
in-edge (a rooted forest), the ancestors are found by binary lifting,
in time :math:`O(V\log V)` for the preprocessing and :math:`O(\log V)` per
pair [bender-lca-2000]_. Otherwise, the common ancestors of each pair are
found by backward searches, in time :math:`O(V + E)` per pair (with the
pairs processed in parallel), and the one that comes last in
topological order is returned, which has no other
common ancestor as a descendant (there may be several such vertices).
Examples
--------
>>> g = gt.Graph([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)])
>>> print(gt.lowest_common_ancestors(g, [(3, 4), (3, 5), (4, 1)]))
[1 0 1]
References
----------
.. [bender-lca-2000] Michael A. Bender and Martín Farach-Colton, "The LCA
problem revisited", LATIN 2000: Theoretical Informatics, Lecture
Notes in Computer Science 1776, 88-94 (2000),
:DOI:`10.1007/10719839_9`
"""
if not g.is_directed():
raise ValueError("The graph must be directed.")
pairs = numpy.ascontiguousarray(numpy.asarray(pairs, dtype="int64")
.reshape(-1, 2))
tree = (g.get_in_degrees(g.get_vertices()) <= 1).all()
return libgraph_tool_structure.lca(g, pairs, bool(tree))
[docs]
def prufer_sequence(g):
r"""Return the Prüfer sequence of a tree.
Parameters
----------
g : :class:`~graph_tool.Graph`
Tree with at least two vertices. Edge directions are ignored.
Returns
-------
seq : :class:`numpy.ndarray`
The Prüfer sequence, of length :math:`V - 2`, in terms of the
positions of the vertices in :meth:`~graph_tool.Graph.get_vertices`.
See Also
--------
graph_tool.generation.prufer_tree: Inverse operation
graph_tool.generation.generate_random_tree: Random tree
Notes
-----
The
`Prüfer sequence <https://en.wikipedia.org/wiki/Pr%C3%BCfer_sequence>`_
[prufer-neuer-1918]_ is obtained by removing the leaf
with the smallest index and recording its neighbor, :math:`V - 2` times.
It is a bijection between the labeled trees with :math:`V` vertices and
the sequences of length :math:`V - 2` over :math:`V` symbols, and is
inverted by :func:`~graph_tool.generation.prufer_tree`. The time is
:math:`O(V)`.
Examples
--------
>>> g = gt.Graph([(0, 3), (1, 3), (2, 3), (3, 4), (4, 5)], directed=False)
>>> print(gt.prufer_sequence(g))
[3 3 3 4]
References
----------
.. [prufer-neuer-1918] Heinz Prüfer, "Neuer Beweis eines Satzes über
Permutationen", Archiv der Mathematik und Physik 27, 142-144 (1918).
"""
vs = g.get_vertices()
if len(vs) < 2 or g.num_edges() != len(vs) - 1 or \
len(label_components(GraphView(g, directed=False))[1]) != 1:
raise ValueError("The graph must be a tree with at least two " +
"vertices.")
idx = numpy.full(g.num_vertices(True), -1, dtype="int64")
idx[vs] = numpy.arange(len(vs))
es = numpy.ascontiguousarray(idx[g.get_edges()[:, :2]], dtype="int64")
return numpy.asarray(libgraph_tool_structure.prufer_sequence(len(vs), es),
dtype="int64")
[docs]
def unfold_tree(g, roots):
r"""Unfold a graph into a forest by breadth-first search.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
roots : iterable of ``int`` or :class:`~graph_tool.Vertex`
Roots of the searches.
Returns
-------
t : :class:`~graph_tool.Graph`
The forest, with the directedness of ``g``.
orig : :class:`~graph_tool.VertexPropertyMap`
The vertex of ``g`` corresponding to every vertex of ``t``.
See Also
--------
dag_to_branching: Branching of the paths of a directed acyclic graph
graph_tool.search.bfs_search: Breadth-first search
Notes
-----
A breadth-first search is run from every root (not reached before); each
edge is traversed once (along the out-edges, for directed graphs), and
if it leads to a vertex already reached, a new copy of that vertex is
created as its endpoint, so that every edge reachable from the roots
appears once in the forest. The vertices of ``g`` keep their indices,
and the copies come after them. The time is :math:`O(V + E)`.
Examples
--------
>>> g = gt.circular_graph(4)
>>> t, orig = gt.unfold_tree(g, [0])
>>> print(t.num_vertices(), t.num_edges(), orig.a)
5 4 [0 1 2 3 2]
"""
roots = numpy.asarray([int(r) for r in roots], dtype="int64")
orig, es = libgraph_tool_structure.unfold_tree(g, roots)
t = Graph(directed=g.is_directed())
t.add_vertex(len(orig))
t.add_edge_list(numpy.asarray(es, dtype="int64").reshape(-1, 2),
parallel=False)
o = t.new_vp("int64_t")
o.a = orig
return t, o
[docs]
def junction_tree(g):
r"""Return a junction tree of a graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Undirected graph, or directed acyclic graph (a Bayesian network).
Returns
-------
t : :class:`~graph_tool.Graph`
Undirected tree (or forest) with one vertex per maximal clique of the
triangulated graph.
cliques : :class:`~graph_tool.VertexPropertyMap`
Vector-valued property map with the vertices of ``g`` in every
clique.
separators : :class:`~graph_tool.EdgePropertyMap`
Vector-valued property map with the intersection of the cliques at
the endpoints of every edge.
See Also
--------
treewidth: Upper bound on the treewidth
chordal_completion: Minimal chordal completion
chordal_cliques: Maximal cliques of a chordal graph
graph_tool.generation.moral_graph: Moral graph of a directed acyclic graph
Notes
-----
A
`junction tree <https://en.wikipedia.org/wiki/Junction_tree_algorithm>`_
[lauritzen-local-1988]_ is a tree of the maximal cliques
of a chordal graph such that the cliques containing any given vertex
form a connected subtree. It is obtained as follows: 1. a directed graph
is moralized (see :func:`~graph_tool.generation.moral_graph`); 2. the
graph is made chordal with a minimal completion (see
:func:`~graph_tool.structure.chordal_completion`); 3. its maximal cliques
are found (see :func:`~graph_tool.structure.chordal_cliques`); and 4. a
maximum spanning tree of the cliques is taken, with the size of their
intersections as weights [jensen-optimal-1994]_. The width of the
decomposition is the size of the largest clique minus one.
Examples
--------
>>> g = gt.Graph([(0, 2), (1, 2), (2, 3), (3, 4), (2, 4)])
>>> t, cliques, seps = gt.junction_tree(g)
>>> print(sorted(sorted(cliques[v]) for v in t.vertices()))
[[0, 1, 2], [2, 3, 4]]
For a :math:`3\times 4` lattice, the junction tree is a path of cliques
of the completed graph, which we draw with the vertices of every clique
as labels:
>>> g = gt.lattice([3, 4])
>>> t, cliques, seps = gt.junction_tree(g)
>>> label = t.new_vp("string", vals=[",".join(map(str, sorted(cliques[v])))
... for v in t.vertices()])
>>> tpos = t.new_vp("vector<double>",
... vals=[(i, 0) for i in range(t.num_vertices())])
>>> gt.graph_draw(t, tpos, vertex_text=label, vertex_fill_color="#cccccc",
... edge_color="#999999", vertex_size=75,
... vertex_font_size=13,
... vertex_shape="square", output_size=(1000, 120),
... output="junction_tree-lattice.pdf")
<...>
.. testcleanup::
conv_png("junction_tree-lattice.pdf")
.. figure:: junction_tree-lattice.png
:align: center
:width: 90%
Junction tree of a :math:`3\times 4` lattice, with the vertices of
every clique given in the labels.
References
----------
.. [jensen-optimal-1994] Finn V. Jensen and Frank Jensen, "Optimal
junction trees", Proceedings of the Tenth Conference on Uncertainty in
Artificial Intelligence, 360-366 (1994), :arxiv:`1302.6823`
.. [lauritzen-local-1988] Steffen L. Lauritzen and David J. Spiegelhalter,
"Local computations with probabilities on graphical structures and
their application to expert systems", Journal of the Royal Statistical
Society B 50, 157-194 (1988),
:DOI:`10.1111/j.2517-6161.1988.tb01721.x`
"""
if g.is_directed():
if not is_DAG(g):
raise ValueError("A directed graph must be acyclic.")
h = moral_graph(g)
else:
h = Graph(g, prune=True)
remove_parallel_edges(h)
remove_self_loops(h)
h.add_edge_list(chordal_completion(h), parallel=False)
vs = numpy.asarray(g.get_vertices(), dtype="int64")
t = Graph(directed=False)
cliques = t.new_vp("vector<int64_t>")
seps = t.new_ep("vector<int64_t>")
libgraph_tool_structure.junction_tree(h, vs, t,
cliques._get_any(), seps._get_any())
return t, cliques, seps
[docs]
def tree_broadcast_center(g):
r"""Return the broadcast time and the broadcast center of a tree.
Parameters
----------
g : :class:`~graph_tool.Graph`
Undirected tree.
Returns
-------
time : ``int``
The broadcast time of the tree: the minimum, over the vertices, of
the number of rounds needed to inform all vertices from it, when in
each round every informed vertex can inform one neighbor.
center : :class:`numpy.ndarray`
The vertices from which this time is achieved.
See Also
--------
tree_broadcast_time: Broadcast time from one vertex
center: Vertices of minimum eccentricity
Notes
-----
The algorithm of Slater, Cockayne, and Hedetniemi [slater-information-1981]_
removes the leaves repeatedly, assigning to every removed vertex the
time needed to inform its subtree, which is obtained by informing its
children in decreasing order of their times. The time is
:math:`O(V\log V)`.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (1, 3), (3, 4), (3, 5), (5, 6)],
... directed=False)
>>> print(gt.tree_broadcast_center(g))
(3, array([1, 3]))
References
----------
.. [slater-information-1981] Peter J. Slater, Ernest J. Cockayne and
Stephen T. Hedetniemi, "Information dissemination in trees", SIAM
Journal on Computing 10, 692-701 (1981), :DOI:`10.1137/0210052`
"""
vs = g.get_vertices()
n = len(vs)
if g.is_directed() or g.num_edges() != n - 1 or \
(n > 0 and len(label_components(g)[1]) != 1):
raise ValueError("The graph must be an undirected tree.")
if n < 3:
return n - 1, vs
b, c = libgraph_tool_structure.tree_broadcast_center(g)
return b, numpy.asarray(c, dtype="int64")
[docs]
def tree_broadcast_time(g, v=None):
r"""Return the broadcast time of a tree, or from one of its vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Undirected tree.
v : :class:`~graph_tool.Vertex` or ``int`` (optional, default: ``None``)
Source vertex. If not given, the largest time over all sources is
returned.
Returns
-------
time : ``int``
The number of rounds needed to inform all vertices from ``v`` (or,
if ``v`` is ``None``, the maximum over all vertices), when in each
round every informed vertex can inform one neighbor.
See Also
--------
tree_broadcast_center: Broadcast time and broadcast center
eccentricity: Eccentricity of every vertex
Notes
-----
The time from a vertex is the broadcast time of the tree (see
:func:`~graph_tool.structure.tree_broadcast_center`) plus its distance to
the nearest vertex of the broadcast center [slater-information-1981]_,
which is the minimum over the broadcast schemes. The time is
:math:`O(V\log V)`.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (1, 3), (3, 4), (3, 5), (5, 6)],
... directed=False)
>>> print(gt.tree_broadcast_time(g), gt.tree_broadcast_time(g, 6))
5 5
References
----------
.. [slater-information-1981] Peter J. Slater, Ernest J. Cockayne and
Stephen T. Hedetniemi, "Information dissemination in trees", SIAM
Journal on Computing 10, 692-701 (1981), :DOI:`10.1137/0210052`
"""
b, center = tree_broadcast_center(g)
if g.num_vertices() < 3:
return int(b)
return libgraph_tool_structure.tree_broadcast_time(g,
-1 if v is None
else int(v))
[docs]
def flow_hierarchy(g, weight=None):
r"""Return the flow hierarchy of a directed graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed graph.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights.
Returns
-------
h : ``float``
The fraction of edges (or of the total weight) that are not part of a
cycle.
See Also
--------
edge_reciprocity: Fraction of reciprocated edges
label_components: Strongly connected components
graph_tool.centrality.trophic_incoherence: Trophic incoherence parameter
Notes
-----
The flow hierarchy [luo-detecting-2011]_ is
.. math::
h = 1 - \frac{\sum_{e\in E_c}w_e}{\sum_{e\in E}w_e},
where :math:`E_c` is the set of edges that belong to a directed cycle,
i.e. whose endpoints lie in the same strongly connected component
(self-loops included), and :math:`w_e = 1` if no weights are given. It
is one for directed acyclic graphs (and for graphs without edges) and
zero for strongly connected ones. The strongly connected components are
found in time :math:`O(V + E)`.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (2, 0), (2, 3), (3, 4)])
>>> print(gt.flow_hierarchy(g))
0.4
References
----------
.. [luo-detecting-2011] Jianxi Luo and Christopher L. Magee, "Detecting
evolving patterns of self-organizing networks by flow hierarchy
measurement", Complexity 16, 53-61 (2011), :DOI:`10.1002/cplx.20368`
"""
if not g.is_directed():
raise ValueError("The graph must be directed.")
if weight is not None:
_check_prop_scalar(weight, "weight")
comp = label_components(g)[0]
return libgraph_tool_structure.flow_hierarchy(g,
comp._get_any(),
weight._get_any() if weight
is not None else None)
def _index_sums(g, weights):
d, d2, schultz, gutman, disc = \
libgraph_tool_structure.distance_indices(g, weights)
return d, d2, schultz, gutman, disc
[docs]
@_parallel
def hyper_wiener_index(g, weights=None):
r"""Return the hyper-Wiener index of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights (lengths).
Returns
-------
WW : ``float``
The hyper-Wiener index :math:`\frac{1}{2}\sum_{u<v}(d_{uv} + d_{uv}^2)`
[randic-novel-1993]_, or :math:`\infty` if the graph is not
connected.
See Also
--------
wiener_index: Sum of the distances between all pairs
schultz_index: Degree-weighted variant of the Wiener index
gutman_index: Degree-product-weighted variant of the Wiener index
Notes
-----
The hyper-Wiener index [randic-novel-1993]_ is
.. math::
WW = \frac{1}{2}\sum_{u<v}\left[d(u, v) + d(u, v)^2\right],
where the sum runs over the unordered pairs of distinct vertices, and
:math:`d(u, v)` is the length of a shortest path between :math:`u` and
:math:`v`, ignoring the edge directions (the number of its edges, or the
sum of their weights). If the graph is not connected, :math:`WW =
\infty`. This is the usual definition, with a sum over unordered pairs,
for which a path of :math:`n` vertices has :math:`WW = \binom{n+2}{4}`
(see also the
`Wiener index <https://en.wikipedia.org/wiki/Wiener_index>`_,
computed by :func:`~graph_tool.structure.wiener_index`).
The distances are computed by a breadth-first search (or Dijkstra's
algorithm, with weights) from every vertex, in time :math:`O(VE)` (or
:math:`O(V(E + V)\log V)`), in parallel.
@parallel@
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.hyper_wiener_index(g))
2545.0
References
----------
.. [randic-novel-1993] Milan Randić, "Novel molecular descriptor for
structure-property studies", Chemical Physics Letters 211, 478-483
(1993), :DOI:`10.1016/0009-2614(93)87094-J`
"""
d, d2, schultz, gutman, disc = _index_sums(g, weights)
if disc > 0:
return numpy.inf
return (d + d2) / 2
[docs]
@_parallel
def schultz_index(g, weights=None):
r"""Return the Schultz index of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights (lengths).
Returns
-------
S : ``float``
The Schultz index :math:`\sum_{u<v}(k_u + k_v) d_{uv}`
[schultz-topological-1989]_, where :math:`k_u` is the degree, or
:math:`\infty` if the graph is not connected.
See Also
--------
gutman_index: Variant with products of degrees
wiener_index: Sum of the distances between all pairs
hyper_wiener_index: Wiener index that also includes squared distances
Notes
-----
The Schultz index [schultz-topological-1989]_ is
.. math::
S = \sum_{u<v}(k_u + k_v)\,d(u, v),
where the sum runs over the unordered pairs of distinct vertices,
:math:`k_u` is the total degree of :math:`u` (the sum of its in- and
out-degrees, for directed graphs), and :math:`d(u, v)` is the length of a
shortest path between :math:`u` and :math:`v`, ignoring the edge
directions (the number of its edges, or the sum of their weights). In
the degrees, parallel edges are counted with their multiplicity and a
self-loop contributes two, as in the
`handshake lemma <https://en.wikipedia.org/wiki/Handshaking_lemma>`_;
neither affects the distances. If the graph is not connected,
:math:`S = \infty`. The distances are computed
as in :func:`~graph_tool.structure.hyper_wiener_index`.
@parallel@
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.schultz_index(g))
11221.0
References
----------
.. [schultz-topological-1989] Harry P. Schultz, "Topological organic
chemistry. 1. Graph theory and topological indices of alkanes",
Journal of Chemical Information and Computer Sciences 29, 227-228
(1989), :DOI:`10.1021/ci00063a012`
"""
d, d2, schultz, gutman, disc = _index_sums(g, weights)
if disc > 0:
return numpy.inf
return schultz
[docs]
@_parallel
def gutman_index(g, weights=None):
r"""Return the Gutman index of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
weights : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights (lengths).
Returns
-------
G : ``float``
The Gutman index :math:`\sum_{u<v}k_uk_v d_{uv}`
[gutman-selected-1994]_, where :math:`k_u` is the degree, or
:math:`\infty` if the graph is not connected.
See Also
--------
schultz_index: Variant with sums of degrees
wiener_index: Sum of the distances between all pairs
hyper_wiener_index: Wiener index that also includes squared distances
Notes
-----
The Gutman index [gutman-selected-1994]_ is
.. math::
\mathrm{Gut} = \sum_{u<v}k_uk_v\,d(u, v),
where the sum runs over the unordered pairs of distinct vertices,
:math:`k_u` is the total degree of :math:`u` (the sum of its in- and
out-degrees, for directed graphs), and :math:`d(u, v)` is the length of a
shortest path between :math:`u` and :math:`v`, ignoring the edge
directions (the number of its edges, or the sum of their weights). In
the degrees, parallel edges are counted with their multiplicity and a
self-loop contributes two, as in the
`handshake lemma <https://en.wikipedia.org/wiki/Handshaking_lemma>`_;
neither affects the distances. If the graph is not connected,
:math:`\mathrm{Gut} = \infty`. The distances are
computed as in :func:`~graph_tool.structure.hyper_wiener_index`.
@parallel@
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.gutman_index(g))
22959.0
References
----------
.. [gutman-selected-1994] Ivan Gutman, "Selected properties of the
Schultz molecular topological index", Journal of Chemical Information
and Computer Sciences 34, 1087-1089 (1994), :DOI:`10.1021/ci00021a009`
"""
d, d2, schultz, gutman, disc = _index_sums(g, weights)
if disc > 0:
return numpy.inf
return gutman
[docs]
def s_metric(g):
r"""Return the s-metric of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
Returns
-------
s : ``float``
The sum of :math:`k_uk_v` over the edges :math:`(u, v)`, where
:math:`k` is the total degree.
See Also
--------
graph_tool.correlations.assortativity: Degree assortativity coefficient
graph_tool.correlations.scalar_assortativity: Scalar assortativity
Notes
-----
The s-metric [li-towards-2005]_ is defined as
.. math::
s(G) = \sum_{(u,v)\in E} k_uk_v,
where :math:`k_u` is the total degree of vertex :math:`u` (the sum of
its in- and out-degrees, for directed graphs), with parallel edges
counted with their multiplicity and a self-loop contributing two, as in
the `handshake lemma <https://en.wikipedia.org/wiki/Handshaking_lemma>`_.
Every edge, including each parallel edge and self-loop, appears once in
the sum, so that a self-loop at :math:`u` contributes :math:`k_u^2`. It
is large for graphs whose high-degree vertices are connected to each
other, and is related to the
`degree assortativity <https://en.wikipedia.org/wiki/Assortativity>`_
(see :func:`~graph_tool.correlations.assortativity`). The time is
:math:`O(V + E)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.s_metric(g))
3640.0
References
----------
.. [li-towards-2005] Lun Li, David Alderson, John C. Doyle and Walter
Willinger, "Towards a theory of scale-free graphs: definition,
properties, and implications", Internet Mathematics 2, 431-523
(2005), :DOI:`10.1080/15427951.2005.10129111`
"""
return libgraph_tool_structure.s_metric(g)
[docs]
def intersection_array(g):
r"""Return the intersection array of a distance-regular graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
b : :class:`numpy.ndarray` or ``None``
The numbers :math:`b_0, \dots, b_{d-1}`, or ``None`` if the graph is
not distance-regular.
c : :class:`numpy.ndarray`
The numbers :math:`c_1, \dots, c_d`. Only returned if the graph is
distance-regular.
See Also
--------
is_distance_regular: Test for distance-regular graphs
global_parameters: Global parameters from the intersection array
is_strongly_regular: Test for strongly regular graphs
Notes
-----
A connected graph of diameter :math:`d` is
`distance-regular <https://en.wikipedia.org/wiki/Distance-regular_graph>`_
[brouwer-distance-1989]_ if, for every pair of vertices :math:`u, v` at
distance :math:`i`, the number :math:`c_i` of neighbors of :math:`v` at
distance :math:`i-1` from :math:`u`, and the number :math:`b_i` of those
at distance :math:`i+1`, depend only on :math:`i`. They are counted after
a breadth-first search from every vertex, in parallel, in time
:math:`O(VE)`.
Examples
--------
>>> g = gt.lattice([2, 2, 2])
>>> print(gt.intersection_array(g))
(array([3, 2, 1]), array([1, 2, 3]))
>>> print(gt.intersection_array(gt.lattice([3, 3])))
None
References
----------
.. [brouwer-distance-1989] Andries E. Brouwer, Arjeh M. Cohen and Arnold
Neumaier, "Distance-Regular Graphs", Springer (1989),
:DOI:`10.1007/978-3-642-74341-2`
"""
r = libgraph_tool_structure.intersection_array(g)
if r is None:
return None
return numpy.asarray(r[0]), numpy.asarray(r[1])
[docs]
def is_distance_regular(g):
r"""Check whether a graph is distance-regular.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
regular : ``bool``
``True`` if the graph is distance-regular (see
:func:`~graph_tool.structure.intersection_array`).
See Also
--------
intersection_array: Intersection array of a distance-regular graph
is_strongly_regular: Test for strongly regular graphs
Notes
-----
A connected graph of diameter :math:`d` is
`distance-regular <https://en.wikipedia.org/wiki/Distance-regular_graph>`_
[brouwer-distance-1989]_ if, for every pair of vertices :math:`u, v` at
distance :math:`i`, the number :math:`c_i` of neighbors of :math:`v` at
distance :math:`i-1` from :math:`u`, and the number :math:`b_i` of those
at distance :math:`i+1`, depend only on :math:`i`, for :math:`0 \le i
\le d`. Disconnected graphs are not considered distance-regular. The
numbers are counted after a breadth-first search from every vertex, in
time :math:`O(VE)`.
Examples
--------
>>> print(gt.is_distance_regular(gt.lattice([2, 2, 2])))
True
References
----------
.. [brouwer-distance-1989] Andries E. Brouwer, Arjeh M. Cohen and Arnold
Neumaier, "Distance-Regular Graphs", Springer (1989),
:DOI:`10.1007/978-3-642-74341-2`
"""
return intersection_array(g) is not None
[docs]
def global_parameters(b, c):
r"""Return the global parameters of a distance-regular graph from its
intersection array.
Parameters
----------
b : iterable of ``int``
The numbers :math:`b_0, \dots, b_{d-1}`.
c : iterable of ``int``
The numbers :math:`c_1, \dots, c_d`.
Returns
-------
params : ``list`` of ``tuple``
The triples :math:`(c_i, a_i, b_i)` for :math:`i = 0, \dots, d`, where
:math:`a_i = b_0 - b_i - c_i` is the number of neighbors at the same
distance, with :math:`c_0 = 0` and :math:`b_d = 0`
[brouwer-distance-1989]_.
See Also
--------
intersection_array: Intersection array of a distance-regular graph
is_distance_regular: Test for distance-regular graphs
Notes
-----
In a
`distance-regular graph <https://en.wikipedia.org/wiki/Distance-regular_graph>`_
of diameter :math:`d`
[brouwer-distance-1989]_, for every pair of vertices :math:`u, v` at
distance :math:`i`, the vertex :math:`v` has :math:`c_i` neighbors at
distance :math:`i-1` from :math:`u`, :math:`a_i` at distance :math:`i`,
and :math:`b_i` at distance :math:`i+1`, independently of the pair. Since
the graph is regular with degree :math:`k = b_0`, these numbers satisfy
:math:`a_i + b_i + c_i = k`, from which :math:`a_i` is computed. The
arrays given are not checked for feasibility.
Examples
--------
>>> b, c = gt.intersection_array(gt.lattice([2, 2, 2]))
>>> print(gt.global_parameters(b, c))
[(0, 0, 3), (1, 0, 2), (2, 0, 1), (3, 0, 0)]
References
----------
.. [brouwer-distance-1989] Andries E. Brouwer, Arjeh M. Cohen and Arnold
Neumaier, "Distance-Regular Graphs", Springer (1989),
:DOI:`10.1007/978-3-642-74341-2`
"""
b = [int(x) for x in b] + [0]
c = [0] + [int(x) for x in c]
k = b[0]
return [(ci, k - bi - ci, bi) for ci, bi in zip(c, b)]
[docs]
def is_strongly_regular(g):
r"""Check whether a graph is strongly regular.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
regular : ``bool``
``True`` if the graph is strongly regular.
See Also
--------
is_distance_regular: Test for distance-regular graphs
intersection_array: Intersection array of a distance-regular graph
Notes
-----
A regular graph is
`strongly regular <https://en.wikipedia.org/wiki/Strongly_regular_graph>`_
if every two adjacent vertices have the
same number :math:`\lambda` of common neighbors, and every two non-adjacent
ones the same number :math:`\mu`. A connected strongly regular graph is a
distance-regular graph of diameter two (see
:func:`~graph_tool.structure.intersection_array`) [brouwer-distance-1989]_;
disconnected graphs are not considered strongly regular.
Examples
--------
>>> g = gt.lattice([3, 3], periodic=True)
>>> print(gt.is_strongly_regular(g))
True
References
----------
.. [brouwer-distance-1989] Andries E. Brouwer, Arjeh M. Cohen and Arnold
Neumaier, "Distance-Regular Graphs", Springer (1989),
:DOI:`10.1007/978-3-642-74341-2`
"""
r = intersection_array(g)
return r is not None and len(r[0]) == 2
[docs]
def is_regular_expander(g, epsilon=0):
r"""Check whether a graph is a regular (near-)Ramanujan expander.
Parameters
----------
g : :class:`~graph_tool.Graph`
Undirected graph.
epsilon : ``float`` (optional, default: ``0``)
Tolerance above the Ramanujan bound.
Returns
-------
is_expander : ``bool``
``True`` if the graph is :math:`d`-regular and the second largest
absolute eigenvalue of its adjacency matrix is smaller than
:math:`2\sqrt{d-1} + \epsilon`.
See Also
--------
graph_tool.generation.generate_regular_expander: Random regular expanders
Notes
-----
A :math:`d`-regular graph whose nontrivial adjacency eigenvalues are bounded
in absolute value by :math:`2\sqrt{d-1}` is a `Ramanujan graph
<https://en.wikipedia.org/wiki/Ramanujan_graph>`_
[lubotzky-ramanujan-1988]_, the best possible spectral `expander
<https://en.wikipedia.org/wiki/Expander_graph>`_ in the limit of large
graphs. If the eigenvalues of the adjacency matrix are ordered as
:math:`|\lambda_1|\ge|\lambda_2|\ge\dots`, so that :math:`\lambda_1 = d`,
the test returns ``True`` if all vertices have the same total degree
:math:`d` and
.. math::
|\lambda_2| < 2\sqrt{d-1} + \epsilon.
Hence, disconnected graphs, for which :math:`\lambda_2 = d`, and
bipartite graphs, for which :math:`\lambda_2 = -d`, never pass the
test. The two eigenvalues of largest magnitude are computed with the
Lanczos method.
Examples
--------
>>> g = gt.complete_graph(10)
>>> print(gt.is_regular_expander(g))
True
References
----------
.. [lubotzky-ramanujan-1988] A. Lubotzky, R. Phillips and P. Sarnak,
"Ramanujan graphs", Combinatorica 8, 261-277 (1988),
:DOI:`10.1007/BF02126799`
"""
import scipy.sparse.linalg
from .. spectral import adjacency
if epsilon < 0:
raise ValueError("epsilon must be nonnegative.")
k = g.degree_property_map("total").fa
if len(k) == 0 or (k != k[0]).any():
return False
d = k[0]
A = adjacency(g).astype("double")
if A.shape[0] <= 2:
lams = numpy.linalg.eigvalsh(A.toarray())
lams = lams[numpy.argsort(-numpy.abs(lams))]
else:
lams = scipy.sparse.linalg.eigsh(A, k=2, which="LM",
return_eigenvectors=False)
lambda2 = numpy.abs(lams[:2]).min()
return bool(lambda2 < 2 * numpy.sqrt(d - 1) + epsilon)
[docs]
def find_negative_cycle(g, weight, source=None):
r"""Return a cycle of negative total weight, if there is one.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. For undirected graphs, every edge can be traversed
in both directions.
weight : :class:`~graph_tool.EdgePropertyMap`
Edge weights.
source : :class:`~graph_tool.Vertex` or ``int`` (optional, default: ``None``)
If given, only the cycles reachable from this vertex are considered.
Returns
-------
cycle : :class:`numpy.ndarray` or ``None``
The vertices of a negative cycle, in order, or ``None`` if there is
none.
See Also
--------
find_cycle: A single cycle of the graph
cycle_ratio: Maximum or minimum cycle ratio
graph_tool.search.bellman_ford_search: Shortest paths with negative weights
Notes
-----
The
`Bellman-Ford algorithm <https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm>`_
[bellman-routing-1958]_ is run from a virtual
source joined to every vertex (or from ``source``); if some distance is
still reduced after :math:`V` rounds, the predecessors lead from it to a
negative cycle. The time is :math:`O(VE)`. For undirected graphs, any
edge of negative weight forms a negative cycle with itself.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (2, 0), (2, 3)])
>>> w = g.new_ep("double", vals=[1, -3, 1, 1])
>>> print(gt.find_negative_cycle(g, w))
[0 1 2]
References
----------
.. [bellman-routing-1958] Richard Bellman, "On a routing problem",
Quarterly of Applied Mathematics 16, 87-90 (1958),
:DOI:`10.1090/qam/102435`
"""
c = libgraph_tool_structure.find_negative_cycle(g, weight,
-1 if source is None
else int(source))
return None if c is None else numpy.asarray(c)
[docs]
def is_semiconnected(g):
r"""Check whether a directed graph is semiconnected.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed graph.
Returns
-------
semiconnected : ``bool``
``True`` if, for every pair of vertices :math:`u, v`, there is a path
from :math:`u` to :math:`v` or from :math:`v` to :math:`u`.
See Also
--------
label_components: Strongly connected components
graph_tool.generation.condensation_graph: Graph of the strong components
Notes
-----
A directed graph is semiconnected if and only if its condensation (the
acyclic graph of its strongly connected components) has a
`Hamiltonian path <https://en.wikipedia.org/wiki/Hamiltonian_path>`_,
i.e. if consecutive components in topological order are joined by
an edge. The time is :math:`O(V + E)`.
Examples
--------
>>> print(gt.is_semiconnected(gt.Graph([(0, 1), (1, 2)])),
... gt.is_semiconnected(gt.Graph([(0, 1), (0, 2)])))
True False
"""
if not g.is_directed():
raise ValueError("The graph must be directed.")
comp = label_components(g)[0]
return libgraph_tool_structure.is_semiconnected(g,
comp._get_any())
[docs]
def eulerize(g, weight=None):
r"""Return the edges to duplicate to make a connected undirected graph
Eulerian.
Parameters
----------
g : :class:`~graph_tool.Graph`
Connected undirected graph.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge lengths. If given, the total length of the duplicated edges is
minimized; otherwise, their number.
Returns
-------
edges : :class:`numpy.ndarray`
Array of shape ``(k, 2)`` with the endpoints of the edges to add
(copies of existing edges), after which every vertex has even degree.
See Also
--------
eulerian_path: Eulerian path or circuit
Notes
-----
A connected graph has an Eulerian circuit if and only if every vertex
has even degree (see :func:`~graph_tool.structure.eulerian_path`). The
edges returned are copies of existing edges, chosen so that after their
addition every vertex has even degree, and so that their total length
:math:`\sum_e w_e` (their number, if no lengths are given) is minimal.
The vertices of odd degree are paired by a minimum-weight perfect
matching of their shortest-path distances, and the edges of the
shortest paths between the paired vertices are duplicated
[edmonds-matching-1973]_, which solves the
`route inspection (Chinese postman) problem <https://en.wikipedia.org/wiki/Chinese_postman_problem>`_.
The time is dominated by :math:`O(V_{\text{odd}})`
shortest-path searches, which run in parallel, and the matching. An
Eulerian circuit of the
result is given by :func:`~graph_tool.structure.eulerian_path`.
Examples
--------
>>> g = gt.lattice([3, 3])
>>> es = gt.eulerize(g)
>>> print(len(es))
4
>>> g.add_edge_list(es)
>>> print(gt.eulerian_path(g, circuit=True) is not None)
True
The duplicated edges can be shown in a drawing of the result:
>>> pos = g.new_vp("vector<double>",
... vals=[(i % 3, i // 3) for i in range(9)])
>>> ecolor = g.new_ep("string", vals=["#999999"] * 12 + ["#e41a1c"] * 4)
>>> gt.graph_draw(g, pos, vertex_fill_color="#cccccc", edge_color=ecolor,
... vertex_size=40, edge_pen_width=2,
... output="eulerize-lattice.pdf")
<...>
.. testcleanup::
conv_png("eulerize-lattice.pdf")
.. figure:: eulerize-lattice.png
:align: center
:width: 30%
A :math:`3\times 3` lattice made Eulerian, with the duplicated edges
shown in red.
References
----------
.. [edmonds-matching-1973] Jack Edmonds and Ellis L. Johnson, "Matching,
Euler tours and the Chinese postman", Mathematical Programming 5,
88-124 (1973), :DOI:`10.1007/BF01580113`
"""
if g.is_directed():
raise ValueError("The graph must be undirected.")
if len(label_components(g)[1]) > 1:
raise ValueError("The graph must be connected.")
if weight is not None:
_check_prop_scalar(weight, "weight")
dup = libgraph_tool_structure.eulerize(g,
weight._get_any() if weight
is not None else None)
return numpy.asarray(dup, dtype="int64").reshape(-1, 2)
[docs]
def find_bridges(g):
r"""Return the bridges of a graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
bridges : :class:`~graph_tool.EdgePropertyMap`
Boolean edge property map marking the bridges.
See Also
--------
local_bridges: Edges whose endpoints share no neighbors
chain_decomposition: Chain decomposition of a graph
label_biconnected_components: Biconnected components and articulation points
graph_tool.flow.label_bridge_components: Components without the bridges
Notes
-----
A
`bridge <https://en.wikipedia.org/wiki/Bridge_(graph_theory)>`_
is an edge whose removal disconnects its endpoints. Parallel
edges are never bridges. The bridges are found with Tarjan's low-link
values in a depth-first search [tarjan-note-1974]_, in time
:math:`O(V + E)`. Removing them leaves the 2-edge-connected components.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.find_bridges(g).a.sum())
1
The bridge can be highlighted in a drawing of the network:
>>> b = gt.find_bridges(g)
>>> ecolor = g.new_ep("string", vals=np.where(b.a, "#e41a1c", "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(b.a, 3, 1))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color="#cccccc",
... edge_color=ecolor, edge_pen_width=ewidth,
... output="find_bridges-karate.pdf")
<...>
.. testcleanup::
conv_png("find_bridges-karate.pdf")
.. figure:: find_bridges-karate.png
:align: center
:width: 50%
Bridge of Zachary's karate club network, shown in red.
References
----------
.. [tarjan-note-1974] Robert E. Tarjan, "A note on finding the bridges of
a graph", Information Processing Letters 2, 160-161 (1974),
:DOI:`10.1016/0020-0190(74)90003-9`
"""
b = g.new_ep("bool")
libgraph_tool_structure.find_bridges(g, b._get_any())
return b
[docs]
def local_bridges(g, with_span=True):
r"""Return the local bridges of a graph and their spans.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
with_span : ``bool`` (optional, default: ``True``)
If ``True``, the spans are computed.
Returns
-------
local : :class:`~graph_tool.EdgePropertyMap`
Boolean edge property map marking the local bridges.
span : :class:`~graph_tool.EdgePropertyMap`
The distance between the endpoints of every local bridge after its
removal (:math:`\infty` for bridges), and zero for the other edges.
Only returned if ``with_span == True``.
See Also
--------
find_bridges: Edges whose removal disconnects the graph
graph_tool.clustering.edge_clustering: Number of triangles of every edge
Notes
-----
A local bridge [granovetter-strength-1973]_ is an edge whose endpoints
have no common neighbor, so that it is not part of a triangle. The span
is found by a breadth-first search between the endpoints without the
edge, in parallel; the time is :math:`O(E\bar k)` for the detection and
up to :math:`O(V + E)` per local bridge for the spans.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> local, span = gt.local_bridges(g)
>>> print(local.a.sum(), span.a.max())
11 inf
The local bridges can be highlighted in a drawing of the network:
>>> ecolor = g.new_ep("string", vals=np.where(local.a, "#e41a1c",
... "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(local.a, 2.5, 1))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color="#cccccc",
... edge_color=ecolor, edge_pen_width=ewidth,
... output="local_bridges-karate.pdf")
<...>
.. testcleanup::
conv_png("local_bridges-karate.pdf")
.. figure:: local_bridges-karate.png
:align: center
:width: 50%
Local bridges of Zachary's karate club network, shown in red.
References
----------
.. [granovetter-strength-1973] Mark S. Granovetter, "The strength of weak
ties", American Journal of Sociology 78, 1360-1380 (1973),
:DOI:`10.1086/225469`
"""
span = g.new_ep("double", val=numpy.nan)
libgraph_tool_structure.local_bridges(g, span._get_any(),
bool(with_span))
local = g.new_ep("bool", vals=~numpy.isnan(span.a))
span.a[numpy.isnan(span.a)] = 0
if with_span:
return local, span
return local
[docs]
def chain_decomposition(g, root=None):
r"""Return the chain decomposition of a graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
root : :class:`~graph_tool.Vertex` or ``int`` (optional, default: ``None``)
Root of the first depth-first search. If not given, the first vertex
is used; the other components are visited afterwards.
Returns
-------
chains : ``list`` of :class:`numpy.ndarray`
The vertices of every chain, in order; a chain that is a cycle
repeats its first vertex at the end.
See Also
--------
find_bridges: Bridges of a graph
label_biconnected_components: Biconnected components and articulation points
Notes
-----
After a depth-first search, for every vertex in the order of discovery
and every back edge leaving it, a chain starts with the back edge and
follows the tree edges upwards until it reaches a vertex already on a
chain [schmidt-simple-2013]_. The chains cover all edges that are not
bridges; the graph is
`2-edge-connected <https://en.wikipedia.org/wiki/Edge_connectivity>`_
if they cover all edges, and
`2-vertex-connected <https://en.wikipedia.org/wiki/Vertex_connectivity>`_
if, in addition, only the first chain is a cycle. The
time is :math:`O(V + E)`.
Examples
--------
>>> g = gt.Graph([(0, 1), (1, 2), (2, 0), (2, 3), (3, 4), (4, 2)],
... directed=False)
>>> print(gt.chain_decomposition(g))
[array([0, 2, 1, 0], dtype=uint64), array([2, 4, 3, 2], dtype=uint64)]
The chains of a :math:`3\times 4` lattice can be shown in a drawing:
>>> g = gt.lattice([3, 4])
>>> chains = gt.chain_decomposition(g)
>>> palette = ["#e41a1c", "#377eb8", "#4daf4a", "#984ea3", "#ff7f00",
... "#a65628"]
>>> ecolor = g.new_ep("string")
>>> for c, color in zip(chains, palette):
... for u, v in zip(c[:-1], c[1:]):
... ecolor[g.edge(u, v)] = color
>>> pos = g.new_vp("vector<double>",
... vals=[(i % 3, i // 3) for i in range(12)])
>>> gt.graph_draw(g, pos, vertex_fill_color="#cccccc", edge_color=ecolor,
... vertex_size=30, edge_pen_width=3,
... output="chain_decomposition-lattice.pdf")
<...>
.. testcleanup::
conv_png("chain_decomposition-lattice.pdf")
.. figure:: chain_decomposition-lattice.png
:align: center
:width: 30%
Chain decomposition of a :math:`3\times 4` lattice, with the edges of
every chain shown in a different color (red for the first chain, a
cycle).
References
----------
.. [schmidt-simple-2013] Jens M. Schmidt, "A simple test on
2-vertex- and 2-edge-connectivity", Information Processing Letters
113, 241-244 (2013), :DOI:`10.1016/j.ipl.2013.01.016`
"""
return [numpy.asarray(c) for c in
libgraph_tool_structure.chain_decomposition(g,
-1 if root is None
else int(root))]
[docs]
def spanner(g, stretch, weight=None):
r"""Return a spanner of a graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions, self-loops, and parallel edges are
ignored.
stretch : ``float``
Largest allowed factor between the distances in the spanner and in
the graph (at least one).
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge lengths.
Returns
-------
spanner : :class:`~graph_tool.EdgePropertyMap`
Boolean edge property map marking the edges of the spanner.
See Also
--------
minimum_spanning_tree: Minimum spanning tree
shortest_distance: Shortest distances
Notes
-----
A :math:`t`-spanner is a subgraph in which the distance between any two
vertices is at most :math:`t` times that in the graph. With :math:`k =
\lfloor(t+1)/2\rfloor`, the randomized algorithm of Baswana and Sen
[baswana-simple-2007]_ grows :math:`k - 1` levels of clusters, whose
centers are sampled with probability :math:`V^{-1/k}`, and keeps the
lightest edge from every vertex to each neighboring cluster that it does
not join, which yields a :math:`(2k-1)`-spanner with
:math:`O(kV^{1+1/k})` edges in expectation, in expected time
:math:`O(kE)`.
Examples
--------
.. testsetup:: spanner
gt.seed_rng(42)
.. doctest:: spanner
>>> g = gt.collection.data["netscience"]
>>> s = gt.spanner(g, 3)
>>> print(g.num_edges(), s.a.sum())
2742 2687
References
----------
.. [baswana-simple-2007] Surender Baswana and Sandeep Sen, "A simple and
linear time randomized algorithm for computing sparse spanners in
weighted graphs", Random Structures & Algorithms 30, 532-563 (2007),
:DOI:`10.1002/rsa.20130`
"""
if stretch < 1:
raise ValueError("stretch must be at least one")
k = int((stretch + 1) // 2)
if weight is not None:
_check_prop_scalar(weight, "weight")
sp = g.new_ep("bool")
libgraph_tool_structure.spanner(g,
weight._get_any() if weight is not None
else None, k, sp._get_any(), _get_rng())
return sp
[docs]
def small_world_sigma(g, niter=100, nrand=10):
r"""Return the small-world coefficient sigma of a graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Connected undirected graph.
niter : ``int`` (optional, default: ``100``)
Number of edge swaps per edge in each random reference.
nrand : ``int`` (optional, default: ``10``)
Number of random references averaged.
Returns
-------
sigma : ``float``
The coefficient :math:`\sigma = (C/C_r)/(L/L_r)`.
See Also
--------
small_world_omega: Small-world coefficient omega
graph_tool.generation.random_rewire_connected: Degree-preserving randomization
graph_tool.clustering.global_clustering: Global clustering coefficient
average_shortest_path_length: Average distance between pairs of vertices
Notes
-----
:math:`C` is the global clustering coefficient (transitivity, see
:func:`~graph_tool.clustering.global_clustering`) and :math:`L` the
average shortest path length (see
:func:`~graph_tool.structure.average_shortest_path_length`), and
:math:`C_r`, :math:`L_r` are their averages over random references
with the same degrees (see
:func:`~graph_tool.generation.random_rewire_connected`)
[humphries-network-2008]_. A graph is often called "
`small world <https://en.wikipedia.org/wiki/Small-world_network>`_
" if
:math:`\sigma > 1`.
The reference graphs are generated in parallel, each with the random
number generator of its thread, so that the result depends on the number
of threads, besides the seed.
Examples
--------
.. testsetup:: sigma
gt.seed_rng(42)
.. doctest:: sigma
>>> g = gt.collection.data["karate"]
>>> print(gt.small_world_sigma(g, niter=10, nrand=5))
1.05...
References
----------
.. [humphries-network-2008] Mark D. Humphries and Kevin Gurney, "Network
'small-world-ness': a quantitative method for determining canonical
network equivalence", PLoS ONE 3, e0002051 (2008),
:DOI:`10.1371/journal.pone.0002051`
"""
from .. clustering import global_clustering
n, es = _simple_edges(g)
C = global_clustering(g)[0]
L = average_shortest_path_length(g)
Cr, Lr = libgraph_tool_structure.small_world_references(n, es, int(niter),
int(nrand), False,
_get_rng())
return (C / Cr) / (L / Lr)
[docs]
def small_world_omega(g, niter=5, nrand=10):
r"""Return the small-world coefficient omega of a graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Connected undirected graph.
niter : ``int`` (optional, default: ``5``)
Number of edge swaps per edge in each reference graph.
nrand : ``int`` (optional, default: ``10``)
Number of reference graphs averaged.
Returns
-------
omega : ``float``
The coefficient :math:`\omega = L_r/L - C/C_l`.
See Also
--------
small_world_sigma: Small-world coefficient sigma
graph_tool.generation.random_rewire_connected: Degree-preserving randomization
graph_tool.generation.random_rewire_lattice: Rewiring towards a ring lattice
Notes
-----
:math:`L` is the average shortest path length and :math:`C` the average
local clustering coefficient; :math:`L_r` is averaged over random
references and :math:`C_l` over lattice references with the same degrees
(see :func:`~graph_tool.generation.random_rewire_connected` and
:func:`~graph_tool.generation.random_rewire_lattice`)
[telesford-ubiquity-2011]_. It is close to zero for
`small-world graphs <https://en.wikipedia.org/wiki/Small-world_network>`_,
negative for lattice-like and positive for random-like ones.
The reference graphs are generated in parallel, each with the random
number generator of its thread, so that the result depends on the number
of threads, besides the seed.
Examples
--------
.. testsetup:: omega
gt.seed_rng(42)
.. doctest:: omega
>>> g = gt.collection.data["karate"]
>>> print(gt.small_world_omega(g, niter=5, nrand=5))
-0...
References
----------
.. [telesford-ubiquity-2011] Qawi K. Telesford, Karen E. Joyce, Satoru
Hayasaka, Jonathan H. Burdette and Paul J. Laurienti, "The ubiquity of
small-world networks", Brain Connectivity 1, 367-375 (2011),
:DOI:`10.1089/brain.2011.0038`
"""
from .. clustering import local_clustering
n, es = _simple_edges(g)
C = local_clustering(g).fa.mean()
L = average_shortest_path_length(g)
Lr, Cl = libgraph_tool_structure.small_world_references(n, es, int(niter),
int(nrand), True,
_get_rng())
return Lr / L - C / Cl
[docs]
def common_neighbor_centrality(g, vertex_pairs, alpha=0.8):
r"""Return the common neighbor and centrality based parameterized
algorithm (CCPA) score of pairs of vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
vertex_pairs : iterable of pairs of ``int``
The pairs of vertices.
alpha : ``float`` (optional, default: ``0.8``)
Weight of the common neighbors.
Returns
-------
scores : :class:`numpy.ndarray`
The score of every pair.
See Also
--------
vertex_similarity: Local similarity indices of pairs of vertices
community_link_prediction: Community-based link prediction
graph_tool.centrality.closeness: Closeness centrality
Notes
-----
The
`score <https://en.wikipedia.org/wiki/Link_prediction>`_
[ahmad-missing-2020]_ is
.. math::
s_{uv} = \alpha|\Gamma(u)\cap\Gamma(v)| + (1-\alpha)\frac{V}{d_{uv}},
where :math:`\Gamma(u)` is the set of distinct neighbors of :math:`u`
other than itself, :math:`V` is the number of vertices, and
:math:`d_{uv}` is the shortest-path distance between the vertices, all
ignoring the edge directions (the second term vanishes if they are not
connected). The distances are computed by a breadth-first search from
every distinct first vertex of the pairs.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.common_neighbor_centrality(g, [(0, 33), (5, 6)]))
[6.6 8.4]
References
----------
.. [ahmad-missing-2020] Iftikhar Ahmad, Muhammad Usman Akhtar, Salma
Noor and Ambreen Shahnaz, "Missing link prediction using common
neighbor and centrality based parameterized algorithm", Scientific
Reports 10, 364 (2020), :DOI:`10.1038/s41598-019-57304-y`
"""
pairs = numpy.ascontiguousarray(numpy.asarray(vertex_pairs, dtype="int64")
.reshape(-1, 2))
if (pairs[:, 0] == pairs[:, 1]).any():
raise ValueError("self-pairs are not supported")
return libgraph_tool_structure.common_neighbor_centrality(
GraphView(g, directed=False), pairs, float(alpha))
[docs]
@_parallel
def panther_similarity(g, source, k=5, path_length=5, c=0.5, delta=0.1,
eps=None, weight=None, vector=False, D=10):
r"""Return the vertices most similar to a given one according to the
Panther algorithm.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
source : :class:`~graph_tool.Vertex` or ``int``
Vertex whose similar vertices are returned.
k : ``int`` (optional, default: ``5``)
Number of vertices returned.
path_length : ``int`` (optional, default: ``5``)
Number of steps of the random paths.
c : ``float`` (optional, default: ``0.5``)
Constant of the sample size.
delta : ``float`` (optional, default: ``0.1``)
Probability that the error exceeds ``eps``.
eps : ``float`` (optional, default: ``None``)
Error bound; if not given, :math:`\sqrt{1/E}`.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights, used as transition weights.
vector : ``bool`` (optional, default: ``False``)
If ``True``, the Panther++ similarity is used (see below).
D : ``int`` (optional, default: ``10``)
Dimension of the feature vectors of Panther++.
Returns
-------
vertices : :class:`numpy.ndarray`
The ``k`` most similar vertices, in decreasing similarity.
similarity : :class:`numpy.ndarray`
Their similarities.
See Also
--------
simrank: SimRank similarity of pairs of vertices
vertex_similarity: Local similarity indices of pairs of vertices
Notes
-----
The Panther similarity [zhang-panther-2015]_ of two vertices is the
fraction of :math:`R` random paths that contain both, where the paths of
``path_length`` steps start at uniformly chosen vertices, and :math:`R
= \frac{c}{\epsilon^2}(\log_2\binom{T}{2} + 1 + \ln\frac{1}{\delta})`
with :math:`T` = ``path_length`` guarantees an error below
:math:`\epsilon` with probability :math:`1 - \delta`. The walks are
sampled as with :func:`~graph_tool.structure.random_walk`, in time
:math:`O(RT)`.
With ``vector == True``, every vertex is described by the vector of its
``D`` largest Panther similarities (to any vertex, itself included), and
the similarity of two vertices is the inverse Euclidean distance between
their vectors, normalized by the largest one among those returned
(Panther++ [zhang-panther-2015]_). The vectors are obtained from the
co-occurrences of the vertices in the walks, in time :math:`O(RT^2)`, and
the nearest ones by comparing the vector of the source with all others, in
time :math:`O(VD\log V)`.
@parallel@
Examples
--------
.. testsetup:: panther
gt.seed_rng(42)
.. doctest:: panther
>>> g = gt.collection.data["karate"]
>>> vs, s = gt.panther_similarity(g, 0, k=3)
>>> print(vs)
[2 1 3]
References
----------
.. [zhang-panther-2015] Jing Zhang, Jie Tang, Cong Ma, Hanghang Tong, Yu
Jing and Juanzi Li, "Panther: Fast top-k similarity search on large
networks", Proceedings of the 21th ACM SIGKDD International Conference
on Knowledge Discovery and Data Mining, 1445-1454 (2015),
:DOI:`10.1145/2783258.2783267`
"""
if eps is None:
eps = math.sqrt(1. / max(g.num_edges(), 1))
t2 = math.comb(path_length, 2)
R = int((c / eps ** 2) * (math.log2(max(t2, 1)) + 1 +
math.log(1 / delta)))
R = max(R, 1)
if weight is not None:
_check_prop_scalar(weight, "weight")
if not vector:
k = min(k, g.num_vertices() - 1)
top, sim = libgraph_tool_structure.panther_similarity(
g, int(source), int(k), R, int(path_length),
bool(vector), int(D), float(eps),
weight._get_any() if weight is not None else None, _get_rng())
return numpy.asarray(top, dtype="int64"), numpy.asarray(sim)
[docs]
def bipartite_vertex_cover(g, partition=None):
r"""Return a minimum vertex cover of a bipartite graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Bipartite graph. Edge directions are ignored.
partition : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Boolean partition of the vertices. If not given, it is computed with
:func:`~graph_tool.structure.is_bipartite`.
Returns
-------
cover : :class:`~graph_tool.VertexPropertyMap`
Boolean vertex property map marking the vertices of the cover.
See Also
--------
approx_minimum_vertex_cover: Approximate minimum vertex cover
maximum_cardinality_matching: Maximum matching, as large as the cover
is_bipartite: Test for bipartite graphs
Notes
-----
By
`König's theorem <https://en.wikipedia.org/wiki/K%C5%91nig%27s_theorem_(graph_theory)>`_
[konig-grafok-1931]_, the size of a minimum vertex
cover of a bipartite graph equals that of a maximum matching. From a
maximum matching (see
:func:`~graph_tool.structure.maximum_cardinality_matching`), the vertices
:math:`Z` reachable from the unmatched vertices of the first side
:math:`L` by alternating paths (whose edges alternate between unmatched
and matched ones) are found, and the cover is :math:`(L \setminus Z)
\cup (R \cap Z)`, where :math:`R` is the second side. The time is
dominated by the matching. Minimum vertex covers of general graphs are
NP-hard; an approximation is given by
:func:`~graph_tool.structure.approx_minimum_vertex_cover`.
Examples
--------
>>> g = gt.Graph([(0, 3), (0, 4), (1, 3), (2, 4), (2, 5)], directed=False)
>>> c = gt.bipartite_vertex_cover(g)
>>> print(c.a.sum(), gt.maximum_cardinality_matching(g, edges=True).a.sum())
3 3
References
----------
.. [konig-grafok-1931] Dénes Kőnig, "Gráfok és mátrixok", Matematikai és
Fizikai Lapok 38, 116-119 (1931).
"""
u = GraphView(g, directed=False)
if partition is None:
bip, partition = is_bipartite(u, partition=True)
if not bip:
raise ValueError("The graph is not bipartite.")
_check_prop_scalar(partition, "partition")
m = maximum_cardinality_matching(u, bipartite=partition, edges=True)
cover = g.new_vp("bool")
libgraph_tool_structure.bipartite_vertex_cover(u,
partition._get_any(),
m._get_any(),
cover._get_any())
return cover
[docs]
@_parallel
def maximal_extendability(g):
r"""Return the maximal extendability of a bipartite graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Connected bipartite graph with a perfect matching.
Returns
-------
k : ``int``
The largest :math:`k` such that every matching of :math:`k` edges
extends to a perfect matching.
See Also
--------
maximum_cardinality_matching: Maximum matching
graph_tool.flow.disjoint_paths: Disjoint paths between two vertices
is_bipartite: Test for bipartite graphs
Notes
-----
A connected bipartite graph with a
`perfect matching <https://en.wikipedia.org/wiki/Perfect_matching>`_
is
:math:`k`-extendable if every matching of :math:`k` edges (a set of
:math:`k` edges no two of which share an endpoint) is contained in a
perfect matching (one that covers every vertex), and its maximal
extendability is the largest such :math:`k`. To compute it, a perfect
matching is oriented from the second side to the first, and the
other edges from the first side to the second; the extendability is the
smallest number of vertex-disjoint paths in this residual graph from a
vertex of the first side to one of the second [lakhal-polynomial-1998]_,
found by augmenting paths (as with :func:`~graph_tool.flow.disjoint_paths`)
for every pair, so that the time is :math:`O(V^2 E k)`. A ``ValueError`` is
raised if the graph is not connected or bipartite, has no perfect matching,
or its residual graph is not strongly connected (in which case the
extendability is zero).
@parallel@
Examples
--------
>>> g = gt.lattice([2, 2, 2])
>>> print(gt.maximal_extendability(g))
2
References
----------
.. [lakhal-polynomial-1998] Jamel Lakhal and Louis Litzler, "A
polynomial algorithm for the extendability problem in bipartite
graphs", Information Processing Letters 65, 11-16 (1998),
:DOI:`10.1016/S0020-0190(97)00177-4`
"""
u = GraphView(g, directed=False)
if len(label_components(u)[1]) != 1:
raise ValueError("The graph is not connected.")
bip, part = is_bipartite(u, partition=True)
if not bip:
raise ValueError("The graph is not bipartite.")
m = maximum_cardinality_matching(u, bipartite=part, edges=True)
if 2 * m.a.sum() != g.num_vertices():
raise ValueError("The graph has no perfect matching.")
k = libgraph_tool_structure.maximal_extendability(u,
part._get_any(),
m._get_any())
if k < 0:
raise ValueError("The residual graph is not strongly connected.")
return k
[docs]
def cd_index(g, v, time, time_delta, weight=None):
r"""Return the CD index of a vertex of a citation graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed citation graph, with edges from the citing vertex to the
cited one.
v : :class:`~graph_tool.Vertex` or ``int``
Focal vertex.
time : :class:`~graph_tool.VertexPropertyMap`
Time of every vertex.
time_delta : ``float``
Length of the time window after the focal vertex.
weight : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Vertex weights of the citing vertices.
Returns
-------
cd : ``float``
The CD index, rounded to two decimals.
See Also
--------
graph_tool.centrality.pagerank: PageRank centrality
Notes
-----
The CD index [funk-dynamic-2017]_ measures whether a work consolidates or
disrupts its field. For the focal vertex :math:`v` with time
:math:`t_v`, it is
.. math::
\mathrm{CD}_v = \frac{1}{|N_v|}\sum_{u\in N_v}\frac{b_u}{w_u},
where :math:`N_v` is the set of vertices :math:`u` with a time in the
window :math:`t_v < t_u \le t_v + \Delta t` (with :math:`\Delta t`
given by ``time_delta``) that cite :math:`v` or one of the vertices
cited by :math:`v`; :math:`b_u = -1` if :math:`u` cites both :math:`v`
and one of the vertices cited by :math:`v`, :math:`b_u = 1` if it cites
:math:`v` but none of them, and :math:`b_u = 0` if it does not cite
:math:`v`; and :math:`w_u` is the weight of :math:`u` (or one, if no
weights are given). The time window applies to all vertices in
:math:`N_v`, as in the reference implementation of the authors of
[funk-dynamic-2017]_. Without weights, it ranges from :math:`-1`
(consolidating) to :math:`1` (disruptive) [park-papers-2023]_. A
``ValueError`` is raised if :math:`N_v` is empty.
Examples
--------
>>> g = gt.Graph([(4, 0), (4, 1), (5, 0), (6, 1), (6, 2), (0, 3)])
>>> t = g.new_vp("double", vals=[2, 1, 1, 0, 3, 3, 3])
>>> print(gt.cd_index(g, 0, t, 5))
1.0
References
----------
.. [funk-dynamic-2017] Russell J. Funk and Jason Owen-Smith, "A dynamic
network measure of technological change", Management Science 63,
791-817 (2017), :DOI:`10.1287/mnsc.2015.2366`
.. [park-papers-2023] Michael Park, Erin Leahey and Russell J. Funk,
"Papers and patents are becoming less disruptive over time", Nature
613, 138-144 (2023), :DOI:`10.1038/s41586-022-05543-x`
"""
if not g.is_directed():
raise ValueError("The graph must be directed.")
t = numpy.asarray(time.a, dtype="double")
w = numpy.zeros(0) if weight is None else \
numpy.asarray(weight.a, dtype="double")
total, n = libgraph_tool_structure.cd_index(g, int(v), t,
float(time_delta), w)
if n == 0:
raise ValueError("The CD index is not defined for this vertex.")
return round(total / n, 2)
[docs]
def ramsey_r2(g):
r"""Return a clique and an independent vertex set found by the Ramsey
approximation.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
clique : :class:`numpy.ndarray`
The vertices of a clique.
iset : :class:`numpy.ndarray`
The vertices of an independent set.
See Also
--------
clique_removal: Independent set and clique cover
approx_maximum_clique: Approximate maximum clique
Notes
-----
The algorithm of Boppana and Halldórsson [boppana-approximating-1992]_
takes the vertex :math:`v` of smallest index, and is applied recursively
to the subgraphs induced by the neighbors of :math:`v` and by its
non-neighbors, which yield the cliques :math:`C_1, C_2` and the
independent sets :math:`I_1, I_2`, respectively. The clique returned is
the larger of :math:`C_1\cup\{v\}` and :math:`C_2`, and the independent
set the larger of :math:`I_1` and :math:`I_2\cup\{v\}`; the empty graph
yields two empty sets. As in the proof of
`Ramsey's theorem <https://en.wikipedia.org/wiki/Ramsey%27s_theorem>`_,
it follows
by induction that the clique :math:`C` and the independent set
:math:`I` returned satisfy :math:`\binom{|C|+|I|}{|C|} > V`. Self-loops
and parallel edges are ignored. The time is :math:`O(V^2)` per level of
recursion in the worst case.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> c, i = gt.ramsey_r2(g)
>>> print(len(c), len(i))
5 13
The clique and the independent set can be highlighted in a drawing of
the network:
>>> vcolor = g.new_vp("string", val="#cccccc")
>>> for v in c:
... vcolor[v] = "#f28c8e"
>>> for v in i:
... vcolor[v] = "#9bbedc"
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color="#999999", output="ramsey_r2-karate.pdf")
<...>
.. testcleanup::
conv_png("ramsey_r2-karate.pdf")
.. figure:: ramsey_r2-karate.png
:align: center
:width: 50%
Clique (red) and independent vertex set (blue) of Zachary's karate
club network found by the Ramsey approximation.
References
----------
.. [boppana-approximating-1992] Ravi Boppana and Magnús M. Halldórsson,
"Approximating maximum independent sets by excluding subgraphs", BIT
32, 180-196 (1992), :DOI:`10.1007/BF01994876`
"""
# the edge directions are ignored
if g.is_directed():
g = GraphView(g, directed=False)
c, i = libgraph_tool_structure.ramsey_r2(g)
return numpy.asarray(c), numpy.asarray(i)
[docs]
def clique_removal(g):
r"""Return an approximate maximum independent vertex set and a clique
cover.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
iset : :class:`numpy.ndarray`
The vertices of an independent set.
cliques : ``list`` of :class:`numpy.ndarray`
Cliques that cover all vertices.
See Also
--------
ramsey_r2: A clique and an independent vertex set
maximal_independent_vertex_set: Maximal independent vertex set
independence_number: Exact size of a largest independent vertex set
Notes
-----
An independent vertex set is a set of pairwise non-adjacent vertices,
and a
`clique cover <https://en.wikipedia.org/wiki/Clique_cover>`_
is a partition of the vertices into cliques (sets of
pairwise adjacent vertices), ignoring the edge directions. The clique
removal algorithm [boppana-approximating-1992]_ applies
:func:`~graph_tool.structure.ramsey_r2` repeatedly, removing the clique
found each time, and keeps the largest independent set, which
approximates the maximum within a factor :math:`O(V/\log^2 V)`. The
approximate maximum clique is the independent set of the complement
graph (see :func:`~graph_tool.structure.approx_maximum_clique`).
Examples
--------
>>> g = gt.collection.data["karate"]
>>> i, cs = gt.clique_removal(g)
>>> print(len(i), sum([len(c) for c in cs]))
19 34
References
----------
.. [boppana-approximating-1992] Ravi Boppana and Magnús M. Halldórsson,
"Approximating maximum independent sets by excluding subgraphs", BIT
32, 180-196 (1992), :DOI:`10.1007/BF01994876`
"""
# the edge directions are ignored
if g.is_directed():
g = GraphView(g, directed=False)
i, cs = libgraph_tool_structure.clique_removal(g)
return numpy.asarray(i), [numpy.asarray(c) for c in cs]
[docs]
def approx_maximum_clique(g):
r"""Return an approximate maximum clique.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
clique : :class:`numpy.ndarray`
The vertices of a clique.
See Also
--------
largest_cliques: Exact cliques of maximum size
large_clique_size: Size of a large clique
maximum_weight_clique: Clique of maximum total vertex weight
Notes
-----
A clique is a set of pairwise adjacent vertices (ignoring the edge
directions), and a
`maximum clique <https://en.wikipedia.org/wiki/Clique_problem>`_
is one of the largest size. The clique
returned is the independent set found by
:func:`~graph_tool.structure.clique_removal` in the complement graph,
which approximates the maximum within a factor :math:`O(V/\log^2 V)`
[boppana-approximating-1992]_; the complement takes time and memory
:math:`O(V^2)`. The exact maximum is found by
:func:`~graph_tool.structure.maximum_weight_clique`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(len(gt.approx_maximum_clique(g)))
5
References
----------
.. [boppana-approximating-1992] Ravi Boppana and Magnús M. Halldórsson,
"Approximating maximum independent sets by excluding subgraphs", BIT
32, 180-196 (1992), :DOI:`10.1007/BF01994876`
"""
# the edge directions are ignored
if g.is_directed():
g = GraphView(g, directed=False)
c, vs = _simple_complement(g)
i, cs = clique_removal(c)
return vs[i]
[docs]
def large_clique_size(g):
r"""Return the size of a large clique found by a fast heuristic.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
size : ``int``
The size of a clique, a lower bound on the clique number.
See Also
--------
clique_number: Exact size of a largest clique
approx_maximum_clique: Approximate maximum clique
Notes
-----
From every vertex with degree at least the best size found so far, a
clique is grown greedily [pattabiraman-fast-2015]_: the candidates are
the vertices adjacent to all the vertices of the clique whose degree is
at least the best size found so far, and the candidate of largest degree
is added, until there are no candidates left. The size returned is the
largest of these cliques, and the degrees are those of the simple graph
underlying ``g``. The time is :math:`O(V\Delta^2)` in the worst
case, where :math:`\Delta` is the largest degree.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.large_clique_size(g), gt.clique_number(g))
5 5
References
----------
.. [pattabiraman-fast-2015] Bharath Pattabiraman, Md. Mostofa Ali Patwary,
Assefaw H. Gebremedhin, Wei-keng Liao and Alok Choudhary, "Fast
algorithms for the maximum clique problem on massive graphs with
applications to overlapping community detection", Internet
Mathematics 11, 421-448 (2015), :DOI:`10.1080/15427951.2014.986778`
"""
# the edge directions are ignored
if g.is_directed():
g = GraphView(g, directed=False)
return libgraph_tool_structure.large_clique_size(g)
[docs]
def approx_minimum_maximal_matching(g):
r"""Return a maximal matching, which approximates the minimum maximal
matching within a factor two.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
matching : :class:`~graph_tool.EdgePropertyMap`
Boolean edge property map marking the edges of the matching.
See Also
--------
maximum_cardinality_matching: Maximum matching
approx_minimum_edge_dominating_set: Approximate minimum edge dominating set
Notes
-----
A
`matching <https://en.wikipedia.org/wiki/Matching_(graph_theory)>`_
is a set of edges no two of which share an endpoint, and it is
maximal if no other edge can be added to it, i.e. if every edge shares an
endpoint with an edge of the matching. A minimum maximal matching is a
maximal matching with the fewest edges. Any maximal matching has at most
twice as many edges as a minimum maximal matching (which is NP-hard to
find), and the same holds for the minimum edge dominating set (see
:func:`~graph_tool.structure.approx_minimum_edge_dominating_set`)
[yannakakis-edge-1980]_. A maximum matching (see
:func:`~graph_tool.structure.maximum_cardinality_matching`) is used, which is
maximal.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.approx_minimum_maximal_matching(g).a.sum())
13
The matching can be highlighted in a drawing of the network:
>>> m = gt.approx_minimum_maximal_matching(g)
>>> ecolor = g.new_ep("string", vals=np.where(m.a, "#e41a1c", "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(m.a, 2.5, 1))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color="#cccccc",
... edge_color=ecolor, edge_pen_width=ewidth,
... output="approx_minimum_maximal_matching-karate.pdf")
<...>
.. testcleanup::
conv_png("approx_minimum_maximal_matching-karate.pdf")
.. figure:: approx_minimum_maximal_matching-karate.png
:align: center
:width: 50%
Maximal matching of Zachary's karate club network, with its edges
shown in red.
References
----------
.. [yannakakis-edge-1980] Mihalis Yannakakis and Fanica Gavril, "Edge
dominating sets in graphs", SIAM Journal on Applied Mathematics 38,
364-372 (1980), :DOI:`10.1137/0138030`
"""
return maximum_cardinality_matching(GraphView(g, directed=False),
edges=True)
[docs]
def approx_minimum_edge_dominating_set(g):
r"""Return an edge dominating set within a factor two of the minimum.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored.
Returns
-------
edges : :class:`~graph_tool.EdgePropertyMap`
Boolean edge property map marking the edges of the set, each other
edge sharing an endpoint with one of them.
See Also
--------
approx_minimum_maximal_matching: Approximate minimum maximal matching
approx_minimum_dominating_set: Vertex counterpart
Notes
-----
An
`edge dominating set <https://en.wikipedia.org/wiki/Edge_dominating_set>`_
is a set :math:`D` of edges such that every edge
of the graph is in :math:`D` or shares an endpoint with an edge of
:math:`D`, and a minimum one has the fewest edges. A maximal matching
is an edge dominating set, and the smallest edge
dominating set has the size of the smallest maximal matching
[yannakakis-edge-1980]_, so that the matching returned by
:func:`~graph_tool.structure.approx_minimum_maximal_matching` is a
2-approximation.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.approx_minimum_edge_dominating_set(g).a.sum())
13
References
----------
.. [yannakakis-edge-1980] Mihalis Yannakakis and Fanica Gavril, "Edge
dominating sets in graphs", SIAM Journal on Applied Mathematics 38,
364-372 (1980), :DOI:`10.1137/0138030`
"""
return approx_minimum_maximal_matching(g)
[docs]
def densest_subgraph(g, iterations=1, method="greedy++"):
r"""Return an approximately densest subgraph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions, self-loops, and parallel edges are
ignored.
iterations : ``int`` (optional, default: ``1``)
Number of iterations.
method : ``str`` (optional, default: ``"greedy++"``)
Algorithm: ``"greedy++"`` or ``"fista"``.
Returns
-------
density : ``float``
The density :math:`E(S)/|S|` of the subgraph found.
vertices : :class:`numpy.ndarray`
Its vertices.
See Also
--------
kcore_subgraph: K-core of the graph
maximal_cliques: Maximal cliques
graph_tool.stats.density: Density of a graph
Notes
-----
The
`densest subgraph <https://en.wikipedia.org/wiki/Dense_subgraph>`_
is induced by the set of vertices :math:`S` that
maximizes the density
.. math::
\rho(S) = \frac{|E(S)|}{|S|},
where :math:`E(S)` is the set of edges with both endpoints in :math:`S`
of the simple undirected graph underlying ``g``. Both methods remove
("peel") the vertices one at a time, and return the set of remaining
vertices of largest density found along the way. With one iteration,
Greedy++ [boob-flowless-2020]_ is Charikar's greedy peeling
[charikar-greedy-2000]_, which removes each time a vertex of smallest
degree in the remaining subgraph, and is a 2-approximation, i.e.
:math:`\rho(S) \ge \max_{S'}\rho(S')/2`; further iterations peel by the
remaining degree plus a load, which accumulates the degree of every vertex
at its removal in the previous iterations, and the density converges to
the optimum. FISTA [harb-faster-2022]_ solves the dual linear program, in
which every edge splits a unit load between its endpoints so that the
sum of the squares of the total loads of the vertices is minimized, by an
accelerated projected gradient method, starting from equal shares; the
fractional solution is then rounded by peeling, which removes each time
a vertex of smallest remaining load, i.e. of the smallest sum of its
shares of the edges to the vertices not yet removed. Each iteration
takes time :math:`O(E\log V)` (Greedy++) or :math:`O(E)` (FISTA, which
is followed by a single peeling in time :math:`O(E\log V)`).
Examples
--------
>>> g = gt.collection.data["karate"]
>>> d, vs = gt.densest_subgraph(g, iterations=10)
>>> print(d, len(vs))
2.625 16
The subgraph can be highlighted in a drawing of the network:
>>> ind = g.new_vp("bool")
>>> ind.a[vs] = True
>>> vcolor = g.new_vp("string", vals=np.where(ind.a, "#f28c8e",
... "#cccccc"))
>>> s = gt.edge_endpoint_property(g, ind, "source")
>>> t = gt.edge_endpoint_property(g, ind, "target")
>>> ecolor = g.new_ep("string", vals=np.where(s.a & t.a, "#e41a1c",
... "#999999"))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color=ecolor, output="densest_subgraph-karate.pdf")
<...>
.. testcleanup::
conv_png("densest_subgraph-karate.pdf")
.. figure:: densest_subgraph-karate.png
:align: center
:width: 50%
Densest subgraph of Zachary's karate club network found by Greedy++,
with its vertices and edges shown in red.
References
----------
.. [charikar-greedy-2000] Moses Charikar, "Greedy approximation
algorithms for finding dense components in a graph", APPROX 2000,
Lecture Notes in Computer Science 1913, 84-95 (2000),
:DOI:`10.1007/3-540-44436-X_10`
.. [boob-flowless-2020] Digvijay Boob, Yu Gao, Richard Peng, Saurabh
Sawlani, Charalampos Tsourakakis, Di Wang and Junxing Wang,
"Flowless: Extracting densest subgraphs without flow computations",
Proceedings of The Web Conference 2020, 573-583 (2020),
:DOI:`10.1145/3366423.3380140`
.. [harb-faster-2022] Elfarouk Harb, Kent Quanrud and Chandra Chekuri,
"Faster and scalable algorithms for densest subgraph and decomposition",
Advances in Neural Information Processing Systems 35 (2022),
:arxiv:`2206.02942`
"""
if method not in ["greedy++", "fista"]:
raise ValueError(f"invalid method: {method}")
if iterations < 1:
raise ValueError("iterations must be at least 1")
d, vs = libgraph_tool_structure.densest_subgraph(g,
method == "fista",
int(iterations))
return d, numpy.asarray(vs, dtype="int64")
[docs]
def connected_dominating_set(g):
r"""Return a connected dominating set of a connected graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Connected graph to be used. Edge directions are ignored.
Returns
-------
dset : :class:`~graph_tool.VertexPropertyMap`
Boolean vertex property map marking the vertices of the set.
See Also
--------
approx_minimum_dominating_set: Approximate minimum dominating set
steiner_tree: Approximate minimum tree connecting a subset of vertices
Notes
-----
A
`connected dominating set <https://en.wikipedia.org/wiki/Connected_dominating_set>`_
is a set of vertices that induces a connected
subgraph and such that every other vertex is adjacent to one of them.
The non-leaf vertices of any spanning tree form such a set, and the
minimum ones are the complements of the sets of leaves of the spanning
trees with the most leaves; finding one is NP-hard. The first greedy
algorithm of Guha and Khuller [guha-approximation-1998]_ starts from a
vertex of largest degree, whose neighbors become reached, and then adds
repeatedly the reached vertex with the most unreached neighbors, which
become reached in turn, until all vertices are reached. Since every
vertex added is adjacent to one added before, the set is connected, and
it approximates the minimum within a factor
:math:`2(1 + H(\Delta))`, where :math:`H` is the harmonic number and
:math:`\Delta` the largest degree. The time is :math:`O((V+E)\log V)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> d = gt.connected_dominating_set(g)
>>> print(d.a.sum())
5
The set can be highlighted in a drawing of the network:
>>> vcolor = g.new_vp("string", vals=np.where(d.a, "#f28c8e", "#cccccc"))
>>> s = gt.edge_endpoint_property(g, d, "source")
>>> t = gt.edge_endpoint_property(g, d, "target")
>>> ecolor = g.new_ep("string", vals=np.where(s.a & t.a, "#e41a1c",
... "#999999"))
>>> ewidth = g.new_ep("double", vals=np.where(s.a & t.a, 2.5, 1))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color=ecolor, edge_pen_width=ewidth,
... output="connected_dominating_set-karate.pdf")
<...>
.. testcleanup::
conv_png("connected_dominating_set-karate.pdf")
.. figure:: connected_dominating_set-karate.png
:align: center
:width: 50%
Connected dominating set of Zachary's karate club network, with its
vertices and the edges between them shown in red.
References
----------
.. [guha-approximation-1998] Sudipto Guha and Samir Khuller,
"Approximation algorithms for connected dominating sets",
Algorithmica 20, 374-387 (1998), :DOI:`10.1007/PL00009201`
"""
u = GraphView(g, directed=False)
if g.num_vertices() > 0 and len(label_components(u)[1]) != 1:
raise ValueError("The graph must be connected.")
d = g.new_vp("bool")
libgraph_tool_structure.connected_dominating_set(u,
d._get_any())
return d
def _vset_mask(g, S, name="S"):
"""Vertex mask (uint8 array indexed by vertex) of a set of vertices given
as an iterable or a vertex property map."""
m = numpy.zeros(g.num_vertices(True), dtype="uint8")
if isinstance(S, VertexPropertyMap):
_check_prop("v", g, S)
m[:] = numpy.asarray(S.a) != 0
return m
if isinstance(S, (int, numpy.integer)) or hasattr(S, "out_degree"):
S = [S]
idx = numpy.asarray([int(v) for v in S], dtype="int64")
if idx.size > 0 and (idx.min() < 0 or idx.max() >= len(m)):
raise ValueError("invalid vertex in %s" % name)
m[idx] = 1
return m
def _cut_stats(g, S, T, weight):
if weight is not None:
_check_prop_scalar(weight, "weight")
ms = _vset_mask(g, S)
if T is None:
mt = 1 - ms
else:
mt = _vset_mask(g, T, "T")
return libgraph_tool_structure.cut_stats(g, ms, mt, weight)
[docs]
def cut_size(g, S, T=None, weight=None):
r"""Return the size of the cut between two sets of vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
S : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap`
First set of vertices, as a sequence of vertices or a Boolean vertex
property map.
T : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Second set of vertices. If not given, the complement of ``S`` is used.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights. If not given, every edge has weight one.
Returns
-------
cut : ``float``
The total weight of the edges between ``S`` and ``T``.
See Also
--------
volume: Total degree of a set of vertices
conductance: Cut size normalized by the smaller volume
normalized_cut_size: Cut size normalized by both volumes
edge_boundary: Edges of the cut
graph_tool.flow.minimum_cut: Minimum cut
Notes
-----
The `cut size <https://en.wikipedia.org/wiki/Cut_(graph_theory)>`_ is
.. math::
c(S, T) = \sum_{\{u,v\}\in E,\, u\in S,\, v\in T} w_{uv},
the total weight of the edges with one endpoint in :math:`S` and the
other in :math:`T`; for directed graphs, the edges in both directions
are counted. This and the other cut and expansion measures
(:func:`volume`, :func:`conductance`, :func:`normalized_cut_size`,
:func:`edge_expansion`, :func:`vertex_expansion`,
:func:`boundary_expansion`, and :func:`mixing_expansion`) are described in
[gleich-hierarchical-2005]_, and are computed in time :math:`O(V + E)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> S = np.arange(17)
>>> print(gt.cut_size(g, S))
20.0
References
----------
.. [gleich-hierarchical-2005] David Gleich, "Hierarchical directed spectral
graph partitioning", Information Networks (2005),
https://www.cs.purdue.edu/homes/dgleich/publications/Gleich%202005%20-%20hierarchical%20directed%20spectral.pdf
"""
return _cut_stats(g, S, T, weight)[0]
[docs]
def volume(g, S, weight=None):
r"""Return the volume of a set of vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
S : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap`
Set of vertices, as a sequence of vertices or a Boolean vertex
property map.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights. If not given, every edge has weight one.
Returns
-------
vol : ``float``
The volume of ``S``.
See Also
--------
cut_size: Size of the cut between two sets of vertices
conductance: Cut size normalized by the smaller volume
Notes
-----
The volume of a set :math:`S` of vertices is
.. math::
\mathrm{vol}(S) = \sum_{v\in S}\sum_{e\in\delta(v)} w_e,
where :math:`\delta(v)` is the set of edges incident to :math:`v` (its
out-edges, for directed graphs), i.e. the sum of the (weighted) degrees
of its vertices, or of their out-degrees for directed graphs. The time is
:math:`O(V + E)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.volume(g, [0, 1, 2]))
35.0
"""
return _cut_stats(g, S, None, weight)[1]
[docs]
def conductance(g, S, T=None, weight=None):
r"""Return the conductance of the cut between two sets of vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
S : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap`
First set of vertices, as a sequence of vertices or a Boolean vertex
property map.
T : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Second set of vertices. If not given, the complement of ``S`` is used.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights. If not given, every edge has weight one.
Returns
-------
phi : ``float``
The conductance.
See Also
--------
cut_size: Size of the cut between two sets of vertices
normalized_cut_size: Cut size normalized by both volumes
edge_expansion: Cut size normalized by the size of the set
volume: Total degree of a set of vertices
Notes
-----
The
`conductance <https://en.wikipedia.org/wiki/Conductance_(graph_theory)>`_
is :math:`c(S,T)/\min(\mathrm{vol}(S),\mathrm{vol}(T))`,
where :math:`c(S,T)` is the cut size (see :func:`cut_size`) and
:math:`\mathrm{vol}` the volume (see :func:`volume`). The time is
:math:`O(V + E)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> S = np.arange(17)
>>> print(gt.conductance(g, S))
0.263157894736...
"""
r = _cut_stats(g, S, T, weight)
return r[0] / min(r[1], r[2])
[docs]
def normalized_cut_size(g, S, T=None, weight=None):
r"""Return the normalized size of the cut between two sets of vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
S : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap`
First set of vertices, as a sequence of vertices or a Boolean vertex
property map.
T : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Second set of vertices. If not given, the complement of ``S`` is used.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights. If not given, every edge has weight one.
Returns
-------
ncut : ``float``
The normalized cut size.
See Also
--------
conductance: Cut size normalized by the smaller volume
cut_size: Size of the cut between two sets of vertices
graph_tool.inference.NormCutState: Normalized cut partitions
Notes
-----
The normalized cut size is :math:`c(S,T)[1/\mathrm{vol}(S) +
1/\mathrm{vol}(T)]`, where :math:`c(S,T)` is the cut size (see
:func:`cut_size`) and :math:`\mathrm{vol}` the volume (see :func:`volume`).
The time is :math:`O(V + E)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> S = np.arange(17)
>>> print(gt.normalized_cut_size(g, S))
0.513157894736...
"""
r = _cut_stats(g, S, T, weight)
return r[0] * (1 / r[1] + 1 / r[2])
[docs]
def edge_expansion(g, S, T=None, weight=None):
r"""Return the edge expansion of a set of vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
S : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap`
First set of vertices, as a sequence of vertices or a Boolean vertex
property map.
T : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Second set of vertices. If not given, the complement of ``S`` is used.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights. If not given, every edge has weight one.
Returns
-------
h : ``float``
The edge expansion.
See Also
--------
mixing_expansion: Cut size normalized by the total edge weight
vertex_expansion: Vertex counterpart
conductance: Cut size normalized by the smaller volume
Notes
-----
The
`edge expansion <https://en.wikipedia.org/wiki/Expander_graph>`_
is :math:`c(S,T)/\min(|S|,|T|)`, where
:math:`c(S,T)` is the cut size (see :func:`cut_size`). The time is
:math:`O(V + E)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> S = np.arange(17)
>>> print(gt.edge_expansion(g, S))
1.176470588235...
"""
r = _cut_stats(g, S, T, weight)
return r[0] / min(r[4], r[5])
[docs]
def mixing_expansion(g, S, T=None, weight=None):
r"""Return the mixing expansion of a set of vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
S : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap`
First set of vertices, as a sequence of vertices or a Boolean vertex
property map.
T : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Second set of vertices. If not given, the complement of ``S`` is used.
weight : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
Edge weights. If not given, every edge has weight one.
Returns
-------
m : ``float``
The mixing expansion.
See Also
--------
edge_expansion: Cut size normalized by the size of the set
cut_size: Size of the cut between two sets of vertices
conductance: Cut size normalized by the smaller volume
Notes
-----
The mixing expansion is :math:`c(S,T)/2W`, where :math:`c(S,T)` is the
cut size (see :func:`cut_size`) and :math:`W` the total edge weight (the
number of edges, if no weights are given). The time is
:math:`O(V + E)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> S = np.arange(17)
>>> print(gt.mixing_expansion(g, S))
0.128205128205...
"""
r = _cut_stats(g, S, T, weight)
return r[0] / (2 * r[3])
[docs]
def vertex_expansion(g, S):
r"""Return the vertex expansion of a set of vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
S : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap`
Set of vertices, as a sequence of vertices or a Boolean vertex
property map.
Returns
-------
x : ``float``
The vertex expansion.
See Also
--------
boundary_expansion: Boundary size normalized by the size of the set
edge_expansion: Edge counterpart
vertex_boundary: Vertex boundary of a set of vertices
Notes
-----
The
`vertex expansion <https://en.wikipedia.org/wiki/Expander_graph>`_
is :math:`|N(S)|/|S|`, where :math:`N(S)` is the set
of (out-)neighbors of the vertices in :math:`S` (which may include
vertices of :math:`S`). The time is :math:`O(V + E)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.vertex_expansion(g, [0, 1, 2]))
7.333333333333...
"""
r = _cut_stats(g, S, None, None)
return r[6] / r[4]
[docs]
def boundary_expansion(g, S):
r"""Return the boundary expansion of a set of vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
S : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap`
Set of vertices, as a sequence of vertices or a Boolean vertex
property map.
Returns
-------
x : ``float``
The boundary expansion.
See Also
--------
vertex_expansion: Size of the neighborhood normalized by the size of the set
vertex_boundary: Vertex boundary of a set of vertices
Notes
-----
The boundary expansion is :math:`|\partial S|/|S|`, where
:math:`\partial S` is the vertex boundary of :math:`S`, i.e. the
(out-)neighbors of the vertices in :math:`S` that are not in :math:`S`
(see :func:`vertex_boundary`). The time is :math:`O(V + E)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.boundary_expansion(g, [0, 1, 2]))
6.333333333333...
"""
r = _cut_stats(g, S, None, None)
return r[7] / r[4]
[docs]
def vertex_boundary(g, S, T=None):
r"""Return the vertex boundary of a set of vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
S : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap`
Set of vertices, as a sequence of vertices or a Boolean vertex
property map.
T : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
If given, the boundary is restricted to these vertices.
Returns
-------
boundary : :class:`numpy.ndarray`
The vertices of the boundary, in increasing order.
See Also
--------
edge_boundary: Edge counterpart
boundary_expansion: Boundary size normalized by the size of the set
Notes
-----
The vertex boundary of :math:`S` is the set of (out-)neighbors of its
vertices that are not in :math:`S` (and are in :math:`T`, if given).
The time is :math:`O(V + E)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.vertex_boundary(g, [0, 1, 2]))
[ 3 4 5 6 7 8 9 10 11 12 13 17 19 21 27 28 30 31 32]
The set and its boundary can be shown in a drawing of the network:
>>> vcolor = g.new_vp("string", val="#cccccc")
>>> for v in gt.vertex_boundary(g, [0, 1, 2]):
... vcolor[v] = "#f28c8e"
>>> for v in [0, 1, 2]:
... vcolor[v] = "#9bbedc"
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color="#999999", output="vertex_boundary-karate.pdf")
<...>
.. testcleanup::
conv_png("vertex_boundary-karate.pdf")
.. figure:: vertex_boundary-karate.png
:align: center
:width: 50%
Vertex boundary (red) of the set of vertices 0, 1 and 2 (blue) of
Zachary's karate club network.
"""
ms = _vset_mask(g, S)
mt = ms if T is None else _vset_mask(g, T, "T")
return libgraph_tool_structure.vertex_boundary(g, ms, mt,
T is None)
[docs]
def edge_boundary(g, S, T=None):
r"""Return the edge boundary of a set of vertices.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
S : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap`
Set of vertices, as a sequence of vertices or a Boolean vertex
property map.
T : iterable of ``int`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Second set of vertices. If not given, the complement of ``S`` is used.
Returns
-------
edges : :class:`numpy.ndarray`
Array with one row ``(s, t, i)`` for every edge of the boundary,
where ``s`` is in ``S``, ``t`` in ``T``, and ``i`` is the edge index.
See Also
--------
vertex_boundary: Vertex counterpart
cut_size: Size of the cut between two sets of vertices
Notes
-----
The edge boundary contains the edges with one endpoint in :math:`S` and
the other in :math:`T`; for directed graphs, only the out-edges of the
vertices in :math:`S` are considered. The time is :math:`O(V + E)`.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> print(gt.edge_boundary(g, [0, 1, 2])[:4])
[[0 3 3]
[1 3 4]
[2 3 5]
[0 4 6]]
The set and its boundary can be shown in a drawing of the network:
>>> es = gt.edge_boundary(g, [0, 1, 2])
>>> vcolor = g.new_vp("string", val="#cccccc")
>>> for v in [0, 1, 2]:
... vcolor[v] = "#9bbedc"
>>> inb = g.new_ep("bool")
>>> inb.a[es[:, 2]] = True
>>> ecolor = g.new_ep("string", vals=np.where(inb.a, "#e41a1c",
... "#999999"))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color=ecolor, output="edge_boundary-karate.pdf")
<...>
.. testcleanup::
conv_png("edge_boundary-karate.pdf")
.. figure:: edge_boundary-karate.png
:align: center
:width: 50%
Edge boundary (red) of the set of vertices 0, 1 and 2 (blue) of
Zachary's karate club network.
"""
ms = _vset_mask(g, S)
mt = ms if T is None else _vset_mask(g, T, "T")
es = libgraph_tool_structure.edge_boundary(g, ms, mt,
T is None)
return es.reshape((-1, 3))
[docs]
def is_threshold_graph(g):
r"""Return whether the graph is a threshold graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions, self-loops, and parallel edges are
ignored.
Returns
-------
is_threshold : ``bool``
``True`` if the graph is a threshold graph.
See Also
--------
find_threshold_graph: Threshold subgraph of a graph
Notes
-----
A
`threshold graph <https://en.wikipedia.org/wiki/Threshold_graph>`_
[chvatal-aggregation-1977]_ can be built from the empty
graph by adding repeatedly an isolated vertex or a vertex connected to
all previous ones. This holds if and only if its degree sequence is a
threshold sequence, i.e. one that can be reduced to the empty sequence by
removing repeatedly a zero entry or an entry equal to the number of the
remaining entries minus one, which in the latter case are decreased by
one. The time is :math:`O(V\log V + E)`.
Examples
--------
>>> print(gt.is_threshold_graph(gt.complete_graph(5)),
... gt.is_threshold_graph(gt.circular_graph(5)))
True False
References
----------
.. [chvatal-aggregation-1977] Václav Chvátal and Peter L. Hammer,
"Aggregation of inequalities in integer programming", Annals of
Discrete Mathematics 1, 145-162 (1977),
:doi:`10.1016/S0167-5060(08)70731-3`
"""
return libgraph_tool_structure.is_threshold_graph(g)
[docs]
def find_threshold_graph(g):
r"""Return a threshold subgraph of the graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions, self-loops, and parallel edges are
ignored.
Returns
-------
u : :class:`~graph_tool.GraphView`
Induced subgraph that is a threshold graph.
See Also
--------
is_threshold_graph: Test for threshold graphs
Notes
-----
The vertices of the subgraph are found greedily: starting from the whole
graph, its isolated vertices are kept, and its vertex of largest degree
(the largest index among ties) is kept, with the search continuing in the
subgraph induced by the neighbors of this vertex, which is dominating in
the subgraph found there. The induced subgraph of these vertices is a
`threshold graph <https://en.wikipedia.org/wiki/Threshold_graph>`_
(see :func:`is_threshold_graph`), although not necessarily
the largest one. The time is :math:`O(VE)` in the worst case.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> u = gt.find_threshold_graph(g)
>>> print(u.num_vertices(), u.num_edges(), gt.is_threshold_graph(u))
13 21 True
The threshold subgraph can be highlighted in a drawing of the network:
>>> inu = g.new_vp("bool")
>>> inu.a[u.get_vertices()] = True
>>> vcolor = g.new_vp("string", vals=np.where(inu.a, "#f28c8e",
... "#cccccc"))
>>> s = gt.edge_endpoint_property(g, inu, "source")
>>> t = gt.edge_endpoint_property(g, inu, "target")
>>> ecolor = g.new_ep("string", vals=np.where(s.a & t.a, "#e41a1c",
... "#999999"))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=vcolor,
... edge_color=ecolor,
... output="find_threshold_graph-karate.pdf")
<...>
.. testcleanup::
conv_png("find_threshold_graph-karate.pdf")
.. figure:: find_threshold_graph-karate.png
:align: center
:width: 50%
Threshold subgraph of Zachary's karate club network, with its
vertices and edges shown in red.
"""
keep = g.new_vp("bool")
libgraph_tool_structure.find_threshold_graph(g,
keep._get_any())
return GraphView(g, vfilt=keep)
[docs]
def is_kl_connected(g, k, l):
r"""Return whether the graph is locally :math:`(k, l)`-connected.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
k : ``int``
Maximum length of the paths.
l : ``int``
Number of edge-disjoint paths.
Returns
-------
is_kl : ``bool``
``True`` if every edge is :math:`(k, l)`-connected.
See Also
--------
kl_connected_subgraph: Largest locally (k, l)-connected subgraph
graph_tool.flow.edge_connectivity: Edge connectivity
Notes
-----
An edge :math:`(u, v)` is :math:`(k, l)`-connected if there are at least
:math:`l` edge-disjoint paths of length at most :math:`k` from :math:`u` to
:math:`v` [chung-small-2004]_. Since finding the largest number of such
paths is a hard problem, they are found greedily: the edge itself is the
first path, and the next paths are shortest paths, found by breadth-first
search up to depth :math:`k`, in the graph without the edges of the
previous paths. Hence, the graph may be :math:`(k, l)`-connected even if
this function returns ``False``, unless :math:`l \le 2`. The time is
:math:`O(lE(V + E))` in the worst case.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> u, ok = gt.kl_connected_subgraph(g, 2, 2)
>>> print(gt.is_kl_connected(g, 2, 2), gt.is_kl_connected(u, 2, 2))
False True
References
----------
.. [chung-small-2004] Fan Chung and Linyuan Lu, "The small world
phenomenon in hybrid power law graphs", in Complex Networks, Lecture
Notes in Physics 650, 89-104 (Springer, 2004),
:doi:`10.1007/978-3-540-44485-5_4`
"""
if k < 1 or l < 1:
raise ValueError("k and l must be positive")
return libgraph_tool_structure.is_kl_connected(g, int(k),
int(l))
[docs]
def kl_connected_subgraph(g, k, l):
r"""Return the largest locally :math:`(k, l)`-connected subgraph found by
edge removal.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
k : ``int``
Maximum length of the paths.
l : ``int``
Number of edge-disjoint paths.
Returns
-------
u : :class:`~graph_tool.GraphView`
Subgraph with the remaining edges.
ok : ``bool``
``True`` if no edge was removed, i.e. if the graph is locally
:math:`(k, l)`-connected.
See Also
--------
is_kl_connected: Test for local (k, l)-connectivity
graph_tool.flow.label_k_edge_subgraphs: K-edge-connected subgraphs
Notes
-----
The edges that are not :math:`(k, l)`-connected (see
:func:`is_kl_connected`, which describes the greedy search for the paths)
are removed repeatedly, with the paths searched in the remaining graph,
until every remaining edge is :math:`(k, l)`-connected in it, as in the
extraction of the local graph of Chung and Lu [chung-small-2004]_. The time
is :math:`O(lE^2(V + E))` in the worst case.
Examples
--------
>>> g = gt.collection.data["karate"]
>>> u, ok = gt.kl_connected_subgraph(g, 2, 2)
>>> print(u.num_edges(), ok)
67 False
The edges removed can be shown in a drawing of the network:
>>> kept = g.new_ep("bool")
>>> kept.a[u.get_edges([u.edge_index])[:, 2]] = True
>>> ecolor = g.new_ep("string", vals=np.where(kept.a, "#999999",
... "#e41a1c"))
>>> ewidth = g.new_ep("double", vals=np.where(kept.a, 1, 2.5))
>>> gt.graph_draw(g, g.vp.pos, vertex_fill_color="#cccccc",
... edge_color=ecolor, edge_pen_width=ewidth,
... output="kl_connected_subgraph-karate.pdf")
<...>
.. testcleanup::
conv_png("kl_connected_subgraph-karate.pdf")
.. figure:: kl_connected_subgraph-karate.png
:align: center
:width: 50%
Locally :math:`(2, 2)`-connected subgraph of Zachary's karate club
network. The edges removed are shown in red, and the remaining edges
in gray.
References
----------
.. [chung-small-2004] Fan Chung and Linyuan Lu, "The small world
phenomenon in hybrid power law graphs", in Complex Networks, Lecture
Notes in Physics 650, 89-104 (Springer, 2004),
:doi:`10.1007/978-3-540-44485-5_4`
"""
if k < 1 or l < 1:
raise ValueError("k and l must be positive")
keep = g.new_ep("bool")
ok = libgraph_tool_structure.kl_connected_subgraph(g,
int(k), int(l),
keep._get_any())
return GraphView(g, efilt=keep), ok
[docs]
def count_reachable(g, mode="out"):
r"""Return the number of vertices reachable from every vertex.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used.
mode : ``str`` (optional, default: ``"out"``)
If ``"out"``, the vertices reachable from every vertex are counted;
if ``"in"``, those from which every vertex is reachable. Ignored for
undirected graphs.
Returns
-------
count : :class:`~graph_tool.VertexPropertyMap`
The number of reachable vertices, including the vertex itself.
See Also
--------
label_out_component: Vertices reachable from a given vertex
transitive_closure: Transitive closure of a graph
Notes
-----
The strongly connected components are contracted with Tarjan's algorithm
[tarjan-depth-1972]_, which numbers them in reverse topological order, and
the sets of components
`reachable <https://en.wikipedia.org/wiki/Reachability>`_
from every component are propagated as
bitsets in this order, in blocks of target components so that the memory
used by the bitsets is bounded by about 128 MB. The blocks, or the words
of the bitsets of a single block, are processed in parallel; since the
memory bound is shared among the threads, fewer threads are used if the
bitsets of every thread would become too short. The time is
:math:`O(V + E + C(C + E_C)/64)`, where :math:`C` and :math:`E_C` are the
numbers of components and of edges between them. For undirected graphs, the
sizes of the connected components are returned, in time :math:`O(V + E)`.
Examples
--------
>>> g = gt.collection.data["celegansneural"]
>>> c = gt.count_reachable(g)
>>> print(c.a.min(), c.a.max())
1 268
References
----------
.. [tarjan-depth-1972] Robert Tarjan, "Depth-first search and linear
graph algorithms", SIAM Journal on Computing 1, 146-160 (1972),
:doi:`10.1137/0201010`
"""
if mode not in ["out", "in"]:
raise ValueError("invalid mode: " + str(mode))
count = g.new_vp("int64_t")
libgraph_tool_structure.count_reachable(g, mode == "in",
count._get_any())
return count
[docs]
def dag_to_branching(g):
r"""Return the branching of the paths from the sources of a directed
acyclic graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Directed acyclic graph.
Returns
-------
b : :class:`~graph_tool.Graph`
The branching, a directed forest.
source : :class:`~graph_tool.VertexPropertyMap`
Vertex property map of ``b`` with the vertex of ``g`` that
corresponds to every vertex.
See Also
--------
unfold_tree: Unfolding of a graph into a forest
topological_sort: Topological ordering of a directed acyclic graph
Notes
-----
The branching has a vertex for every distinct path (as a sequence of
vertices, so that parallel edges are merged) that starts at a source
of ``g`` (a vertex without in-edges), which corresponds to the last vertex
of the path, and the vertex of every path is the parent of those of its
extensions by one vertex. Hence, the root-to-leaf paths of the branching
correspond one-to-one to the root-to-leaf paths of ``g``. The vertices are
numbered in depth-first order, from the sources in increasing order and
with the out-neighbors in increasing order. The number of paths, and hence
the time, can be exponential in the size of the graph.
Examples
--------
>>> g = gt.Graph([(0, 1), (0, 2), (1, 3), (2, 3)])
>>> b, source = gt.dag_to_branching(g)
>>> print(b.get_edges().tolist(), source.a)
[[0, 1], [0, 3], [1, 2], [3, 4]] [0 1 3 2 3]
"""
if not g.is_directed():
raise ValueError("The graph must be directed.")
try:
parent, orig = libgraph_tool_structure.dag_to_branching(g)
except ValueError:
raise ValueError("The graph is not acyclic.")
idx = numpy.where(parent >= 0)[0]
b = Graph(len(orig))
b.add_edge_list(numpy.column_stack((parent[idx], idx)), parallel=False)
source = b.new_vp("int64_t", vals=orig)
return b, source
[docs]
def graphlet_decomposition(g, weight, niter=1000):
r"""Return the graphlet decomposition of a weighted graph.
Parameters
----------
g : :class:`~graph_tool.Graph`
Graph to be used. Edge directions are ignored. The graph must not
have parallel edges, and self-loops are ignored.
weight : :class:`~graph_tool.EdgePropertyMap`
Nonnegative edge weights.
niter : ``int`` (optional, default: ``1000``)
Number of iterations of the projection.
Returns
-------
cliques : ``list`` of :class:`numpy.ndarray`
The vertices of every graphlet (clique of the basis), in order of
decreasing weight.
mu : :class:`numpy.ndarray`
The weight of every graphlet.
See Also
--------
maximal_cliques: Maximal cliques, which yield the candidate graphlets
graph_tool.inference.OverlapBlockState: Overlapping stochastic block model
Notes
-----
The graphlet decomposition of Soufiani and Airoldi
[soufiani-graphlet-2012]_ models the edge weights as Poisson variables,
with the mean of the weight of edge :math:`e` given by
:math:`\lambda_e = \sum_c \mu_c [e\in c]`, a sum over overlapping
cliques :math:`c` (the graphlets) with weights :math:`\mu_c`. The
candidate cliques are found as follows: the maximal
cliques of the graph with the edges of weight at least a threshold
:math:`t` (initially the smallest weight) are candidates, and for each
of them the search is repeated in the subgraph of its edges heavier than
its lightest edge, with the next weight of its edges as the threshold;
candidates contained in another one with the same smallest edge weight
are discarded. The weights are then obtained by the
expectation-maximization (multiplicative) updates of the maximum
likelihood estimate,
.. math::
\mu_c \leftarrow \frac{\mu_c}{|E_c|}\sum_{e\in c}\frac{w_e}{\lambda_e},
from :math:`\mu_c = 1`, where :math:`|E_c|` is the number of edges of
clique :math:`c`. Isolated vertices are not part of any graphlet. The time
is dominated by the enumeration of maximal cliques, which is exponential in
the worst case, plus :math:`O(n_{\text{iter}}\sum_c |E_c|)` for the
projection.
Examples
--------
>>> g = gt.collection.data["lesmis"]
>>> cliques, mu = gt.graphlet_decomposition(g, g.ep.value)
>>> print(len(cliques), cliques[0], mu[0])
143 [11 26 55] 14.417990123...
References
----------
.. [soufiani-graphlet-2012] Hossein Azari Soufiani and Edoardo M.
Airoldi, "Graphlet decomposition of a weighted network", Proceedings of
the Fifteenth International Conference on Artificial Intelligence and
Statistics, PMLR 22, 54-63 (2012), :arxiv:`1203.2821`
"""
_check_prop_scalar(weight, "weight")
if weight.fa.size > 0 and weight.fa.min() < 0:
raise ValueError("The edge weights must be nonnegative.")
u = GraphView(g, directed=False)
if label_parallel_edges(u, mark_only=True).fa.max(initial=0) > 0:
raise ValueError("The graph must not have parallel edges.")
cs, thr, mu = libgraph_tool_structure.graphlets(u,
weight._get_any(),
int(niter))
order = numpy.argsort(-mu, kind="stable")
return [numpy.asarray(cs[i]) for i in order], mu[order]
from .. flow import libgraph_tool_flow