# Ticket #12816: trac_12816-v2.patch

File trac_12816-v2.patch, 96.6 KB (added by ncohen, 9 years ago)
• ## sage/graphs/cliquer.pyx

# HG changeset patch
# User Nathann Cohen <nathann.cohen@gmail.com>
# Date 1333885363 -7200
# Node ID bbe42450c96129ac7023194143a935484e79a5a1
# Parent  8e6696c1dc1066018e35ab263eb9c15a29976c1a
Massive amount of documentation in the Graph files. The main addition is a list of methods at the top of our three main graph files

diff --git a/sage/graphs/cliquer.pyx b/sage/graphs/cliquer.pyx
 a - Jeroen Demeyer (2011-05-06): Make cliquer interruptible (#11252) Methods ------- """ #*****************************************************************************
• ## sage/graphs/convexity_properties.pyx

diff --git a/sage/graphs/convexity_properties.pyx b/sage/graphs/convexity_properties.pyx
 a r""" Convexity properties of graphs This class gathers the algorithms related to convexity in a graph. This class gathers the algorithms related to convexity in a graph. It implements the following methods: AUTHOR: Nathann Cohen .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:ConvexityProperties.hull | Returns the convex hull of a set of vertices :meth:ConvexityProperties.hull_number | Computes the hull number of a graph and a corresponding generating set. These methods can be used through the :class:ConvexityProperties object returned by :meth:Graph.convexity_properties. AUTHORS: -  Nathann Cohen Methods ------- """ include "../misc/bitset.pxi" * This class is useful if you compute the convex hulls of many sets in the same graph, or if you want to compute the hull number itself as it involves many calls to :meth:hull * Using this class on non-conected graphs is a waste of space and efficiency ! If your graph is disconnected, the best for you is to deal independently with each connected component, whatever you are ... ValueError: This is currenly implemented for Graphs only.Only minor updates are needed if you want to makeit support DiGraphs too. """ def __init__(self, G): r""" Constructor raise ValueError("This is currenly implemented for Graphs only."+ "Only minor updates are needed if you want to make"+ "it support DiGraphs too.") # Cached number of vertices cdef int n = G.order() self._n = n # Filling it for 0<= k < n: if ((d_i[self._list_integers_to_vertices[k]] + d_j[self._list_integers_to_vertices[k]]) + d_j[self._list_integers_to_vertices[k]]) == d_ij): bitset_add(p_bitset[0], k) # Next bitset ! p_bitset = p_bitset + 1 def __destruct__(self): r""" Destructor p_bitset = p_bitset + 1 sage_free(self._cache_hull_pairs) cdef list _vertices_to_integers(self, vertices): r""" Converts a list of vertices to a list of integers with the cached data. count = bitset_len(hull) while True: # Iterating over all the elements in the cache p_bitset = self._cache_hull_pairs # Next bitset ! p_bitset = p_bitset + 1 tmp_count = bitset_len(hull) # If we added nothing new during the previous loop, our set is # convex ! if tmp_count == count: return # Otherwise, update and back to the loop count = tmp_count sage: CP.hull([1,3]) [1, 2, 3] """ cdef bitset_t bs cdef bitset_t bs bitset_init(bs, self._n) bitset_set_first_n(bs, 0) Given a bitset whose hull is not the whole set, greedily add vertices and stop before its hull is the whole set. NOTE: NOTE: * Counting the bits at each turn is not the best way... """ self._bitset_convex_hull(tmp) if bitset_len(tmp) < self._n: bitset_add(bs, i) cpdef hull_number(self, value_only = True, verbose = False): r""" Computes the hull number and a correspondin generating set. Computes the hull number and a corresponding generating set. The hull number hn(G) of a graph G is the cardinality of a smallest set of vertices S such that h(S)=V(G). INPUT: * value_only (boolean) -- whether to return only the hull number (default) or a minimum set whose convex hull is the whole graph. * value_only (boolean) -- whether to return only the hull number (default) or a minimum set whose convex hull is the whole graph. * verbose (boolean) -- whether to display information on the LP. Mathematical and computer modelling vol. 17 n11 pp.89--95, 1993 """ cdef int i cdef list constraint # temporary variable to add constraints to the LP return self._n else: return self._list_integers_to_vertices cdef GenericBackend p = get_solver(constraint_generation = True) # Minimization bitset_set_first_n(current_hull,1) while True: # Greedily increase it to obtain a better constraint self._greedy_increase(current_hull)
• ## sage/graphs/digraph.py

diff --git a/sage/graphs/digraph.py b/sage/graphs/digraph.py
 a Directed graphs This module implements functions and operations involving directed graphs. graphs. Here is what they can do **Graph basic operations:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~DiGraph.layout_acyclic_dummy | Computes a (dummy) ranked layout so that all edges point upward. :meth:~DiGraph.layout_acyclic | Computes a ranked layout so that all edges point upward. :meth:~DiGraph.reverse | Returns a copy of digraph with edges reversed in direction. :meth:~DiGraph.out_degree_sequence | Return the outdegree sequence :meth:~DiGraph.out_degree_iterator | Same as degree_iterator, but for out degree. :meth:~DiGraph.out_degree | Same as degree, but for out degree. :meth:~DiGraph.in_degree_sequence | Return the indegree sequence of this digraph. :meth:~DiGraph.in_degree_iterator | Same as degree_iterator, but for in degree. :meth:~DiGraph.in_degree | Same as degree, but for in-degree. :meth:~DiGraph.neighbors_out | Returns the list of the out-neighbors of a given vertex. :meth:~DiGraph.neighbor_out_iterator | Returns an iterator over the out-neighbors of a given vertex. :meth:~DiGraph.neighbors_in | Returns the list of the in-neighbors of a given vertex. :meth:~DiGraph.neighbor_in_iterator | Returns an iterator over the in-neighbors of vertex. :meth:~DiGraph.outgoing_edges | Returns a list of edges departing from vertices. :meth:~DiGraph.outgoing_edge_iterator | Return an iterator over all departing edges from vertices :meth:~DiGraph.incoming_edges | Returns a list of edges arriving at vertices. :meth:~DiGraph.incoming_edge_iterator | Return an iterator over all arriving edges from vertices :meth:~DiGraph.to_undirected | Returns an undirected version of the graph. :meth:~DiGraph.to_directed | Since the graph is already directed, simply returns a copy of itself. :meth:~DiGraph.is_directed | Since digraph is directed, returns True. :meth:~DiGraph.dig6_string | Returns the dig6 representation of the digraph as an ASCII string. **Paths and cycles:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~DiGraph.all_paths_iterator | Returns an iterator over the paths of self. The paths are :meth:~DiGraph.all_simple_paths | Returns a list of all the simple paths of self starting :meth:~DiGraph.all_cycles_iterator | Returns an iterator over all the cycles of self starting :meth:~DiGraph.all_simple_cycles | Returns a list of all simple cycles of self. **Connectivity:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~DiGraph.is_strongly_connected | Returns whether the current DiGraph is strongly connected. :meth:~DiGraph.strongly_connected_components_digraph | Returns the digraph of the strongly connected components :meth:~DiGraph.strongly_connected_components_subgraphs | Returns the strongly connected components as a list of subgraphs. :meth:~DiGraph.strongly_connected_component_containing_vertex | Returns the strongly connected component containing a given vertex :meth:~DiGraph.strongly_connected_components | Returns the list of strongly connected components. **Acyclicity:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~DiGraph.is_directed_acyclic | Returns whether the digraph is acyclic or not. :meth:~DiGraph.level_sets | Returns the level set decomposition of the digraph. :meth:~DiGraph.topological_sort_generator | Returns a list of all topological sorts of the digraph if it is acyclic :meth:~DiGraph.topological_sort | Returns a topological sort of the digraph if it is acyclic **Hard stuff:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~DiGraph.feedback_edge_set | Computes the minimum feedback edge (arc) set of a digraph :meth:~DiGraph.feedback_vertex_set | Computes the minimum feedback vertex set of a digraph. Methods ------- """ from sage.rings.integer import Integer A digraph or directed graph is a set of vertices connected by oriented edges. For more information, see the Wikipedia article on digraphs Wikipedia article on digraphs _. One can very easily create a directed graph in Sage by typing:: sage: g = DiGraph() By typing the name of the digraph, one can get some basic information def in_degree_sequence(self): r""" Return the indegree sequence of this digraph. Return the indegree sequence. EXAMPLES: def layout_acyclic(self, **options): """ Computes a ranked layout so that all edges point upward. To this end, the heights of the vertices are set according to the level set decomposition of the graph (see :meth:.level_sets). This is achieved by calling graphviz and dot2tex if available (see :meth:.layout_acyclic_graphviz), and using a random horizontal placement of the vertices otherwise (see :meth:.layout_acyclic_dummy). Non acyclic graphs are partially supported by graphviz, which then chooses some edges to point down. Computes a ranked layout so that all edges point upward. To this end, the heights of the vertices are set according to the level set decomposition of the graph (see :meth:.level_sets). This is achieved by calling graphviz and dot2tex if available (see :meth:.layout_acyclic_graphviz), and using a random horizontal placement of the vertices otherwise (see :meth:.layout_acyclic_dummy). Non acyclic graphs are partially supported by graphviz, which then chooses some edges to point down. EXAMPLES:: def level_sets(self): """ Returns the level set decomposition of the digraph. OUTPUT: - a list of non empty lists of vertices of this graph Returns the level set decomposition of the graph. This a list l such that the level l[i] contains all the vertices having all their predecessors in the levels l[j] for j
• ## sage/graphs/generic_graph.py

diff --git a/sage/graphs/generic_graph.py b/sage/graphs/generic_graph.py
 a r""" Generic graphs This module implements the base class for graphs and digraphs, and methods that can be applied on both. This module implements the base class for graphs and digraphs, and methods that can be applied on both. Here is what it can do: **Basic Graph operations:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~GenericGraph.networkx_graph | Creates a new NetworkX graph from the Sage graph :meth:~GenericGraph.adjacency_matrix | Returns the adjacency matrix of the (di)graph. :meth:~GenericGraph.incidence_matrix | Returns an incidence matrix of the (di)graph :meth:~GenericGraph.weighted_adjacency_matrix | Returns the weighted adjacency matrix of the graph :meth:~GenericGraph.kirchhoff_matrix | Returns the Kirchhoff matrix (a.k.a. the Laplacian) of the graph. :meth:~GenericGraph.get_boundary | Returns the boundary of the (di)graph. :meth:~GenericGraph.set_boundary | Sets the boundary of the (di)graph. :meth:~GenericGraph.has_loops | Returns whether there are loops in the (di)graph. :meth:~GenericGraph.allows_loops | Returns whether loops are permitted in the (di)graph. :meth:~GenericGraph.allow_loops | Changes whether loops are permitted in the (di)graph. :meth:~GenericGraph.loops | Returns any loops in the (di)graph. :meth:~GenericGraph.has_multiple_edges | Returns whether there are multiple edges in the (di)graph. :meth:~GenericGraph.allows_multiple_edges | Returns whether multiple edges are permitted in the (di)graph. :meth:~GenericGraph.allow_multiple_edges | Changes whether multiple edges are permitted in the (di)graph. :meth:~GenericGraph.multiple_edges | Returns any multiple edges in the (di)graph. :meth:~GenericGraph.name | Returns or sets the graph's name. :meth:~GenericGraph.weighted | Whether the (di)graph is to be considered as a weighted (di)graph. :meth:~GenericGraph.antisymmetric | Tests whether the graph is antisymmetric :meth:~GenericGraph.density | Returns the density :meth:~GenericGraph.order | Returns the number of vertices. :meth:~GenericGraph.size | Returns the number of edges. :meth:~GenericGraph.add_vertex | Creates an isolated vertex. :meth:~GenericGraph.add_vertices | Add vertices to the (di)graph from an iterable container :meth:~GenericGraph.delete_vertex | Deletes a vertex, removing all incident edges. :meth:~GenericGraph.delete_vertices | Remove vertices from the (di)graph taken from an iterable container of vertices. :meth:~GenericGraph.has_vertex | Return True if vertex is one of the vertices of this graph. :meth:~GenericGraph.random_vertex | Returns a random vertex of self. :meth:~GenericGraph.random_edge | Returns a random edge of self. :meth:~GenericGraph.vertex_boundary | Returns a list of all vertices in the external boundary of vertices1, intersected with vertices2. :meth:~GenericGraph.set_vertices | Associate arbitrary objects with each vertex :meth:~GenericGraph.set_vertex | Associate an arbitrary object with a vertex. :meth:~GenericGraph.get_vertex | Retrieve the object associated with a given vertex. :meth:~GenericGraph.get_vertices | Return a dictionary of the objects associated to each vertex. :meth:~GenericGraph.loop_vertices | Returns a list of vertices with loops. :meth:~GenericGraph.vertex_iterator | Returns an iterator over the vertices. :meth:~GenericGraph.neighbor_iterator | Return an iterator over neighbors of vertex. :meth:~GenericGraph.vertices | Return a list of the vertices. :meth:~GenericGraph.neighbors | Return a list of neighbors (in and out if directed) of vertex. :meth:~GenericGraph.merge_vertices | Merge vertices. :meth:~GenericGraph.add_edge | Adds an edge from u and v. :meth:~GenericGraph.add_edges | Add edges from an iterable container. :meth:~GenericGraph.subdivide_edge | Subdivides an edge k times. :meth:~GenericGraph.subdivide_edges | Subdivides k times edges from an iterable container. :meth:~GenericGraph.delete_edge | Delete the edge from u to v :meth:~GenericGraph.delete_edges | Delete edges from an iterable container. :meth:~GenericGraph.delete_multiedge | Deletes all edges from u and v. :meth:~GenericGraph.set_edge_label | Set the edge label of a given edge. :meth:~GenericGraph.has_edge | Returns True if (u, v) is an edge, False otherwise. :meth:~GenericGraph.edges | Return a list of edges. :meth:~GenericGraph.edge_boundary | Returns a list of edges (u,v,l) with u in vertices1 :meth:~GenericGraph.edge_iterator | Returns an iterator over edges. :meth:~GenericGraph.edges_incident | Returns incident edges to some vertices. :meth:~GenericGraph.edge_label | Returns the label of an edge. :meth:~GenericGraph.edge_labels | Returns a list of edge labels. :meth:~GenericGraph.remove_multiple_edges | Removes all multiple edges, retaining one edge for each. :meth:~GenericGraph.remove_loops | Removes loops on vertices in vertices. If vertices is None, removes all loops. :meth:~GenericGraph.loop_edges | Returns a list of all loops in the graph. :meth:~GenericGraph.number_of_loops | Returns the number of edges that are loops. :meth:~GenericGraph.clear | Empties the graph of vertices and edges and removes name, boundary, associated objects, and position information. :meth:~GenericGraph.degree | Gives the degree (in + out for digraphs) of a vertex or of vertices. :meth:~GenericGraph.average_degree | Returns the average degree of the graph. :meth:~GenericGraph.degree_histogram | Returns a list, whose ith entry is the frequency of degree i. :meth:~GenericGraph.degree_iterator | Returns an iterator over the degrees of the (di)graph. :meth:~GenericGraph.degree_sequence | Return the degree sequence of this (di)graph. :meth:~GenericGraph.random_subgraph | Return a random subgraph that contains each vertex with prob. p. :meth:~GenericGraph.add_cycle | Adds a cycle to the graph with the given vertices. :meth:~GenericGraph.add_path | Adds a cycle to the graph with the given vertices. :meth:~GenericGraph.complement | Returns the complement of the (di)graph. :meth:~GenericGraph.line_graph | Returns the line graph of the (di)graph. :meth:~GenericGraph.to_simple | Returns a simple version of itself (i.e., undirected and loops and multiple edges are removed). :meth:~GenericGraph.disjoint_union | Returns the disjoint union of self and other. :meth:~GenericGraph.union | Returns the union of self and other. :meth:~GenericGraph.relabel | Relabels the vertices of self :meth:~GenericGraph.degree_to_cell | Returns the number of edges from vertex to an edge in cell. :meth:~GenericGraph.subgraph | Returns the subgraph containing the given vertices and edges. :meth:~GenericGraph.is_subgraph | Tests whether self is a subgraph of other. **Graph products:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~GenericGraph.cartesian_product | Returns the Cartesian product of self and other. :meth:~GenericGraph.tensor_product | Returns the tensor product, also called the categorical product, of self and other. :meth:~GenericGraph.lexicographic_product | Returns the lexicographic product of self and other. :meth:~GenericGraph.strong_product | Returns the strong product of self and other. :meth:~GenericGraph.disjunctive_product | Returns the disjunctive product of self and other. **Paths and cycles:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~GenericGraph.eulerian_orientation | Returns a DiGraph which is an Eulerian orientation of the current graph. :meth:~GenericGraph.eulerian_circuit | Return a list of edges forming an eulerian circuit if one exists. :meth:~GenericGraph.cycle_basis | Returns a list of cycles which form a basis of the cycle space of self. :meth:~GenericGraph.interior_paths | Returns an exhaustive list of paths (also lists) through only interior vertices from vertex start to vertex end in the (di)graph. :meth:~GenericGraph.all_paths | Returns a list of all paths (also lists) between a pair of vertices in the (di)graph. **Linear algebra:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~GenericGraph.spectrum | Returns a list of the eigenvalues of the adjacency matrix. :meth:~GenericGraph.eigenvectors | Returns the *right* eigenvectors of the adjacency matrix of the graph. :meth:~GenericGraph.eigenspaces | Returns the *right* eigenspaces of the adjacency matrix of the graph. **Some metrics:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~GenericGraph.cluster_triangles | Returns the number of triangles for nbunch of vertices as a dictionary keyed by vertex. :meth:~GenericGraph.clustering_average | Returns the average clustering coefficient. :meth:~GenericGraph.clustering_coeff | Returns the clustering coefficient for each vertex in nbunch :meth:~GenericGraph.cluster_transitivity | Returns the transitivity (fraction of transitive triangles) of the graph. :meth:~GenericGraph.szeged_index | Returns the Szeged index of the graph. **Automorphism group:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~GenericGraph.coarsest_equitable_refinement | Returns the coarsest partition which is finer than the input partition, and equitable with respect to self. :meth:~GenericGraph.automorphism_group | Returns the largest subgroup of the automorphism group of the (di)graph whose orbit partition is finer than the partition given. :meth:~GenericGraph.is_vertex_transitive | Returns whether the automorphism group of self is transitive within the partition provided :meth:~GenericGraph.is_isomorphic | Tests for isomorphism between self and other. :meth:~GenericGraph.canonical_label | Returns the unique graph on \{0,1,...,n-1\} ( n = self.order() ) which 1) is isomorphic to self 2) is invariant in the isomorphism class. **Graph properties:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~GenericGraph.is_eulerian | Return true if the graph has a (closed) tour that visits each edge exactly once. :meth:~GenericGraph.is_tree | Return True if the graph is a tree. :meth:~GenericGraph.is_forest | Return True if the graph is a forest, i.e. a disjoint union of trees. :meth:~GenericGraph.is_overfull | Tests whether the current graph is overfull. :meth:~GenericGraph.is_planar | Tests whether the graph is planar. :meth:~GenericGraph.is_circular_planar | Tests whether the graph is circular planar (outerplanar) :meth:~GenericGraph.is_regular | Return True if this graph is (k-)regular. :meth:~GenericGraph.is_chordal | Tests whether the given graph is chordal. :meth:~GenericGraph.is_interval | Check whether self is an interval graph :meth:~GenericGraph.is_gallai_tree | Returns whether the current graph is a Gallai tree. :meth:~GenericGraph.is_clique | Tests whether a set of vertices is a clique :meth:~GenericGraph.is_independent_set | Tests whether a set of vertices is an independent set :meth:~GenericGraph.is_transitively_reduced | Tests whether the digraph is transitively reduced. :meth:~GenericGraph.is_equitable | Checks whether the given partition is equitable with respect to self. **Traversals:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~GenericGraph.breadth_first_search | Returns an iterator over the vertices in a breadth-first ordering. :meth:~GenericGraph.depth_first_search | Returns an iterator over the vertices in a depth-first ordering. :meth:~GenericGraph.lex_BFS | Performs a Lex BFS on the graph. **Distances:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~GenericGraph.distance | Returns the (directed) distance from u to v in the (di)graph :meth:~GenericGraph.distance_all_pairs | Returns the distances between all pairs of vertices. :meth:~GenericGraph.distances_distribution | Returns the distances distribution of the (di)graph in a dictionary. :meth:~GenericGraph.eccentricity | Return the eccentricity of vertex (or vertices) v. :meth:~GenericGraph.radius | Returns the radius of the (di)graph. :meth:~GenericGraph.center | Returns the set of vertices in the center of the graph :meth:~GenericGraph.diameter | Returns the largest distance between any two vertices. :meth:~GenericGraph.distance_graph | Returns the graph on the same vertex set as the original graph but vertices are adjacent in the returned graph if and only if they are at specified distances in the original graph. :meth:~GenericGraph.girth | Computes the girth of the graph. :meth:~GenericGraph.periphery | Returns the set of vertices in the periphery :meth:~GenericGraph.shortest_path | Returns a list of vertices representing some shortest path from u to v :meth:~GenericGraph.shortest_path_length | Returns the minimal length of paths from u to v :meth:~GenericGraph.shortest_paths | Returns a dictionary associating to each vertex v a shortest path from u to v, if it exists. :meth:~GenericGraph.shortest_path_lengths | Returns a dictionary of shortest path lengths keyed by targets that are connected by a path from u. :meth:~GenericGraph.shortest_path_all_pairs | Computes a shortest path between each pair of vertices. :meth:~GenericGraph.wiener_index | Returns the Wiener index of the graph. :meth:~GenericGraph.average_distance | Returns the average distance between vertices of the graph. **Flows, connectivity, trees:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~GenericGraph.is_connected | Tests whether the (di)graph is connected. :meth:~GenericGraph.connected_components | Returns the list of connected components :meth:~GenericGraph.connected_components_number | Returns the number of connected components. :meth:~GenericGraph.connected_components_subgraphs | Returns a list of connected components as graph objects. :meth:~GenericGraph.connected_component_containing_vertex | Returns a list of the vertices connected to vertex. :meth:~GenericGraph.blocks_and_cut_vertices | Computes the blocks and cut vertices of the graph. :meth:~GenericGraph.edge_cut | Returns a minimum edge cut between vertices s and t :meth:~GenericGraph.vertex_cut | Returns a minimum vertex cut between non-adjacent vertices s and t :meth:~GenericGraph.flow | Returns a maximum flow in the graph from x to y :meth:~GenericGraph.edge_disjoint_paths | Returns a list of edge-disjoint paths between two vertices :meth:~GenericGraph.vertex_disjoint_paths | Returns a list of vertex-disjoint paths between two vertices as given by Menger's theorem. :meth:~GenericGraph.edge_connectivity | Returns the edge connectivity of the graph. :meth:~GenericGraph.vertex_connectivity | Returns the vertex connectivity of the graph. :meth:~GenericGraph.transitive_closure | Computes the transitive closure of a graph and returns it. :meth:~GenericGraph.transitive_reduction | Returns a transitive reduction of a graph. :meth:~GenericGraph.min_spanning_tree | Returns the edges of a minimum spanning tree. :meth:~GenericGraph.spanning_trees_count | Returns the number of spanning trees in a graph. **Plot/embedding-related methods:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~GenericGraph.set_embedding | Sets a combinatorial embedding dictionary to _embedding attribute. :meth:~GenericGraph.get_embedding | Returns the attribute _embedding if it exists. :meth:~GenericGraph.check_embedding_validity | Checks whether an _embedding attribute is well defined :meth:~GenericGraph.get_pos | Returns the position dictionary :meth:~GenericGraph.check_pos_validity | Checks whether pos specifies two (resp. 3) coordinates for every vertex (and no more vertices). :meth:~GenericGraph.set_pos | Sets the position dictionary. :meth:~GenericGraph.set_planar_positions | Compute a planar layout for self using Schnyder's algorithm :meth:~GenericGraph.layout_planar | Uses Schnyder's algorithm to compute a planar layout for self. :meth:~GenericGraph.is_drawn_free_of_edge_crossings | Tests whether the position dictionary gives a planar embedding. :meth:~GenericGraph.latex_options | Returns an instance of :class:~sage.graphs.graph_latex.GraphLatex for the graph. :meth:~GenericGraph.set_latex_options | Sets multiple options for rendering a graph with LaTeX. :meth:~GenericGraph.layout | Returns a layout for the vertices of this graph. :meth:~GenericGraph.layout_spring | Computes a spring layout for this graph :meth:~GenericGraph.layout_ranked | Computes a ranked layout for this graph :meth:~GenericGraph.layout_extend_randomly | Extends randomly a partial layout :meth:~GenericGraph.layout_circular | Computes a circular layout for this graph :meth:~GenericGraph.layout_tree | Computes an ordered tree layout for this graph, which should be a tree (no non-oriented cycles). :meth:~GenericGraph.layout_graphviz | Calls graphviz to compute a layout of the vertices of this graph. :meth:~GenericGraph.graphplot | Returns a GraphPlot object. :meth:~GenericGraph.plot | Returns a graphics object representing the (di)graph. :meth:~GenericGraph.show | Shows the (di)graph. :meth:~GenericGraph.plot3d | Plot a graph in three dimensions. :meth:~GenericGraph.show3d | Plots the graph using Tachyon, and shows the resulting plot. :meth:~GenericGraph.graphviz_string | Returns a representation in the dot language. :meth:~GenericGraph.graphviz_to_file_named | Write a representation in the dot in a file. **Algorithmically hard stuff:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~GenericGraph.steiner_tree | Returns a tree of minimum weight connecting the given set of vertices. :meth:~GenericGraph.edge_disjoint_spanning_trees | Returns the desired number of edge-disjoint spanning trees/arborescences. :meth:~GenericGraph.multiway_cut | Returns a minimum edge multiway cut :meth:~GenericGraph.max_cut | Returns a maximum edge cut of the graph. :meth:~GenericGraph.longest_path | Returns a longest path of self. :meth:~GenericGraph.traveling_salesman_problem | Solves the traveling salesman problem (TSP) :meth:~GenericGraph.is_hamiltonian | Tests whether the current graph is Hamiltonian. :meth:~GenericGraph.hamiltonian_cycle | Returns a Hamiltonian cycle/circuit of the current graph/digraph :meth:~GenericGraph.multicommodity_flow | Solves a multicommodity flow problem. :meth:~GenericGraph.disjoint_routed_paths | Returns a set of disjoint routed paths. :meth:~GenericGraph.dominating_set | Returns a minimum dominating set of the graph :meth:~GenericGraph.subgraph_search | Returns a copy of G in self. :meth:~GenericGraph.subgraph_search_count | Returns the number of labelled occurences of G in self. :meth:~GenericGraph.subgraph_search_iterator | Returns an iterator over the labelled copies of G in self. :meth:~GenericGraph.characteristic_polynomial | Returns the characteristic polynomial of the adjacency matrix of the (di)graph. :meth:~GenericGraph.genus | Returns the minimal genus of the graph. :meth:~GenericGraph.trace_faces | A helper function for finding the genus of a graph. **Graph stuff that should not be in this file:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~GenericGraph.minimum_outdegree_orientation | Returns an orientation of self with the smallest possible maximum outdegree :meth:~GenericGraph.matching | Returns a maximum weighted matching of the graph :meth:~GenericGraph.maximum_average_degree | Returns the Maximum Average Degree (MAD) of the current graph. :meth:~GenericGraph.cores | Returns the core number for each vertex in an ordered list. Methods ------- """ from sage.misc.decorators import options # Nice defaults for plotting arrays of graphs (see sage.misc.functional.show) graphics_array_defaults =  {'layout': 'circular', 'vertex_size':50, 'vertex_labels':False, 'graph_border':True} def __init__(self): r""" Every graph carries a dictionary of options, which is set def __add__(self, other_graph): """ Returns the disjoint union of self and other. If there are common vertices to both, they will be renamed. EXAMPLES:: EXAMPLES:: sage: G = graphs.CycleGraph(3) sage: H = graphs.CycleGraph(4) sage: J = G + H; J Comparison of self and other. For equality, must be in the same class, have the same settings for loops and multiedges, output the same vertex list (in order) and the same adjacency matrix. Note that this is _not_ an isomorphism test. EXAMPLES:: EXAMPLES:: sage: G = graphs.EmptyGraph() sage: H = Graph() sage: G == H def adjacency_matrix(self, sparse=None, boundary_first=False): """ Returns the adjacency matrix of the (di)graph. Each vertex is represented by its position in the list returned by the vertices() function. Returns the adjacency matrix of the (di)graph. Each vertex is represented by its position in the list returned by the vertices() function. The matrix returned is over the integers. If a different ring is desired, use either the change_ring function or the matrix function. INPUT: INPUT: -  sparse - whether to represent with a sparse matrix -  boundary_first - whether to represent the boundary vertices in the upper left block EXAMPLES:: EXAMPLES:: sage: G = graphs.CubeGraph(4) sage: G.adjacency_matrix() [0 1 1 0 1 0 0 0 1 0 0 0 0 0 0 0] [0 0 0 0 0 1 0 0 0 1 0 0 1 0 0 1] [0 0 0 0 0 0 1 0 0 0 1 0 1 0 0 1] [0 0 0 0 0 0 0 1 0 0 0 1 0 1 1 0] :: :: sage: matrix(GF(2),G) # matrix over GF(2) [0 1 1 0 1 0 0 0 1 0 0 0 0 0 0 0] [1 0 0 1 0 1 0 0 0 1 0 0 0 0 0 0] def incidence_matrix(self, sparse=True): """ Returns an incidence matrix of the (di)graph. Each row is a vertex, and each column is an edge. Note that in the case of graphs, there is a choice of orientation for each edge. EXAMPLES:: Returns the incidence matrix of the (di)graph. Each row is a vertex, and each column is an edge. Note that in the case of graphs, there is a choice of orientation for each edge. EXAMPLES:: sage: G = graphs.CubeGraph(3) sage: G.incidence_matrix() [-1 -1 -1  0  0  0  0  0  0  0  0  0] [ 0  0  0  1  0  0  0  0  0  1 -1  0] [ 0  0  0  0  0  1  0  0  1  0  0 -1] [ 0  0  0  0  0  0  0  1  0  0  1  1] :: :: sage: D = DiGraph( { 0: [1,2,3], 1: [0,2], 2: [3], 3: [4], 4: [0,5], 5: [1] } ) sage: D.incidence_matrix() [-1 -1 -1  0  0  0  0  0  1  1] def weighted_adjacency_matrix(self, sparse=True, boundary_first=False): """ Returns the weighted adjacency matrix of the graph. Each vertex is represented by its position in the list returned by the vertices() function. EXAMPLES:: Returns the weighted adjacency matrix of the graph. Each vertex is represented by its position in the list returned by the vertices() function. EXAMPLES:: sage: G = Graph(sparse=True, weighted=True) sage: G.add_edges([(0,1,1),(1,2,2),(0,2,3),(0,3,4)]) sage: M = G.weighted_adjacency_matrix(); M The following doctest verifies that \#4888 is fixed:: sage: G = DiGraph({0:{}, 1:{0:1}, 2:{0:1}}, weighted = True,sparse=True) sage: G.weighted_adjacency_matrix() sage: G.weighted_adjacency_matrix() [0 0 0] [1 0 0] [1 0 0] def kirchhoff_matrix(self, weighted=None, indegree=True, normalized=False, **kwds): """ Returns the Kirchhoff matrix (a.k.a. the Laplacian) of the graph. The Kirchhoff matrix is defined to be D - M, where D is the diagonal degree matrix (each diagonal entry is the degree of the corresponding vertex), and M is the adjacency matrix. def set_embedding(self, embedding): """ Sets a combinatorial embedding dictionary to _embedding attribute. Sets a combinatorial embedding dictionary to _embedding attribute. Dictionary is organized with vertex labels as keys and a list of each vertex's neighbors in clockwise order. Dictionary is error-checked for validity. INPUT: INPUT: -  embedding - a dictionary EXAMPLES:: EXAMPLES:: sage: G = graphs.PetersenGraph() sage: G.set_embedding({0: [1, 5, 4], 1: [0, 2, 6], 2: [1, 3, 7], 3: [8, 2, 4], 4: [0, 9, 3], 5: [0, 8, 7], 6: [8, 1, 9], 7: [9, 2, 5], 8: [3, 5, 6], 9: [4, 6, 7]}) sage: G.set_embedding({'s': [1, 5, 4], 1: [0, 2, 6], 2: [1, 3, 7], 3: [8, 2, 4], 4: [0, 9, 3], 5: [0, 8, 7], 6: [8, 1, 9], 7: [9, 2, 5], 8: [3, 5, 6], 9: [4, 6, 7]}) self._embedding = embedding else: raise Exception('embedding is not valid for %s'%self) def get_embedding(self): """ Returns the attribute _embedding if it exists. _embedding is a dictionary organized with vertex labels as keys and a list of each vertex's neighbors in clockwise order. Returns the attribute _embedding if it exists. _embedding is a dictionary organized with vertex labels as keys and a list of each vertex's neighbors in clockwise order. Error-checked to insure valid embedding is returned. EXAMPLES:: EXAMPLES:: sage: G = graphs.PetersenGraph() sage: G.genus() 1 return self._embedding else: raise Exception('%s has been modified and the embedding is no longer valid.'%self) def check_embedding_validity(self, embedding=None): """ Checks whether an _embedding attribute is defined on self and if so, checks for accuracy. Returns True if everything is okay, False otherwise. Checks whether an _embedding attribute is well defined. If the _embedding attribute exists, it is checked for accuracy. Returns True if everything is okay, False otherwise. If embedding=None will test the attribute _embedding. EXAMPLES:: EXAMPLES:: sage: d = {0: [1, 5, 4], 1: [0, 2, 6], 2: [1, 3, 7], 3: [8, 2, 4], 4: [0, 9, 3], 5: [0, 8, 7], 6: [8, 1, 9], 7: [9, 2, 5], 8: [3, 5, 6], 9: [4, 6, 7]} sage: G = graphs.PetersenGraph() sage: G.check_embedding_validity(d) if len(edges) > 1: multi_edges += edges return multi_edges def name(self, new=None): """ INPUT: Returns or sets the graph's name. INPUT: - new - if not None, then this becomes the new name of the (di)graph. (if new == '', removes any name) EXAMPLES:: sage: d = {0: [1,4,5], 1: [2,6], 2: [3,7], 3: [4,8], 4: [9], 5: [7, 8], 6: [8,9], 7: [9]} sage: G = Graph(d); G Graph on 10 vertices def antisymmetric(self): r""" Returns True if the relation given by the graph is antisymmetric and False otherwise. Tests whether the graph is antisymmetric. A graph represents an antisymmetric relation if there being a path from a vertex x to a vertex y implies that there is not a path from y to x unless x=y. def spanning_trees_count(self, root_vertex=None): """ Returns the number of spanning trees in a graph. In the case of a digraph, counts the number of spanning out-trees rooted in root_vertex. Default is to set first vertex as root. Returns the number of spanning trees in a graph. In the case of a digraph, counts the number of spanning out-trees rooted in root_vertex.  Default is to set first vertex as root. This computation uses Kirchhoff's Matrix Tree Theorem [1] to calculate the number of spanning trees. For complete graphs on n vertices the def minimum_outdegree_orientation(self, use_edge_labels=False, solver=None, verbose=0): r""" Returns a DiGraph which is an orientation with the smallest possible maximum outdegree of the current graph. Returns an orientation of self with the smallest possible maximum outdegree. Given a Graph G, is is polynomial to compute an orientation D of the edges of G such that the maximum out-degree in def is_circular_planar(self, ordered=True, on_embedding=None, kuratowski=False, set_embedding=False, set_pos=False): """ Tests whether the graph is circular planar (outerplanar) A graph (with nonempty boundary) is circular planar if it has a planar embedding in which all boundary vertices can be drawn in order on a disc boundary, with all the interior vertices drawn inside the disc. Returns True if the graph is circular planar, and False if it is not. If kuratowski is set to True, then this function will return a tuple, with boolean first entry and second entry the Kuratowski require that the boundary can be drawn on the boundary of a disc, with all other vertices drawn inside (and no edge crossings). For more information, refer to reference [2]. This is a linear time algorithm to test for circular planarity. It relies on the edge-addition planarity algorithm due to Boyer-Myrvold. We accomplish linear time for circular planarity by modifying the graph before running the general planarity algorithm. REFERENCE: - [1] John M. Boyer and Wendy J. Myrvold, On the Cutting Edge: - [2] Kirkman, Emily A. O(n) Circular Planarity Testing. [Online] Available: soon! INPUT: INPUT: -  ordered - whether or not to consider the order of the boundary (set ordered=False to see if there is any possible boundary order that will satisfy circular planarity) -  kuratowski - if set to True, returns a tuple with boolean first entry and the Kuratowski subgraph or minor as the second entry. See notes above. -  on_embedding - the embedding dictionary to test planarity on. (i.e.: will return True or False only for the given embedding.) -  set_embedding - whether or not to set the instance field variable that contains a combinatorial embedding (clockwise ordering of neighbors at each vertex). This value will only be set if a circular planar embedding is found. It is stored as a Python dict: v1: [n1,n2,n3] where v1 is a vertex and n1,n2,n3 are its neighbors. -  set_pos - whether or not to set the position dictionary (for plotting) to reflect the combinatorial embedding. Note that this value will default to False if set_emb is set to False. Also, the position dictionary will only be updated if a circular planar embedding is found. EXAMPLES:: EXAMPLES:: sage: g439 = Graph({1:[5,7], 2:[5,6], 3:[6,7], 4:[5,6,7]}) sage: g439.set_boundary([1,2,3,4]) sage: g439.show(figsize=[2,2], vertex_labels=True, vertex_size=175) 5: [4, 2, 1], 6: [4, 3, 2], 7: [3, 4, 1]} Order matters:: sage: K23 = graphs.CompleteBipartiteGraph(2,3) sage: K23.set_boundary([0,1,2,3]) sage: K23.is_circular_planar() v = self.vertex_iterator().next() conn_verts = list(self.depth_first_search(v, ignore_direction=True)) return len(conn_verts) == self.num_verts() def connected_components(self): """ Returns the list of connected components. Returns a list of lists of vertices, each list representing a connected component. The list is ordered from largest to smallest component. EXAMPLES:: EXAMPLES:: sage: G = Graph( { 0 : [1, 3], 1 : [2], 2 : [3], 4 : [5, 6], 5 : [6] } ) sage: G.connected_components() [[0, 1, 2, 3], [4, 5, 6]] def blocks_and_cut_vertices(self): """ Computes the blocks and cut vertices of the graph. In the case of a digraph, this computation is done on the underlying graph. Computes the blocks and cut vertices of the graph. In the case of a digraph, this computation is done on the underlying graph. A cut vertex is one whose deletion increases the number of connected components. A block is a maximal induced subgraph which itself has no cut vertices. Two distinct blocks cannot overlap in more than a single cut vertex. OUTPUT: ( B, C ), where B is a list of blocks- each is OUTPUT: ( B, C ), where B is a list of blocks- each is a list of vertices and the blocks are the corresponding induced subgraphs-and C is a list of cut vertices. EXAMPLES:: EXAMPLES:: sage: graphs.PetersenGraph().blocks_and_cut_vertices() ([[6, 4, 9, 7, 5, 8, 3, 2, 1, 0]], []) sage: graphs.PathGraph(6).blocks_and_cut_vertices() ([[2, 1, 0], [4, 3, 0]], [0]) sage: graphs.StarGraph(3).blocks_and_cut_vertices() ([[1, 0], [2, 0], [3, 0]], [0]) TESTS:: sage: Graph(0).blocks_and_cut_vertices() def vertex_iterator(self, vertices=None): """ Returns an iterator over the given vertices. Returns False if not given a vertex, sequence, iterator or None. None is equivalent to a list of every vertex. Note that for v in G syntax is allowed. INPUT: Returns an iterator over the given vertices. Returns False if not given a vertex, sequence, iterator or None. None is equivalent to a list of every vertex. Note that for v in G syntax is allowed. INPUT: -  vertices - iterated vertices are these intersected with the vertices of the (di)graph EXAMPLES:: EXAMPLES:: sage: P = graphs.PetersenGraph() sage: for v in P.vertex_iterator(): ...    print v ... 8 9 :: :: sage: G = graphs.TetrahedralGraph() sage: for i in G: ...    print i def degree_iterator(self, vertices=None, labels=False): """ Returns an iterator over the degrees of the (di)graph. In the case of a digraph, the degree is defined as the sum of the in-degree and the out-degree, i.e. the total number of edges incident to a given vertex. INPUT: labels=False: returns an iterator over degrees. labels=True: returns an iterator over tuples (vertex, degree). Returns an iterator over the degrees of the (di)graph. In the case of a digraph, the degree is defined as the sum of the in-degree and the out-degree, i.e. the total number of edges incident to a given vertex. INPUT: - labels (boolean) -- if set to False (default) the method returns an iterator over degrees. Otherwise it returns an iterator over tuples (vertex, degree). -  vertices - if specified, restrict to this subset. def subgraph(self, vertices=None, edges=None, inplace=False, vertex_property=None, edge_property=None, algorithm=None): """ Returns the subgraph containing the given vertices and edges. If either vertices or edges are not specified, they are assumed to be all vertices or edges. If edges are not specified, returns the subgraph induced by the vertices. Returns the subgraph containing the given vertices and edges. If either vertices or edges are not specified, they are assumed to be all vertices or edges. If edges are not specified, returns the subgraph induced by the vertices. INPUT: This method also works on digraphs. .. SEEALSO:: - :meth:~GenericGraph.subgraph_search_count -- Counts the number of copies of a graph H inside of a graph G - :meth:~GenericGraph.subgraph_search_iterator -- Iterate on the copies of a graph H inside of a graph G ALGORITHM: Brute-force search. return self.subgraph(g) else: Gcopy=G.copy() Gcopy.relabel(g) Gcopy.relabel(g) return self.subgraph(vertices=Gcopy.vertices(), edges=Gcopy.edges()) return None This method also works on digraphs. .. SEEALSO:: - :meth:~GenericGraph.subgraph_search -- finds an subgraph isomorphic to H inside of a graph G - :meth:~GenericGraph.subgraph_search_iterator -- Iterate on the copies of a graph H inside of a graph G EXAMPLES: Counting the number of paths P_5 in a PetersenGraph:: This method also works on digraphs. .. SEEALSO:: - :meth:~GenericGraph.subgraph_search -- finds an subgraph isomorphic to H inside of a graph G - :meth:~GenericGraph.subgraph_search_count -- Counts the number of copies of a graph H inside of a graph G EXAMPLE: Iterating through all the labelled P_3 of P_5:: def is_clique(self, vertices=None, directed_clique=False): """ Returns True if the set vertices is a clique, False if not. A clique is a set of vertices such that there is an edge between any two vertices. INPUT: Tests whether a set of vertices is a clique A clique is a set of vertices such that there is an edge between any two vertices. INPUT: -  vertices - Vertices can be a single vertex or an iterable container of vertices, e.g. a list, set, graph, file or numeric array. If not passed, defaults to the entire graph. -  directed_clique - (default False) If set to False, only consider the underlying undirected graph. If set to True and the graph is directed, only return True if all possible edges in _both_ directions exist. EXAMPLES:: EXAMPLES:: sage: g = graphs.CompleteGraph(4) sage: g.is_clique([1,2,3]) True Returns True if the set vertices is an independent set, False if not. An independent set is a set of vertices such that there is no edge between any two vertices. INPUT: INPUT: -  vertices - Vertices can be a single vertex or an iterable container of vertices, e.g. a list, set, graph, file or numeric array. If not passed, defaults to the entire graph. EXAMPLES:: EXAMPLES:: sage: graphs.CycleGraph(4).is_independent_set([1,3]) True sage: graphs.CycleGraph(4).is_independent_set([1,2,3]) def is_subgraph(self, other): """ Tests whether self is a subgraph of other. EXAMPLES:: Tests whether self is an induced subgraph of other. .. WARNING:: Please note that this method does not check whether self contains a subgraph *isomorphic* to other, but only if it directly contains it as a subgraph ! This means that this method returns True only if the vertices of other are also vertices of self, and that the edges of other are equal to the edges of self between the vertices contained in other. .. SEEALSO:: If you are interested in the (possibly induced) subgraphs of self to other, you are looking for the following methods: - :meth:~GenericGraph.subgraph_search -- finds an subgraph isomorphic to H inside of a graph G - :meth:~GenericGraph.subgraph_search_count -- Counts the number of such copies. - :meth:~GenericGraph.subgraph_search_iterator -- Iterate over all the copies of H contained in G. EXAMPLES:: sage: P = graphs.PetersenGraph() sage: G = P.subgraph(range(6)) sage: G.is_subgraph(P) return other.subgraph(self_verts) == self ### Cluster def cluster_triangles(self, nbunch=None, with_labels=False): r""" Returns the number of triangles for nbunch of vertices as a dictionary keyed by vertex. The clustering coefficient of a graph is the fraction of possible triangles that are triangles, c_i = triangles_i / (k_i\*(k_i-1)/2) where k_i is the degree of vertex i, [1]. A coefficient for the whole graph is the average of the c_i. Transitivity is the fraction of all possible triangles which are triangles, T = 3\*triangles/triads, [HSSNX]_. INPUT: INPUT: -  nbunch - The vertices to inspect. If nbunch=None, returns data for all vertices in the graph REFERENCE: .. [HSSNX] Aric Hagberg, Dan Schult and Pieter Swart. NetworkX documentation. [Online] Available: https://networkx.lanl.gov/reference/networkx/ EXAMPLES:: EXAMPLES:: sage: (graphs.FruchtGraph()).cluster_triangles().values() [1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0] sage: (graphs.FruchtGraph()).cluster_triangles() bidirectional=True, weight_sum=None): """ Returns the minimal length of paths from u to v: if there is no path from u to v, returns Infinity. INPUT: Returns the minimal length of paths from u to v. If there is no path from u to v, returns Infinity. INPUT: -  by_weight - if False, uses a breadth first search. If True, takes edge weightings into account, using Dijkstra's algorithm. -  bidirectional - if True, the algorithm will expand vertices from u and v at the same time, making two spheres of half the usual radius. This generally doubles the speed (consider the total volume in each case). -  weight_sum - if False, returns the number of edges in the path. If True, returns the sum of the weights of these edges. Default behavior is to have the same value as by_weight. EXAMPLES:: EXAMPLES:: sage: D = graphs.DodecahedralGraph() sage: D.shortest_path_length(4, 9) 5 r""" Computes the transitive closure of a graph and returns it. The original graph is not modified. The transitive closure of a graph G has an edge (x,y) if and only if there is a path between x and y in G. The transitive closure of any strongly connected component of a graph is a complete graph. In particular, the transitive closure of a connected undirected graph is a complete graph. The transitive closure of a directed acyclic graph is a directed acyclic graph representing the full partial order. EXAMPLES:: EXAMPLES:: sage: g=graphs.PathGraph(4) sage: g.transitive_closure() Transitive closure of Path Graph: Graph on 4 vertices r""" Returns a transitive reduction of a graph. The original graph is not modified. A transitive reduction H of G has a path from x to y if and only if there was a path from x to y in G. Deleting any edge of H destroys this property. A transitive reduction is not unique in general. A def is_transitively_reduced(self): r""" Returns True if the digraph is transitively reduced and False otherwise. Tests whether the digraph is transitively reduced. A digraph is transitively reduced if it is equal to its transitive reduction. EXAMPLES:: sage: d = DiGraph({0:[1],1:[2],2:[3]}) sage: d.is_transitively_reduced() True def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the unique graph on \{0,1,...,n-1\} ( n = self.order() ) which Returns the unique graph on \{0,1,...,n-1\} ( n = self.order() ) which - is isomorphic to self,
• ## sage/graphs/graph.py

diff --git a/sage/graphs/graph.py b/sage/graphs/graph.py
 a This module implements functions and operations involving undirected graphs. **Graph basic operations:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~Graph.write_to_eps | Writes a plot of the graph to filename in eps format. :meth:~Graph.to_undirected | Since the graph is already undirected, simply returns a copy of itself. :meth:~Graph.to_directed | Returns a directed version of the graph. :meth:~Graph.sparse6_string | Returns the sparse6 representation of the graph as an ASCII string. :meth:~Graph.graph6_string | Returns the graph6 representation of the graph as an ASCII string. :meth:~Graph.bipartite_sets | Returns (X,Y) where X and Y are the nodes in each bipartite set of graph. :meth:~Graph.bipartite_color | Returns a dictionary with vertices as the keys and the color class as the values. :meth:~Graph.is_directed | Since graph is undirected, returns False. **Distances:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~Graph.centrality_closeness | Returns the closeness centrality (1/average distance to all vertices) :meth:~Graph.centrality_degree | Returns the degree centrality :meth:~Graph.centrality_betweenness | Returns the betweenness centrality **Graph properties:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~Graph.is_prime | Tests whether the current graph is prime. :meth:~Graph.is_split | Returns True if the graph is a Split graph, False otherwise. :meth:~Graph.is_triangle_free | Returns whether self is triangle-free :meth:~Graph.is_bipartite | Returns True if graph G is bipartite, False if not. :meth:~Graph.is_line_graph | Tests wether the graph is a line graph. :meth:~Graph.is_odd_hole_free | Tests whether self contains an induced odd hole. :meth:~Graph.is_even_hole_free | Tests whether self contains an induced even hole. **Connectivity and orientations:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~Graph.gomory_hu_tree | Returns a Gomory-Hu tree of self. :meth:~Graph.bounded_outdegree_orientation | Computes an orientation of self such that every vertex v has out-degree less than b(v) :meth:~Graph.strong_orientation | Returns a strongly connected orientation of the current graph. :meth:~Graph.degree_constrained_subgraph | Returns a degree-constrained subgraph. **Clique-related methods:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~Graph.clique_complex | Returns the clique complex of self :meth:~Graph.cliques_containing_vertex | Returns the cliques containing each vertex :meth:~Graph.cliques_vertex_clique_number | Returns a dictionary of sizes of the largest maximal cliques containing each vertex :meth:~Graph.cliques_get_clique_bipartite | Returns a bipartite graph constructed such that maximal cliques are the right vertices and the left vertices are retained from the given graph :meth:~Graph.cliques_get_max_clique_graph | Returns a graph constructed with maximal cliques as vertices, and edges between maximal cliques sharing vertices. :meth:~Graph.cliques_number_of | Returns a dictionary of the number of maximal cliques containing each vertex, keyed by vertex. :meth:~Graph.clique_number | Returns the order of the largest clique of the graph. :meth:~Graph.clique_maximum | Returns the vertex set of a maximal order complete subgraph. :meth:~Graph.cliques_maximum | Returns the list of all maximum cliques :meth:~Graph.cliques_maximal | Returns the list of all maximal cliques **Algorithmically hard stuff:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~Graph.vertex_cover | Returns a minimum vertex cover of self :meth:~Graph.independent_set | Returns a maximum independent set. :meth:~Graph.topological_minor | Returns a topological H-minor from self if one exists. :meth:~Graph.convexity_properties | Returns a ConvexityProperties objet corresponding to self. :meth:~Graph.matching_polynomial | Computes the matching polynomial of the graph G. :meth:~Graph.rank_decomposition | Returns an rank-decomposition of self achieving optiml rank-width. :meth:~Graph.minor | Returns the vertices of a minor isomorphic to H in the current graph. :meth:~Graph.independent_set_of_representatives | Returns an independent set of representatives. :meth:~Graph.coloring | Returns the first (optimal) proper vertex-coloring found. :meth:~Graph.chromatic_number | Returns the minimal number of colors needed to color the vertices of the graph. :meth:~Graph.chromatic_polynomial | Returns the chromatic polynomial of the graph. :meth:~Graph.is_perfect | Tests whether the graph is perfect. **Leftovers:** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:~Graph.fractional_chromatic_index | Computes the fractional chromatic index of self :meth:~Graph.modular_decomposition | Returns the modular decomposition of the current graph. :meth:~Graph.two_factor_petersen | Returns a decomposition of the graph into 2-factors. AUTHORS: -  Robert L. Miller (2006-10-22): initial version \begin{tikzpicture} ... \end{tikzpicture} Methods ------- """ #***************************************************************************** def modular_decomposition(self): r""" Returns the modular decomposition corresponding to the current graph. Returns the modular decomposition of the current graph. Crash course on modular decomposition:
• ## sage/graphs/graph_coloring.py

diff --git a/sage/graphs/graph_coloring.py b/sage/graphs/graph_coloring.py
 a """ Graph coloring This module gathers all methods related to graph coloring. Here is what it can do : **Proper vertex coloring** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:all_graph_colorings | Computes all n-colorings a graph :meth:first_coloring | Returns the first vertex coloring found :meth:number_of_n_colorings | Computes the number of n-colorings of a graph :meth:numbers_of_colorings | Computes the number of colorings of a graph :meth:chromatic_number | Returns the chromatic number of the graph :meth:vertex_coloring | Computes Vertex colorings and chromatic numbers **Other colorings** .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:grundy_coloring | Computes Grundy numbers and Grundy colorings :meth:b_coloring | Computes a b-chromatic numbers and b-colorings :meth:edge_coloring | Compute chromatic index and edge colorings :meth:round_robin | Computes a round-robin coloring of the complete graph on n vertices :meth:linear_arboricity | Computes the linear arboricity of the given graph :meth:acyclic_edge_coloring | Computes an acyclic edge coloring of the current graph AUTHORS: - Tom Boothby (2008-02-21): Initial version - Carlo Hamalainen (2009-03-28): minor change: switch to C++ DLX solver - Nathann Cohen (2009-10-24): Coloring methods using linear programming Methods ------- """ #***************************************************************************** def number_of_n_colorings(G,n): r""" Given a graph G and a natural number n, returns the number of n-colorings of the graph. Computes the number of n-colorings of a graph EXAMPLES:: EXAMPLES: The Grundy number of a P_4 is equal to 3:: sage: from sage.graphs.graph_coloring import grundy_coloring sage: g = graphs.PathGraph(4) sage: grundy_coloring(g, 4) for u,v in g.edges(labels = None): for i in classes: p.add_constraint(b[v][i] + b[u][i], max = 1) # The following constraints ensure that if v is colored with i, # then it has a neighbor colored with j for every j m: k = m p = MixedIntegerLinearProgram(solver = solver) # List of possible colors #color[v][i] is set to 1 if and only if v is colored i color = p.new_variable(dim=2) #b[v][i] is set to 1 if and only if v is a b-vertex from color class i b = p.new_variable(dim=2) #is_used[i] is set to 1 if and only if color [i] is used by some vertex is_used = p.new_variable() # Each vertex is in exactly one class for v in g.vertices(): p.add_constraint(Sum(color[v][i] for i in xrange(k)), min=1, max=1) # Adjacent vertices have distinct colors for (u, v) in g.edge_iterator(labels=None): for i in classes: p.add_constraint(color[u][i] + color[v][i], max=1) # The following constraints ensure that if v is a b-vertex of color i # then it has a neighbor colored j for every j != i for v in g.vertices(): for i in classes: for j in classes: if j != i: # If v is not a b-vertex of color i, the constraint # is always satisfied, since the only possible # If v is not a b-vertex of color i, the constraint # is always satisfied, since the only possible # negative term in this case is -is_used[j] which is # cancelled by + 1. If v is a b-vertex of color i # then we MUST have sum(color[w][j] for w in g.neighbors(v)) # valued at least 1, which means that v has a neighbour in # valued at least 1, which means that v has a neighbour in # color j, as desired. p.add_constraint(Sum(color[w][j] for w in g.neighbors(v)) - b[v][i] p.add_constraint(Sum(color[w][j] for w in g.neighbors(v)) - b[v][i] + 1 - is_used[j], min=0) #if color i is used, there is a vertex colored i for i in classes: p.add_constraint(Sum(color[v][i] for v in g.vertices()) - is_used[i], min = 0) #if there is a vertex colored with color i, then i is used for v in g.vertices(): for i in classes: p.add_constraint(color[v][i] - is_used[i], max = 0) p.add_constraint(color[v][i] - is_used[i], max = 0) #a color class is used if and only if it has one b-vertex #We want to maximize the number of used colors p.set_objective(Sum(is_used[i] for i in classes)) try: obj = p.solve(log = verbose, objective_only = value_only) In a few cases, it is possible to find very quickly the chromatic index of a graph, while it remains a tedious job to compute a corresponding coloring. For this reason, value_only = True can sometimes be much faster, and it is a bad idea to compute can sometimes be much faster, and it is a bad idea to compute the whole coloring if you do not need it ! EXAMPLE:: if g.is_clique(): if value_only: return g.order()-1 if g.order() % 2 == 0 else g.order() return g.order()-1 if g.order() % 2 == 0 else g.order() vertices = g.vertices() r = round_robin(g.order()) classes = [[] for v in g] return k + 1 else: # if the coloring with Delta colors fails, tries Delta + 1 return edge_coloring(g, vizing=True, hex_colors=hex_colors, verbose=verbose, return edge_coloring(g, vizing=True, hex_colors=hex_colors, verbose=verbose, solver = solver) if value_only: return k Computes the linear arboricity of the given graph. The linear arboricity of a graph G is the least number la(G) such that the edges of G can be number la(G) such that the edges of G can be partitioned into linear forests (i.e. into forests of paths). of edges (meant as an argument to the edge_colors keyword of the plot method). - If hex_colors = False (default value), returns - If hex_colors = False (default value), returns a list of graphs corresponding to each color class. - value_only (boolean) - k (integer) -- the number of colors to use. - If 0, computes a decomposition of G into - If 0, computes a decomposition of G into \lceil \frac {\Delta(G)} 2 \rceil forests of paths Mathematical Institute of the Slovak Academy of Sciences Mathematica Slovaca vol30, n4, pages 405--417, 1980 """ from sage.rings.integer import Integer if k is None: try: return linear_arboricity(g, return linear_arboricity(g, k = (Integer(max(g.degree()))/2).ceil(), value_only = value_only, hex_colors = hex_colors, hex_colors = hex_colors, solver = solver, verbose = verbose) except ValueError: return linear_arboricity(g, return linear_arboricity(g, k = 0, value_only = value_only, hex_colors = hex_colors, hex_colors = hex_colors, solver = solver, verbose = verbose) elif k==1: raise Exception("It looks like you have found a counterexample to a very old conjecture. Please do not loose it ! Please publish it, and send a post to sage-devel to warn us. I implore you ! Nathann Cohen ") else: raise ValueError("This graph can not be colored with the given number of colors.") c = p.get_values(c) if hex_colors: An edge coloring of a graph is a assignment of colors to the edges of a graph such that : - the coloring is proper (no adjacent edges share a - the coloring is proper (no adjacent edges share a color) - For any two colors i,j, the union of the edges colored with i or j is a forest. The least number of colors such that such a coloring The least number of colors such that such a coloring exists for a graph G is written \chi'_a(G), also called the acyclic chromatic index of G. of edges (meant as an argument to the edge_colors keyword of the plot method). - If hex_colors = False (default value), returns - If hex_colors = False (default value), returns a list of graphs corresponding to each color class. - value_only (boolean) EXAMPLE: The complete graph on 8 vertices can not be acyclically The complete graph on 8 vertices can not be acyclically edge-colored with less \Delta+1 colors, but it can be colored with \Delta+2=9:: sage: from sage.graphs.graph_coloring import acyclic_edge_coloring sage: g = graphs.CompleteGraph(8) sage: g = graphs.CompleteGraph(8) sage: colors = acyclic_edge_coloring(g) Each color class is of course a matching :: sage: all([g1.union(g2).is_forest() for g1 in colors for g2 in colors]) True If one wants to acyclically color a cycle on 4 vertices, If one wants to acyclically color a cycle on 4 vertices, at least 3 colors will be necessary. The function raises an exception when asked to color it with only 2:: while True: try: return acyclic_edge_coloring(g, return acyclic_edge_coloring(g, value_only = value_only, hex_colors = hex_colors, hex_colors = hex_colors, k = k, solver = solver, verbose = verbose) elif k==0: k = max(g.degree())+2 from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException, Sum from sage.plot.colors import rainbow
• ## sage/graphs/graph_decompositions/rankwidth.pyx

diff --git a/sage/graphs/graph_decompositions/rankwidth.pyx b/sage/graphs/graph_decompositions/rankwidth.pyx
 a * "Computing rank-width exactly" by Sang-il Oum [Oum]_ * "Sopra una formula numerica" by Ernesto Pascal * "Generation of a Vector from the Lexicographical Index" by B.P. Buckles and M. Lybanon [BL]_ * "Generation of a Vector from the Lexicographical Index" by B.P. Buckles and M. Lybanon [BL]_ * "Fast additions on masked integers" by Michael D. Adams and David S. Wise [AW]_ **OUTPUT:** vol. 41, n.5, pages 39--45 ACM http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.86.1801&rep=rep1&type=pdf Methods ------- """ #***************************************************************************** r""" Computes an optiml rank-decomposition of the given graph. This function is available as a method of the This function is available as a method of the :class:Graph  class. See :meth:rank_decomposition . Exception: The rank decomposition cannot be computed on graphs of >= 32 vertices. The empty graph:: sage: g = Graph() sage: rank_decomposition(g) (0, Graph on 0 vertices) Converts the given Sage graph as an adjacency matrix. """ global id_to_vertices global vertices_to_id global vertices_to_id global adjacency_matrix global slots global cslots id_to_vertices = [] vertices_to_id = {} global num_vertices num_vertices = G.order() (this function is a copy of what can be found in rankwidth/rw.c) """ global adjacency_matrix adjacency_matrix[i] &= ~bitmask(j) adjacency_matrix[j] &= ~bitmask(i) global id_to_vertices cdef subset_t s from sage.graphs.graph import Graph g = Graph()
• ## sage/graphs/matchpoly.pyx

diff --git a/sage/graphs/matchpoly.pyx b/sage/graphs/matchpoly.pyx
 a """ Matching Polynomial Routine This module contains the following methods: .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:matching_polynomial | Computes the matching polynomial of a given graph :meth:complete_poly | Compute the matching polynomial of the complete graph on n vertices. AUTHORS: -- Robert Miller, Tom Boothby - original implementation - Robert Miller, Tom Boothby - original implementation REFERENCE: Chris Godsil, Algebraic Combinatorics. Methods ------- """ #***************************************************************************** .. MATH:: \mu(x)=\sum_{k \geq 0} (-1)^k p(G,k) x^{n-2k} INPUT: - complement - (default: True) whether to use Godsil's duality theorem to compute the matching polynomial from that of the graphs complement (see ALGORITHM). - name - optional string for the variable name in the polynomial .. NOTE:: The complement option uses matching polynomials of complete graphs, which are cached. So if you are crazy enough to try computing the matching polynomial on a graph with millions of vertices, you might not The algorithm used is a recursive one, based on the following observation [Godsil93]_: - If e is an edge of G, G' is the result of deleting the edge e, and G'' is the result of deleting each vertex in e, then the matching polynomial of G is equal to that of G' minus that of G''. .. MATH:: \mu(\overline{G}, x) = \sum_{k \geq 0} p(G,k) \mu( K_{n-2k}, x) Where \overline{G} is the complement of G, and K_n the complete graph on n vertices. EXAMPLES:: sage: g = graphs.PetersenGraph() sage: g.matching_polynomial() x^10 - 15*x^8 + 75*x^6 - 145*x^4 + 90*x^2 - 6 sage: prod([h.matching_polynomial() for h in L]) == sum(L, g).matching_polynomial()  # long time (up to 10s on sage.math, 2011) True :: :: sage: from sage.graphs.matchpoly import matching_polynomial sage: for i in [1..12]:  # long time (10s on sage.math, 2011) """ cdef int nverts, nedges, i, j, v, cur cdef int *edges1, *edges2, *edges_mem, **edges cdef fmpz_poly_t pol if G.has_multiple_edges(): raise NotImplementedError nverts = G.num_verts() # Using Godsil's duality theorem when the graph is dense return f nedges = G.num_edges() # Relabelling the vertices of the graph as [0...n-1] so that they are sorted # in increasing order of degree d[L[i][1]] = i G = G.relabel(d, inplace=False) G.allow_loops(False) # Initialization of pol, edges* variables. # The edges_mem table is of size (2 * nedges * nedges), and is to be read as if edges is not NULL: sage_free(edges) raise MemoryError("Error allocating memory for matchpoly.") for i from 0 <= i < 2*nedges: edges[i] = edges_mem + i * nedges edges1[cur] = i edges2[cur] = j cur += 1 # Computing the signless matching polynomial sig_on() sig_off() # Building the actual matching polynomial coeffs_ZZ = [] cdef Integer c_ZZ for i from 0 <= i <= nverts: - n -- order of the complete graph TODO: .. TODO:: This code could probably be made more efficient by using FLINT polynomials and being written in Cython, using an array of fmpz_poly_t pointers or something...  Right now just about the whole complement optimization is written in Python, and could be easily sped up. This code could probably be made more efficient by using FLINT polynomials and being written in Cython, using an array of fmpz_poly_t pointers or something...  Right now just about the whole complement optimization is written in Python, and could be easily sped up. EXAMPLES:: sage: from sage.graphs.matchpoly import complete_poly sage: f = complete_poly(10) sage: f else: fmpz_add_ui_inplace(coeff, 1) return edges1 = edges[2*depth] edges2 = edges[2*depth + 1] new_edges1 = edges[2*depth + 2]
• ## sage/graphs/pq_trees.py

diff --git a/sage/graphs/pq_trees.py b/sage/graphs/pq_trees.py
 a r""" PQ-Trees This module implements PQ-Trees and methods to help recognise Interval Graphs. This module implements PQ-Trees and methods to help recognise Interval Graphs. It is used by :meth:is_interval . """ # Constants, to make the code more readable set_contiguous = lambda tree, x : ( tree.set_contiguous(x) if isinstance(tree, PQ) else ((FULL, ALIGNED) if x in tree ((FULL, ALIGNED) if x in tree else (EMPTY, ALIGNED))) new_P = lambda liste : P(liste) if len(liste) > 1 else liste[0] return tree.ordering() class PQ: r""" r""" This class implements the PQ-Tree, used for the recognition of Interval Graphs, or equivalently for matrices having the so-caled "consecutive ones property". False def split(self, v): r""" r""" Returns the subsequences of children containing and not containing v sage: from sage.graphs.pq_trees import P, Q sage: p = Q([[1,2], [2,3], P([[2,4], [2,8], [2,9]])]) sage: p.cardinality() sage: p.cardinality() 3 """ return len(self._children) def ordering(self): r""" r""" Returns the current ordering given by listing the leaves from left to right. sage: from sage.graphs.pq_trees import P, Q sage: p = Q([[1,2], [2,3], P([[2,4], [2,8], [2,9]])]) sage: p.ordering() sage: p.ordering() [{1, 2}, {2, 3}, {2, 4}, {8, 2}, {9, 2}] """ value = [] else: contains, does_not_contain = self.split(v) A = new_P(does_not_contain) B = new_P(contains) class P(PQ): r""" A P-Tree is a PQ-Tree whose children are A P-Tree is a PQ-Tree whose children are not ordered (they can be permuted in any way) """ def set_contiguous(self, v): r""" r""" Updates self so that its sets containing v are contiguous for any admissible permutation of its subtrees. self._children = set_EMPTY + set_PARTIAL_ALIGNED return (PARTIAL, ALIGNED) ################################################################ # 2/2                                                          # #                                                              # # We must also make sure these elements will not be # reordered in such a way that the elements containing v # are not contiguous # ==> We create a Q-tree if n_PARTIAL_ALIGNED < 2: # We lock all of them in a Q-tree self._children.append(new_Q(new)) return PARTIAL, True # If there are 2 partial elements, we take care of both class Q(PQ): r""" A Q-Tree is a PQ-Tree whose children are A Q-Tree is a PQ-Tree whose children are ordered up to reversal """ def set_contiguous(self, v): r""" r""" Updates self so that its sets containing v are contiguous for any admissible permutation of its subtrees. #                                                                 # # * if the last element is empty (as we checked the whole         # #   vector is not empty                                           # #                                                                 # #                                                                 # # * if the last element is partial, aligned, and all the          # #   others are full                                               # ################################################################### if (f_seq[self._children[-1]] == (EMPTY, ALIGNED) or (f_seq[self._children[-1]] == (PARTIAL, ALIGNED) and n_FULL == self.cardinality() - 1)): if set_PARTIAL_ALIGNED[0] == self._children[-1]: return (PARTIAL, ALIGNED) else: return (PARTIAL, UNALIGNED) new_children = [] # Two variables to remember where we are # Two variables to remember where we are # according to the interval seen_nonempty = False for i in self: type, aligned = f_seq[i] type, aligned = f_seq[i] # We met an empty element if type == EMPTY: #    of the interval new_children.append(i) if seen_nonempty: seen_right_end = True # If we see an UNALIGNED partial element after # having met a nonempty element, there is no # solution to the alignment problem elif seen_nonempty and not aligned: raise ValueError(impossible_msg) subtree = i new_children.extend(subtree.simplify(v, right = True)) else: new_children.append(i) new_children.append(i) seen_nonempty = True # Setting the updated sequence of children self._children = new_children # Whether we achieved an alignment to the right is the # complement of whether we have seen the right end return (PARTIAL, not seen_right_end)
• ## sage/graphs/spanning_tree.pyx

diff --git a/sage/graphs/spanning_tree.pyx b/sage/graphs/spanning_tree.pyx
 a .. [Sahni2000] Sartaj Sahni. *Data Structures, Algorithms, and Applications in Java*. McGraw-Hill, 2000. Methods ------- """ ###########################################################################