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 b  
    1111
    1212- Jeroen Demeyer (2011-05-06): Make cliquer interruptible (#11252)
    1313
     14Methods
     15-------
    1416"""
    1517
    1618#*****************************************************************************
  • sage/graphs/convexity_properties.pyx

    diff --git a/sage/graphs/convexity_properties.pyx b/sage/graphs/convexity_properties.pyx
    a b  
    11r"""
    22Convexity properties of graphs
    33
    4 This class gathers the algorithms related to convexity in a graph.
     4This class gathers the algorithms related to convexity in a graph. It implements
     5the following methods:
    56
    6 AUTHOR: Nathann Cohen
     7.. csv-table::
     8    :class: contentstable
     9    :widths: 30, 70
     10    :delim: |
     11
     12    :meth:`ConvexityProperties.hull` | Returns the convex hull of a set of vertices
     13    :meth:`ConvexityProperties.hull_number` | Computes the hull number of a graph and a corresponding generating set.
     14
     15These methods can be used through the :class:`ConvexityProperties` object
     16returned by :meth:`Graph.convexity_properties`.
     17
     18AUTHORS:
     19
     20    -  Nathann Cohen
     21
     22Methods
     23-------
    724"""
    825
    926include "../misc/bitset.pxi"
     
    5370        * This class is useful if you compute the convex hulls of many sets in
    5471          the same graph, or if you want to compute the hull number itself as it
    5572          involves many calls to :meth:`hull`
    56        
     73
    5774        * Using this class on non-conected graphs is a waste of space and
    5875          efficiency ! If your graph is disconnected, the best for you is to
    5976          deal independently with each connected component, whatever you are
     
    102119        ...
    103120        ValueError: This is currenly implemented for Graphs only.Only minor updates are needed if you want to makeit support DiGraphs too.
    104121    """
    105    
     122
    106123    def __init__(self, G):
    107124        r"""
    108125        Constructor
     
    119136            raise ValueError("This is currenly implemented for Graphs only."+
    120137                             "Only minor updates are needed if you want to make"+
    121138                             "it support DiGraphs too.")
    122        
     139
    123140        # Cached number of vertices
    124141        cdef int n = G.order()
    125142        self._n = n
     
    176193                # Filling it
    177194                for 0<= k < n:
    178195                    if ((d_i[self._list_integers_to_vertices[k]]
    179                          + d_j[self._list_integers_to_vertices[k]]) 
     196                         + d_j[self._list_integers_to_vertices[k]])
    180197                        == d_ij):
    181198                        bitset_add(p_bitset[0], k)
    182199
    183200                # Next bitset !
    184201                p_bitset = p_bitset + 1
    185202
    186    
     203
    187204    def __destruct__(self):
    188205        r"""
    189206        Destructor
     
    204221            p_bitset = p_bitset + 1
    205222
    206223        sage_free(self._cache_hull_pairs)
    207            
     224
    208225    cdef list _vertices_to_integers(self, vertices):
    209226        r"""
    210227        Converts a list of vertices to a list of integers with the cached data.
     
    240257        count = bitset_len(hull)
    241258
    242259        while True:
    243            
     260
    244261            # Iterating over all the elements in the cache
    245262            p_bitset = self._cache_hull_pairs
    246263
     
    264281                    # Next bitset !
    265282                    p_bitset = p_bitset + 1
    266283
    267            
     284
    268285            tmp_count = bitset_len(hull)
    269286
    270287            # If we added nothing new during the previous loop, our set is
    271288            # convex !
    272289            if tmp_count == count:
    273290                return
    274    
     291
    275292            # Otherwise, update and back to the loop
    276293            count = tmp_count
    277294
     
    291308            sage: CP.hull([1,3])
    292309            [1, 2, 3]
    293310        """
    294         cdef bitset_t bs 
     311        cdef bitset_t bs
    295312        bitset_init(bs, self._n)
    296313        bitset_set_first_n(bs, 0)
    297314
     
    312329        Given a bitset whose hull is not the whole set, greedily add vertices
    313330        and stop before its hull is the whole set.
    314331
    315         NOTE: 
     332        NOTE:
    316333
    317334        * Counting the bits at each turn is not the best way...
    318335        """
     
    327344                self._bitset_convex_hull(tmp)
    328345                if bitset_len(tmp) < self._n:
    329346                    bitset_add(bs, i)
    330    
     347
    331348
    332349    cpdef hull_number(self, value_only = True, verbose = False):
    333350        r"""
    334         Computes the hull number and a correspondin generating set.
     351        Computes the hull number and a corresponding generating set.
    335352
    336353        The hull number `hn(G)` of a graph `G` is the cardinality of a smallest
    337354        set of vertices `S` such that `h(S)=V(G)`.
    338355
    339356        INPUT:
    340357
    341         * ``value_only`` (boolean) -- whether to return only the hull number (default) or
    342           a minimum set whose convex hull is the whole graph.
     358        * ``value_only`` (boolean) -- whether to return only the hull number
     359          (default) or a minimum set whose convex hull is the whole graph.
    343360
    344361        * ``verbose`` (boolean) -- whether to display information on the LP.
    345362
     
    404421          Mathematical and computer modelling
    405422          vol. 17 n11 pp.89--95, 1993
    406423        """
    407    
     424
    408425        cdef int i
    409426        cdef list constraint # temporary variable to add constraints to the LP
    410427
     
    413430                return self._n
    414431            else:
    415432                return self._list_integers_to_vertices
    416            
     433
    417434        cdef GenericBackend p = <GenericBackend> get_solver(constraint_generation = True)
    418435
    419436        # Minimization
     
    434451        bitset_set_first_n(current_hull,1)
    435452
    436453        while True:
    437            
     454
    438455            # Greedily increase it to obtain a better constraint
    439456            self._greedy_increase(current_hull)
    440457
  • sage/graphs/digraph.py

    diff --git a/sage/graphs/digraph.py b/sage/graphs/digraph.py
    a b  
    22Directed graphs
    33
    44This module implements functions and operations involving directed
    5 graphs.
     5graphs. Here is what they can do
     6
     7**Graph basic operations:**
     8
     9.. csv-table::
     10    :class: contentstable
     11    :widths: 30, 70
     12    :delim: |
     13
     14    :meth:`~DiGraph.layout_acyclic_dummy` | Computes a (dummy) ranked layout so that all edges point upward.
     15    :meth:`~DiGraph.layout_acyclic` | Computes a ranked layout so that all edges point upward.
     16    :meth:`~DiGraph.reverse` | Returns a copy of digraph with edges reversed in direction.
     17    :meth:`~DiGraph.out_degree_sequence` | Return the outdegree sequence
     18    :meth:`~DiGraph.out_degree_iterator` | Same as degree_iterator, but for out degree.
     19    :meth:`~DiGraph.out_degree` | Same as degree, but for out degree.
     20    :meth:`~DiGraph.in_degree_sequence` | Return the indegree sequence of this digraph.
     21    :meth:`~DiGraph.in_degree_iterator` | Same as degree_iterator, but for in degree.
     22    :meth:`~DiGraph.in_degree` | Same as degree, but for in-degree.
     23    :meth:`~DiGraph.neighbors_out` | Returns the list of the out-neighbors of a given vertex.
     24    :meth:`~DiGraph.neighbor_out_iterator` | Returns an iterator over the out-neighbors of a given vertex.
     25    :meth:`~DiGraph.neighbors_in` | Returns the list of the in-neighbors of a given vertex.
     26    :meth:`~DiGraph.neighbor_in_iterator` | Returns an iterator over the in-neighbors of vertex.
     27    :meth:`~DiGraph.outgoing_edges` | Returns a list of edges departing from vertices.
     28    :meth:`~DiGraph.outgoing_edge_iterator` | Return an iterator over all departing edges from vertices
     29    :meth:`~DiGraph.incoming_edges` | Returns a list of edges arriving at vertices.
     30    :meth:`~DiGraph.incoming_edge_iterator` | Return an iterator over all arriving edges from vertices
     31    :meth:`~DiGraph.to_undirected` | Returns an undirected version of the graph.
     32    :meth:`~DiGraph.to_directed` | Since the graph is already directed, simply returns a copy of itself.
     33    :meth:`~DiGraph.is_directed` | Since digraph is directed, returns True.
     34    :meth:`~DiGraph.dig6_string` | Returns the dig6 representation of the digraph as an ASCII string.
     35
     36
     37**Paths and cycles:**
     38
     39.. csv-table::
     40    :class: contentstable
     41    :widths: 30, 70
     42    :delim: |
     43
     44    :meth:`~DiGraph.all_paths_iterator` | Returns an iterator over the paths of self. The paths are
     45    :meth:`~DiGraph.all_simple_paths` | Returns a list of all the simple paths of self starting
     46    :meth:`~DiGraph.all_cycles_iterator` | Returns an iterator over all the cycles of self starting
     47    :meth:`~DiGraph.all_simple_cycles` | Returns a list of all simple cycles of self.
     48
     49
     50**Connectivity:**
     51
     52.. csv-table::
     53    :class: contentstable
     54    :widths: 30, 70
     55    :delim: |
     56
     57    :meth:`~DiGraph.is_strongly_connected` | Returns whether the current ``DiGraph`` is strongly connected.
     58    :meth:`~DiGraph.strongly_connected_components_digraph` | Returns the digraph of the strongly connected components
     59    :meth:`~DiGraph.strongly_connected_components_subgraphs` | Returns the strongly connected components as a list of subgraphs.
     60    :meth:`~DiGraph.strongly_connected_component_containing_vertex` | Returns the strongly connected component containing a given vertex
     61    :meth:`~DiGraph.strongly_connected_components` | Returns the list of strongly connected components.
     62
     63
     64**Acyclicity:**
     65
     66.. csv-table::
     67    :class: contentstable
     68    :widths: 30, 70
     69    :delim: |
     70
     71    :meth:`~DiGraph.is_directed_acyclic` | Returns whether the digraph is acyclic or not.
     72    :meth:`~DiGraph.level_sets` | Returns the level set decomposition of the digraph.
     73    :meth:`~DiGraph.topological_sort_generator` | Returns a list of all topological sorts of the digraph if it is acyclic
     74    :meth:`~DiGraph.topological_sort` | Returns a topological sort of the digraph if it is acyclic
     75
     76
     77**Hard stuff:**
     78
     79.. csv-table::
     80    :class: contentstable
     81    :widths: 30, 70
     82    :delim: |
     83
     84    :meth:`~DiGraph.feedback_edge_set` | Computes the minimum feedback edge (arc) set of a digraph
     85    :meth:`~DiGraph.feedback_vertex_set` | Computes the minimum feedback vertex set of a digraph.
     86
     87
     88Methods
     89-------
    690"""
    791
    892from sage.rings.integer import Integer
     
    17101
    18102    A digraph or directed graph is a set of vertices connected by oriented
    19103    edges. For more information, see the
    20     `Wikipedia article on digraphs 
     104    `Wikipedia article on digraphs
    21105    <http://en.wikipedia.org/wiki/Digraph_%28mathematics%29>`_.
    22106
    23107    One can very easily create a directed graph in Sage by typing::
    24    
     108
    25109        sage: g = DiGraph()
    26110
    27111    By typing the name of the digraph, one can get some basic information
     
    11551239
    11561240    def in_degree_sequence(self):
    11571241        r"""
    1158         Return the indegree sequence of this digraph.
     1242        Return the indegree sequence.
    11591243
    11601244        EXAMPLES:
    11611245
     
    25902674
    25912675    def layout_acyclic(self, **options):
    25922676        """
    2593         Computes a ranked layout so that all edges point upward. To
    2594         this end, the heights of the vertices are set according to the
    2595         level set decomposition of the graph (see :meth:`.level_sets`).
    2596 
    2597         This is achieved by calling ``graphviz`` and ``dot2tex`` if
    2598         available (see :meth:`.layout_acyclic_graphviz`), and using a
    2599         random horizontal placement of the vertices otherwise (see
    2600         :meth:`.layout_acyclic_dummy`).
    2601 
    2602         Non acyclic graphs are partially supported by ``graphviz``,
    2603         which then chooses some edges to point down.
     2677        Computes a ranked layout so that all edges point upward.
     2678
     2679        To this end, the heights of the vertices are set according to the level
     2680        set decomposition of the graph (see :meth:`.level_sets`).
     2681
     2682        This is achieved by calling ``graphviz`` and ``dot2tex`` if available
     2683        (see :meth:`.layout_acyclic_graphviz`), and using a random horizontal
     2684        placement of the vertices otherwise (see :meth:`.layout_acyclic_dummy`).
     2685
     2686        Non acyclic graphs are partially supported by ``graphviz``, which then
     2687        chooses some edges to point down.
    26042688
    26052689        EXAMPLES::
    26062690
     
    26462730
    26472731    def level_sets(self):
    26482732        """
     2733        Returns the level set decomposition of the digraph.
     2734
    26492735        OUTPUT:
    26502736
    26512737         - a list of non empty lists of vertices of this graph
    26522738
    2653         Returns the level set decomposition of the graph. This a list
    2654         `l` such that the level `l[i]` contains all the vertices
    2655         having all their predecessors in the levels `l[j]` for `j<i`,
    2656         and at least one in level `l[i-1]` (unless `i=0`).
    2657 
    2658         The level decomposition contains exactly the vertices not
    2659         occuring in any cycle of the graph. In particular, the graph
    2660         is acyclic if and only if the decomposition forms a set
    2661         partition of its vertices, and we recover the usual level set
    2662         decomposition of the corresponding poset.
     2739        The level set decomposition of the digraph is a list `l` such that the
     2740        level `l[i]` contains all the vertices having all their predecessors in
     2741        the levels `l[j]` for `j<i`, and at least one in level `l[i-1]` (unless
     2742        `i=0`).
     2743
     2744        The level decomposition contains exactly the vertices not occuring in
     2745        any cycle of the graph. In particular, the graph is acyclic if and only
     2746        if the decomposition forms a set partition of its vertices, and we
     2747        recover the usual level set decomposition of the corresponding poset.
    26632748
    26642749        EXAMPLES::
    26652750
     
    27062791
    27072792    def strongly_connected_components(self):
    27082793        """
    2709         Returns a list of lists of vertices, each list representing a
    2710         strongly connected component.
    2711 
     2794        Returns the list of strongly connected components.
    27122795
    27132796        EXAMPLES::
    27142797
     
    27602843
    27612844    def strongly_connected_component_containing_vertex(self, v):
    27622845        """
    2763         Returns the set of vertices whose strongly connected component is the same as v's.
     2846        Returns the strongly connected component containing a given vertex
    27642847
    27652848        INPUT:
    27662849
  • sage/graphs/generic_graph.py

    diff --git a/sage/graphs/generic_graph.py b/sage/graphs/generic_graph.py
    a b  
    11r"""
    22Generic graphs
    33
    4 This module implements the base class for graphs and digraphs, and
    5 methods that can be applied on both.
     4This module implements the base class for graphs and digraphs, and methods that
     5can be applied on both. Here is what it can do:
     6
     7**Basic Graph operations:**
     8
     9.. csv-table::
     10    :class: contentstable
     11    :widths: 30, 70
     12    :delim: |
     13
     14    :meth:`~GenericGraph.networkx_graph` | Creates a new NetworkX graph from the Sage graph
     15    :meth:`~GenericGraph.adjacency_matrix` | Returns the adjacency matrix of the (di)graph.
     16    :meth:`~GenericGraph.incidence_matrix` | Returns an incidence matrix of the (di)graph
     17    :meth:`~GenericGraph.weighted_adjacency_matrix` | Returns the weighted adjacency matrix of the graph
     18    :meth:`~GenericGraph.kirchhoff_matrix` | Returns the Kirchhoff matrix (a.k.a. the Laplacian) of the graph.
     19    :meth:`~GenericGraph.get_boundary` | Returns the boundary of the (di)graph.
     20    :meth:`~GenericGraph.set_boundary` | Sets the boundary of the (di)graph.
     21    :meth:`~GenericGraph.has_loops` | Returns whether there are loops in the (di)graph.
     22    :meth:`~GenericGraph.allows_loops` | Returns whether loops are permitted in the (di)graph.
     23    :meth:`~GenericGraph.allow_loops` | Changes whether loops are permitted in the (di)graph.
     24    :meth:`~GenericGraph.loops` | Returns any loops in the (di)graph.
     25    :meth:`~GenericGraph.has_multiple_edges` | Returns whether there are multiple edges in the (di)graph.
     26    :meth:`~GenericGraph.allows_multiple_edges` | Returns whether multiple edges are permitted in the (di)graph.
     27    :meth:`~GenericGraph.allow_multiple_edges` | Changes whether multiple edges are permitted in the (di)graph.
     28    :meth:`~GenericGraph.multiple_edges` | Returns any multiple edges in the (di)graph.
     29    :meth:`~GenericGraph.name` | Returns or sets the graph's name.
     30    :meth:`~GenericGraph.weighted` | Whether the (di)graph is to be considered as a weighted (di)graph.
     31    :meth:`~GenericGraph.antisymmetric` | Tests whether the graph is antisymmetric
     32    :meth:`~GenericGraph.density` | Returns the density
     33    :meth:`~GenericGraph.order` | Returns the number of vertices.
     34    :meth:`~GenericGraph.size` | Returns the number of edges.
     35    :meth:`~GenericGraph.add_vertex` | Creates an isolated vertex.
     36    :meth:`~GenericGraph.add_vertices` | Add vertices to the (di)graph from an iterable container
     37    :meth:`~GenericGraph.delete_vertex` | Deletes a vertex, removing all incident edges.
     38    :meth:`~GenericGraph.delete_vertices` | Remove vertices from the (di)graph taken from an iterable container of vertices.
     39    :meth:`~GenericGraph.has_vertex` | Return True if vertex is one of the vertices of this graph.
     40    :meth:`~GenericGraph.random_vertex` | Returns a random vertex of self.
     41    :meth:`~GenericGraph.random_edge` | Returns a random edge of self.
     42    :meth:`~GenericGraph.vertex_boundary` | Returns a list of all vertices in the external boundary of vertices1, intersected with vertices2.
     43    :meth:`~GenericGraph.set_vertices` | Associate arbitrary objects with each vertex
     44    :meth:`~GenericGraph.set_vertex` | Associate an arbitrary object with a vertex.
     45    :meth:`~GenericGraph.get_vertex` | Retrieve the object associated with a given vertex.
     46    :meth:`~GenericGraph.get_vertices` | Return a dictionary of the objects associated to each vertex.
     47    :meth:`~GenericGraph.loop_vertices` | Returns a list of vertices with loops.
     48    :meth:`~GenericGraph.vertex_iterator` | Returns an iterator over the vertices.
     49    :meth:`~GenericGraph.neighbor_iterator` | Return an iterator over neighbors of vertex.
     50    :meth:`~GenericGraph.vertices` | Return a list of the vertices.
     51    :meth:`~GenericGraph.neighbors` | Return a list of neighbors (in and out if directed) of vertex.
     52    :meth:`~GenericGraph.merge_vertices` | Merge vertices.
     53    :meth:`~GenericGraph.add_edge` | Adds an edge from u and v.
     54    :meth:`~GenericGraph.add_edges` | Add edges from an iterable container.
     55    :meth:`~GenericGraph.subdivide_edge` | Subdivides an edge `k` times.
     56    :meth:`~GenericGraph.subdivide_edges` | Subdivides k times edges from an iterable container.
     57    :meth:`~GenericGraph.delete_edge` | Delete the edge from u to v
     58    :meth:`~GenericGraph.delete_edges` | Delete edges from an iterable container.
     59    :meth:`~GenericGraph.delete_multiedge` | Deletes all edges from u and v.
     60    :meth:`~GenericGraph.set_edge_label` | Set the edge label of a given edge.
     61    :meth:`~GenericGraph.has_edge` | Returns True if (u, v) is an edge, False otherwise.
     62    :meth:`~GenericGraph.edges` | Return a list of edges.
     63    :meth:`~GenericGraph.edge_boundary` | Returns a list of edges `(u,v,l)` with `u` in ``vertices1``
     64    :meth:`~GenericGraph.edge_iterator` | Returns an iterator over edges.
     65    :meth:`~GenericGraph.edges_incident` | Returns incident edges to some vertices.
     66    :meth:`~GenericGraph.edge_label` | Returns the label of an edge.
     67    :meth:`~GenericGraph.edge_labels` | Returns a list of edge labels.
     68    :meth:`~GenericGraph.remove_multiple_edges` | Removes all multiple edges, retaining one edge for each.
     69    :meth:`~GenericGraph.remove_loops` | Removes loops on vertices in vertices. If vertices is None, removes all loops.
     70    :meth:`~GenericGraph.loop_edges` | Returns a list of all loops in the graph.
     71    :meth:`~GenericGraph.number_of_loops` | Returns the number of edges that are loops.
     72    :meth:`~GenericGraph.clear` | Empties the graph of vertices and edges and removes name, boundary, associated objects, and position information.
     73    :meth:`~GenericGraph.degree` | Gives the degree (in + out for digraphs) of a vertex or of vertices.
     74    :meth:`~GenericGraph.average_degree` | Returns the average degree of the graph.
     75    :meth:`~GenericGraph.degree_histogram` | Returns a list, whose ith entry is the frequency of degree i.
     76    :meth:`~GenericGraph.degree_iterator` | Returns an iterator over the degrees of the (di)graph.
     77    :meth:`~GenericGraph.degree_sequence` | Return the degree sequence of this (di)graph.
     78    :meth:`~GenericGraph.random_subgraph` | Return a random subgraph that contains each vertex with prob. p.
     79    :meth:`~GenericGraph.add_cycle` | Adds a cycle to the graph with the given vertices.
     80    :meth:`~GenericGraph.add_path` | Adds a cycle to the graph with the given vertices.
     81    :meth:`~GenericGraph.complement` | Returns the complement of the (di)graph.
     82    :meth:`~GenericGraph.line_graph` | Returns the line graph of the (di)graph.
     83    :meth:`~GenericGraph.to_simple` | Returns a simple version of itself (i.e., undirected and loops and multiple edges are removed).
     84    :meth:`~GenericGraph.disjoint_union` | Returns the disjoint union of self and other.
     85    :meth:`~GenericGraph.union` | Returns the union of self and other.
     86    :meth:`~GenericGraph.relabel` | Relabels the vertices of ``self``
     87    :meth:`~GenericGraph.degree_to_cell` | Returns the number of edges from vertex to an edge in cell.
     88    :meth:`~GenericGraph.subgraph` | Returns the subgraph containing the given vertices and edges.
     89    :meth:`~GenericGraph.is_subgraph` | Tests whether self is a subgraph of other.
     90
     91
     92
     93**Graph products:**
     94
     95.. csv-table::
     96    :class: contentstable
     97    :widths: 30, 70
     98    :delim: |
     99
     100    :meth:`~GenericGraph.cartesian_product` | Returns the Cartesian product of self and other.
     101    :meth:`~GenericGraph.tensor_product` | Returns the tensor product, also called the categorical product, of self and other.
     102    :meth:`~GenericGraph.lexicographic_product` | Returns the lexicographic product of self and other.
     103    :meth:`~GenericGraph.strong_product` | Returns the strong product of self and other.
     104    :meth:`~GenericGraph.disjunctive_product` | Returns the disjunctive product of self and other.
     105
     106**Paths and cycles:**
     107
     108.. csv-table::
     109    :class: contentstable
     110    :widths: 30, 70
     111    :delim: |
     112
     113    :meth:`~GenericGraph.eulerian_orientation` | Returns a DiGraph which is an Eulerian orientation of the current graph.
     114    :meth:`~GenericGraph.eulerian_circuit` | Return a list of edges forming an eulerian circuit if one exists.
     115    :meth:`~GenericGraph.cycle_basis` | Returns a list of cycles which form a basis of the cycle space of ``self``.
     116    :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.
     117    :meth:`~GenericGraph.all_paths` | Returns a list of all paths (also lists) between a pair of vertices in the (di)graph.
     118
     119**Linear algebra:**
     120
     121.. csv-table::
     122    :class: contentstable
     123    :widths: 30, 70
     124    :delim: |
     125
     126    :meth:`~GenericGraph.spectrum` | Returns a list of the eigenvalues of the adjacency matrix.
     127    :meth:`~GenericGraph.eigenvectors` | Returns the *right* eigenvectors of the adjacency matrix of the graph.
     128    :meth:`~GenericGraph.eigenspaces` | Returns the *right* eigenspaces of the adjacency matrix of the graph.
     129
     130**Some metrics:**
     131
     132.. csv-table::
     133    :class: contentstable
     134    :widths: 30, 70
     135    :delim: |
     136
     137    :meth:`~GenericGraph.cluster_triangles` | Returns the number of triangles for nbunch of vertices as a dictionary keyed by vertex.
     138    :meth:`~GenericGraph.clustering_average` | Returns the average clustering coefficient.
     139    :meth:`~GenericGraph.clustering_coeff` | Returns the clustering coefficient for each vertex in nbunch
     140    :meth:`~GenericGraph.cluster_transitivity` | Returns the transitivity (fraction of transitive triangles) of the graph.
     141    :meth:`~GenericGraph.szeged_index` | Returns the Szeged index of the graph.
     142
     143
     144**Automorphism group:**
     145
     146.. csv-table::
     147    :class: contentstable
     148    :widths: 30, 70
     149    :delim: |
     150
     151    :meth:`~GenericGraph.coarsest_equitable_refinement` | Returns the coarsest partition which is finer than the input partition, and equitable with respect to self.
     152    :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.
     153    :meth:`~GenericGraph.is_vertex_transitive` | Returns whether the automorphism group of self is transitive within the partition provided
     154    :meth:`~GenericGraph.is_isomorphic` | Tests for isomorphism between self and other.
     155    :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.
     156
     157**Graph properties:**
     158
     159.. csv-table::
     160    :class: contentstable
     161    :widths: 30, 70
     162    :delim: |
     163
     164    :meth:`~GenericGraph.is_eulerian` | Return true if the graph has a (closed) tour that visits each edge exactly once.
     165    :meth:`~GenericGraph.is_tree` | Return True if the graph is a tree.
     166    :meth:`~GenericGraph.is_forest` | Return True if the graph is a forest, i.e. a disjoint union of trees.
     167    :meth:`~GenericGraph.is_overfull` | Tests whether the current graph is overfull.
     168    :meth:`~GenericGraph.is_planar` | Tests whether the graph is planar.
     169    :meth:`~GenericGraph.is_circular_planar` | Tests whether the graph is circular planar (outerplanar)
     170    :meth:`~GenericGraph.is_regular` | Return ``True`` if this graph is (`k`-)regular.
     171    :meth:`~GenericGraph.is_chordal` | Tests whether the given graph is chordal.
     172    :meth:`~GenericGraph.is_interval` | Check whether self is an interval graph
     173    :meth:`~GenericGraph.is_gallai_tree` | Returns whether the current graph is a Gallai tree.
     174    :meth:`~GenericGraph.is_clique` | Tests whether a set of vertices is a clique
     175    :meth:`~GenericGraph.is_independent_set` | Tests whether a set of vertices is an independent set
     176    :meth:`~GenericGraph.is_transitively_reduced` | Tests whether the digraph is transitively reduced.
     177    :meth:`~GenericGraph.is_equitable` | Checks whether the given partition is equitable with respect to self.
     178
     179**Traversals:**
     180
     181.. csv-table::
     182    :class: contentstable
     183    :widths: 30, 70
     184    :delim: |
     185
     186    :meth:`~GenericGraph.breadth_first_search` | Returns an iterator over the vertices in a breadth-first ordering.
     187    :meth:`~GenericGraph.depth_first_search` | Returns an iterator over the vertices in a depth-first ordering.
     188    :meth:`~GenericGraph.lex_BFS` | Performs a Lex BFS on the graph.
     189
     190**Distances:**
     191
     192.. csv-table::
     193    :class: contentstable
     194    :widths: 30, 70
     195    :delim: |
     196
     197    :meth:`~GenericGraph.distance` | Returns the (directed) distance from u to v in the (di)graph
     198    :meth:`~GenericGraph.distance_all_pairs` | Returns the distances between all pairs of vertices.
     199    :meth:`~GenericGraph.distances_distribution` | Returns the distances distribution of the (di)graph in a dictionary.
     200    :meth:`~GenericGraph.eccentricity` | Return the eccentricity of vertex (or vertices) v.
     201    :meth:`~GenericGraph.radius` | Returns the radius of the (di)graph.
     202    :meth:`~GenericGraph.center` | Returns the set of vertices in the center of the graph
     203    :meth:`~GenericGraph.diameter` | Returns the largest distance between any two vertices.
     204    :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.
     205    :meth:`~GenericGraph.girth` | Computes the girth of the graph.
     206    :meth:`~GenericGraph.periphery` | Returns the set of vertices in the periphery
     207    :meth:`~GenericGraph.shortest_path` | Returns a list of vertices representing some shortest path from `u` to `v`
     208    :meth:`~GenericGraph.shortest_path_length` | Returns the minimal length of paths from u to v
     209    :meth:`~GenericGraph.shortest_paths` | Returns a dictionary associating to each vertex v a shortest path from u to v, if it exists.
     210    :meth:`~GenericGraph.shortest_path_lengths` | Returns a dictionary of shortest path lengths keyed by targets that are connected by a path from u.
     211    :meth:`~GenericGraph.shortest_path_all_pairs` | Computes a shortest path between each pair of vertices.
     212    :meth:`~GenericGraph.wiener_index` | Returns the Wiener index of the graph.
     213    :meth:`~GenericGraph.average_distance` | Returns the average distance between vertices of the graph.
     214
     215
     216**Flows, connectivity, trees:**
     217
     218.. csv-table::
     219    :class: contentstable
     220    :widths: 30, 70
     221    :delim: |
     222
     223    :meth:`~GenericGraph.is_connected` | Tests whether the (di)graph is connected.
     224    :meth:`~GenericGraph.connected_components` | Returns the list of connected components
     225    :meth:`~GenericGraph.connected_components_number` | Returns the number of connected components.
     226    :meth:`~GenericGraph.connected_components_subgraphs` | Returns a list of connected components as graph objects.
     227    :meth:`~GenericGraph.connected_component_containing_vertex` | Returns a list of the vertices connected to vertex.
     228    :meth:`~GenericGraph.blocks_and_cut_vertices` | Computes the blocks and cut vertices of the graph.
     229    :meth:`~GenericGraph.edge_cut` | Returns a minimum edge cut between vertices `s` and `t`
     230    :meth:`~GenericGraph.vertex_cut` | Returns a minimum vertex cut between non-adjacent vertices `s` and `t`
     231    :meth:`~GenericGraph.flow` | Returns a maximum flow in the graph from ``x`` to ``y``
     232    :meth:`~GenericGraph.edge_disjoint_paths` | Returns a list of edge-disjoint paths between two vertices
     233    :meth:`~GenericGraph.vertex_disjoint_paths` | Returns a list of vertex-disjoint paths between two vertices as given by Menger's theorem.
     234    :meth:`~GenericGraph.edge_connectivity` | Returns the edge connectivity of the graph.
     235    :meth:`~GenericGraph.vertex_connectivity` | Returns the vertex connectivity of the graph.
     236    :meth:`~GenericGraph.transitive_closure` | Computes the transitive closure of a graph and returns it.
     237    :meth:`~GenericGraph.transitive_reduction` | Returns a transitive reduction of a graph.
     238    :meth:`~GenericGraph.min_spanning_tree` | Returns the edges of a minimum spanning tree.
     239    :meth:`~GenericGraph.spanning_trees_count` | Returns the number of spanning trees in a graph.
     240
     241**Plot/embedding-related methods:**
     242
     243.. csv-table::
     244    :class: contentstable
     245    :widths: 30, 70
     246    :delim: |
     247
     248    :meth:`~GenericGraph.set_embedding` | Sets a combinatorial embedding dictionary to ``_embedding`` attribute.
     249    :meth:`~GenericGraph.get_embedding` | Returns the attribute _embedding if it exists.
     250    :meth:`~GenericGraph.check_embedding_validity` | Checks whether an ``_embedding`` attribute is well defined
     251    :meth:`~GenericGraph.get_pos` | Returns the position dictionary
     252    :meth:`~GenericGraph.check_pos_validity` | Checks whether pos specifies two (resp. 3) coordinates for every vertex (and no more vertices).
     253    :meth:`~GenericGraph.set_pos` | Sets the position dictionary.
     254    :meth:`~GenericGraph.set_planar_positions` | Compute a planar layout for self using Schnyder's algorithm
     255    :meth:`~GenericGraph.layout_planar` | Uses Schnyder's algorithm to compute a planar layout for self.
     256    :meth:`~GenericGraph.is_drawn_free_of_edge_crossings` | Tests whether the position dictionary gives a planar embedding.
     257    :meth:`~GenericGraph.latex_options` | Returns an instance of :class:`~sage.graphs.graph_latex.GraphLatex` for the graph.
     258    :meth:`~GenericGraph.set_latex_options` | Sets multiple options for rendering a graph with LaTeX.
     259    :meth:`~GenericGraph.layout` | Returns a layout for the vertices of this graph.
     260    :meth:`~GenericGraph.layout_spring` | Computes a spring layout for this graph
     261    :meth:`~GenericGraph.layout_ranked` | Computes a ranked layout for this graph
     262    :meth:`~GenericGraph.layout_extend_randomly` | Extends randomly a partial layout
     263    :meth:`~GenericGraph.layout_circular` | Computes a circular layout for this graph
     264    :meth:`~GenericGraph.layout_tree` | Computes an ordered tree layout for this graph, which should be a tree (no non-oriented cycles).
     265    :meth:`~GenericGraph.layout_graphviz` | Calls ``graphviz`` to compute a layout of the vertices of this graph.
     266    :meth:`~GenericGraph.graphplot` | Returns a GraphPlot object.
     267    :meth:`~GenericGraph.plot` | Returns a graphics object representing the (di)graph.
     268    :meth:`~GenericGraph.show` | Shows the (di)graph.
     269    :meth:`~GenericGraph.plot3d` | Plot a graph in three dimensions.
     270    :meth:`~GenericGraph.show3d` | Plots the graph using Tachyon, and shows the resulting plot.
     271    :meth:`~GenericGraph.graphviz_string` | Returns a representation in the dot language.
     272    :meth:`~GenericGraph.graphviz_to_file_named` | Write a representation in the dot in a file.
     273
     274**Algorithmically hard stuff:**
     275
     276.. csv-table::
     277    :class: contentstable
     278    :widths: 30, 70
     279    :delim: |
     280
     281    :meth:`~GenericGraph.steiner_tree` | Returns a tree of minimum weight connecting the given set of vertices.
     282    :meth:`~GenericGraph.edge_disjoint_spanning_trees` | Returns the desired number of edge-disjoint spanning trees/arborescences.
     283    :meth:`~GenericGraph.multiway_cut` | Returns a minimum edge multiway cut
     284    :meth:`~GenericGraph.max_cut` | Returns a maximum edge cut of the graph.
     285    :meth:`~GenericGraph.longest_path` | Returns a longest path of ``self``.
     286    :meth:`~GenericGraph.traveling_salesman_problem` | Solves the traveling salesman problem (TSP)
     287    :meth:`~GenericGraph.is_hamiltonian` | Tests whether the current graph is Hamiltonian.
     288    :meth:`~GenericGraph.hamiltonian_cycle` | Returns a Hamiltonian cycle/circuit of the current graph/digraph
     289    :meth:`~GenericGraph.multicommodity_flow` | Solves a multicommodity flow problem.
     290    :meth:`~GenericGraph.disjoint_routed_paths` | Returns a set of disjoint routed paths.
     291    :meth:`~GenericGraph.dominating_set` | Returns a minimum dominating set of the graph
     292    :meth:`~GenericGraph.subgraph_search` | Returns a copy of ``G`` in ``self``.
     293    :meth:`~GenericGraph.subgraph_search_count` | Returns the number of labelled occurences of ``G`` in ``self``.
     294    :meth:`~GenericGraph.subgraph_search_iterator` | Returns an iterator over the labelled copies of ``G`` in ``self``.
     295    :meth:`~GenericGraph.characteristic_polynomial` | Returns the characteristic polynomial of the adjacency matrix of the (di)graph.
     296    :meth:`~GenericGraph.genus` | Returns the minimal genus of the graph.
     297    :meth:`~GenericGraph.trace_faces` | A helper function for finding the genus of a graph.
     298
     299**Graph stuff that should not be in this file:**
     300
     301.. csv-table::
     302    :class: contentstable
     303    :widths: 30, 70
     304    :delim: |
     305
     306    :meth:`~GenericGraph.minimum_outdegree_orientation` | Returns an orientation of ``self`` with the smallest possible maximum outdegree
     307    :meth:`~GenericGraph.matching` | Returns a maximum weighted matching of the graph
     308    :meth:`~GenericGraph.maximum_average_degree` | Returns the Maximum Average Degree (MAD) of the current graph.
     309    :meth:`~GenericGraph.cores` | Returns the core number for each vertex in an ordered list.
     310
     311
     312Methods
     313-------
    6314"""
    7315
    8316from sage.misc.decorators import options
     
    21329
    22330    # Nice defaults for plotting arrays of graphs (see sage.misc.functional.show)
    23331    graphics_array_defaults =  {'layout': 'circular', 'vertex_size':50, 'vertex_labels':False, 'graph_border':True}
    24    
     332
    25333    def __init__(self):
    26334        r"""
    27335        Every graph carries a dictionary of options, which is set
     
    51359    def __add__(self, other_graph):
    52360        """
    53361        Returns the disjoint union of self and other.
    54        
     362
    55363        If there are common vertices to both, they will be renamed.
    56        
    57         EXAMPLES::
    58        
     364
     365        EXAMPLES::
     366
    59367            sage: G = graphs.CycleGraph(3)
    60368            sage: H = graphs.CycleGraph(4)
    61369            sage: J = G + H; J
     
    71379        Comparison of self and other. For equality, must be in the same
    72380        class, have the same settings for loops and multiedges, output the
    73381        same vertex list (in order) and the same adjacency matrix.
    74        
     382
    75383        Note that this is _not_ an isomorphism test.
    76        
    77         EXAMPLES::
    78        
     384
     385        EXAMPLES::
     386
    79387            sage: G = graphs.EmptyGraph()
    80388            sage: H = Graph()
    81389            sage: G == H
     
    558866
    559867    def adjacency_matrix(self, sparse=None, boundary_first=False):
    560868        """
    561         Returns the adjacency matrix of the (di)graph. Each vertex is
    562         represented by its position in the list returned by the vertices()
    563         function.
    564        
     869        Returns the adjacency matrix of the (di)graph.
     870
     871        Each vertex is represented by its position in the list returned by the
     872        vertices() function.
     873
    565874        The matrix returned is over the integers. If a different ring is
    566875        desired, use either the change_ring function or the matrix
    567876        function.
    568        
    569         INPUT:
    570        
    571        
     877
     878        INPUT:
     879
    572880        -  ``sparse`` - whether to represent with a sparse
    573881           matrix
    574        
     882
    575883        -  ``boundary_first`` - whether to represent the
    576884           boundary vertices in the upper left block
    577        
    578        
    579         EXAMPLES::
    580        
     885
     886        EXAMPLES::
     887
    581888            sage: G = graphs.CubeGraph(4)
    582889            sage: G.adjacency_matrix()
    583890            [0 1 1 0 1 0 0 0 1 0 0 0 0 0 0 0]
     
    596903            [0 0 0 0 0 1 0 0 0 1 0 0 1 0 0 1]
    597904            [0 0 0 0 0 0 1 0 0 0 1 0 1 0 0 1]
    598905            [0 0 0 0 0 0 0 1 0 0 0 1 0 1 1 0]
    599        
    600         ::
    601        
     906
     907        ::
     908
    602909            sage: matrix(GF(2),G) # matrix over GF(2)
    603910            [0 1 1 0 1 0 0 0 1 0 0 0 0 0 0 0]
    604911            [1 0 0 1 0 1 0 0 0 1 0 0 0 0 0 0]
     
    667974
    668975    def incidence_matrix(self, sparse=True):
    669976        """
    670         Returns an incidence matrix of the (di)graph. Each row is a vertex,
    671         and each column is an edge. Note that in the case of graphs, there
    672         is a choice of orientation for each edge.
    673        
    674         EXAMPLES::
    675        
     977        Returns the incidence matrix of the (di)graph.
     978
     979        Each row is a vertex, and each column is an edge. Note that in the case
     980        of graphs, there is a choice of orientation for each edge.
     981
     982        EXAMPLES::
     983
    676984            sage: G = graphs.CubeGraph(3)
    677985            sage: G.incidence_matrix()
    678986            [-1 -1 -1  0  0  0  0  0  0  0  0  0]
     
    683991            [ 0  0  0  1  0  0  0  0  0  1 -1  0]
    684992            [ 0  0  0  0  0  1  0  0  1  0  0 -1]
    685993            [ 0  0  0  0  0  0  0  1  0  0  1  1]
    686        
    687         ::
    688        
     994
     995        ::
     996
    689997            sage: D = DiGraph( { 0: [1,2,3], 1: [0,2], 2: [3], 3: [4], 4: [0,5], 5: [1] } )
    690998            sage: D.incidence_matrix()
    691999            [-1 -1 -1  0  0  0  0  0  1  1]
     
    7231031
    7241032    def weighted_adjacency_matrix(self, sparse=True, boundary_first=False):
    7251033        """
    726         Returns the weighted adjacency matrix of the graph. Each vertex is
    727         represented by its position in the list returned by the vertices()
    728         function.
    729        
    730         EXAMPLES::
    731        
     1034        Returns the weighted adjacency matrix of the graph.
     1035
     1036        Each vertex is represented by its position in the list returned by the
     1037        vertices() function.
     1038
     1039        EXAMPLES::
     1040
    7321041            sage: G = Graph(sparse=True, weighted=True)
    7331042            sage: G.add_edges([(0,1,1),(1,2,2),(0,2,3),(0,3,4)])
    7341043            sage: M = G.weighted_adjacency_matrix(); M
     
    7431052        The following doctest verifies that \#4888 is fixed::
    7441053
    7451054            sage: G = DiGraph({0:{}, 1:{0:1}, 2:{0:1}}, weighted = True,sparse=True)
    746             sage: G.weighted_adjacency_matrix() 
     1055            sage: G.weighted_adjacency_matrix()
    7471056            [0 0 0]
    7481057            [1 0 0]
    7491058            [1 0 0]
     
    7741083    def kirchhoff_matrix(self, weighted=None, indegree=True, normalized=False, **kwds):
    7751084        """
    7761085        Returns the Kirchhoff matrix (a.k.a. the Laplacian) of the graph.
    777        
     1086
    7781087        The Kirchhoff matrix is defined to be `D - M`, where `D` is
    7791088        the diagonal degree matrix (each diagonal entry is the degree
    7801089        of the corresponding vertex), and `M` is the adjacency matrix.
     
    9661275
    9671276    def set_embedding(self, embedding):
    9681277        """
    969         Sets a combinatorial embedding dictionary to _embedding attribute.
     1278        Sets a combinatorial embedding dictionary to ``_embedding`` attribute.
     1279
    9701280        Dictionary is organized with vertex labels as keys and a list of
    9711281        each vertex's neighbors in clockwise order.
    972        
     1282
    9731283        Dictionary is error-checked for validity.
    974        
    975         INPUT:
    976        
    977        
     1284
     1285        INPUT:
     1286
    9781287        -  ``embedding`` - a dictionary
    979        
    980        
    981         EXAMPLES::
    982        
     1288
     1289        EXAMPLES::
     1290
    9831291            sage: G = graphs.PetersenGraph()
    9841292            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]})
    9851293            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]})
     
    9911299            self._embedding = embedding
    9921300        else:
    9931301            raise Exception('embedding is not valid for %s'%self)
    994        
     1302
    9951303    def get_embedding(self):
    9961304        """
    997         Returns the attribute _embedding if it exists. _embedding is a
    998         dictionary organized with vertex labels as keys and a list of each
    999         vertex's neighbors in clockwise order.
    1000        
     1305        Returns the attribute _embedding if it exists.
     1306
     1307        ``_embedding`` is a dictionary organized with vertex labels as keys and a
     1308        list of each vertex's neighbors in clockwise order.
     1309
    10011310        Error-checked to insure valid embedding is returned.
    1002        
    1003         EXAMPLES::
    1004        
     1311
     1312        EXAMPLES::
     1313
    10051314            sage: G = graphs.PetersenGraph()
    10061315            sage: G.genus()
    10071316            1
     
    10121321            return self._embedding
    10131322        else:
    10141323            raise Exception('%s has been modified and the embedding is no longer valid.'%self)
    1015    
     1324
    10161325    def check_embedding_validity(self, embedding=None):
    10171326        """
    1018         Checks whether an _embedding attribute is defined on self and if
    1019         so, checks for accuracy. Returns True if everything is okay, False
    1020         otherwise.
    1021        
     1327        Checks whether an _embedding attribute is well defined.
     1328
     1329        If the ``_embedding`` attribute exists, it is checked for
     1330        accuracy. Returns True if everything is okay, False otherwise.
     1331
    10221332        If embedding=None will test the attribute _embedding.
    1023        
    1024         EXAMPLES::
    1025        
     1333
     1334        EXAMPLES::
     1335
    10261336            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]}
    10271337            sage: G = graphs.PetersenGraph()
    10281338            sage: G.check_embedding_validity(d)
     
    15101820                        if len(edges) > 1:
    15111821                            multi_edges += edges
    15121822        return multi_edges
    1513        
     1823
    15141824    def name(self, new=None):
    15151825        """
    1516         INPUT:
    1517        
     1826        Returns or sets the graph's name.
     1827
     1828        INPUT:
     1829
    15181830        - ``new`` - if not None, then this becomes the new name of the (di)graph.
    15191831          (if new == '', removes any name)
    15201832
    15211833        EXAMPLES::
    1522        
     1834
    15231835            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]}
    15241836            sage: G = Graph(d); G
    15251837            Graph on 10 vertices
     
    16942006
    16952007    def antisymmetric(self):
    16962008        r"""
    1697         Returns True if the relation given by the graph is antisymmetric
    1698         and False otherwise.
    1699        
     2009        Tests whether the graph is antisymmetric.
     2010
    17002011        A graph represents an antisymmetric relation if there being a path
    17012012        from a vertex x to a vertex y implies that there is not a path from
    17022013        y to x unless x=y.
     
    24042715
    24052716    def spanning_trees_count(self, root_vertex=None):
    24062717        """
    2407         Returns the number of spanning trees in a graph. In the case of a
    2408         digraph, counts the number of spanning out-trees rooted in
    2409         ``root_vertex``.
    2410         Default is to set first vertex as root.
     2718        Returns the number of spanning trees in a graph.
     2719
     2720        In the case of a digraph, counts the number of spanning out-trees rooted
     2721        in ``root_vertex``.  Default is to set first vertex as root.
    24112722
    24122723        This computation uses Kirchhoff's Matrix Tree Theorem [1] to calculate
    24132724        the number of spanning trees. For complete graphs on `n` vertices the
     
    25382849
    25392850    def minimum_outdegree_orientation(self, use_edge_labels=False, solver=None, verbose=0):
    25402851        r"""
    2541         Returns a DiGraph which is an orientation with the smallest
    2542         possible maximum outdegree of the current graph.
     2852        Returns an orientation of ``self`` with the smallest possible maximum
     2853        outdegree.
    25432854
    25442855        Given a Graph `G`, is is polynomial to compute an orientation
    25452856        `D` of the edges of `G` such that the maximum out-degree in
     
    27983109
    27993110    def is_circular_planar(self, ordered=True, on_embedding=None, kuratowski=False, set_embedding=False, set_pos=False):
    28003111        """
     3112        Tests whether the graph is circular planar (outerplanar)
     3113
    28013114        A graph (with nonempty boundary) is circular planar if it has a
    28023115        planar embedding in which all boundary vertices can be drawn in
    28033116        order on a disc boundary, with all the interior vertices drawn
    28043117        inside the disc.
    2805        
     3118
    28063119        Returns True if the graph is circular planar, and False if it is
    28073120        not. If kuratowski is set to True, then this function will return a
    28083121        tuple, with boolean first entry and second entry the Kuratowski
     
    28133126        require that the boundary can be drawn on the boundary of a disc,
    28143127        with all other vertices drawn inside (and no edge crossings). For
    28153128        more information, refer to reference [2].
    2816        
     3129
    28173130        This is a linear time algorithm to test for circular planarity. It
    28183131        relies on the edge-addition planarity algorithm due to
    28193132        Boyer-Myrvold. We accomplish linear time for circular planarity by
    28203133        modifying the graph before running the general planarity
    28213134        algorithm.
    2822        
     3135
    28233136        REFERENCE:
    28243137
    28253138        - [1] John M. Boyer and Wendy J. Myrvold, On the Cutting Edge:
     
    28293142
    28303143        - [2] Kirkman, Emily A. O(n) Circular Planarity
    28313144          Testing. [Online] Available: soon!
    2832        
    2833         INPUT:
    2834        
    2835        
     3145
     3146        INPUT:
     3147
    28363148        -  ``ordered`` - whether or not to consider the order
    28373149           of the boundary (set ordered=False to see if there is any possible
    28383150           boundary order that will satisfy circular planarity)
    2839        
     3151
    28403152        -  ``kuratowski`` - if set to True, returns a tuple
    28413153           with boolean first entry and the Kuratowski subgraph or minor as
    28423154           the second entry. See notes above.
    2843        
     3155
    28443156        -  ``on_embedding`` - the embedding dictionary to test
    28453157           planarity on. (i.e.: will return True or False only for the given
    28463158           embedding.)
    2847        
     3159
    28483160        -  ``set_embedding`` - whether or not to set the
    28493161           instance field variable that contains a combinatorial embedding
    28503162           (clockwise ordering of neighbors at each vertex). This value will
    28513163           only be set if a circular planar embedding is found. It is stored
    28523164           as a Python dict: v1: [n1,n2,n3] where v1 is a vertex and n1,n2,n3
    28533165           are its neighbors.
    2854        
     3166
    28553167        -  ``set_pos`` - whether or not to set the position
    28563168           dictionary (for plotting) to reflect the combinatorial embedding.
    28573169           Note that this value will default to False if set_emb is set to
    28583170           False. Also, the position dictionary will only be updated if a
    28593171           circular planar embedding is found.
    2860        
    2861        
    2862         EXAMPLES::
    2863        
     3172
     3173        EXAMPLES::
     3174
    28643175            sage: g439 = Graph({1:[5,7], 2:[5,6], 3:[6,7], 4:[5,6,7]})
    28653176            sage: g439.set_boundary([1,2,3,4])
    28663177            sage: g439.show(figsize=[2,2], vertex_labels=True, vertex_size=175)
     
    28813192             5: [4, 2, 1],
    28823193             6: [4, 3, 2],
    28833194             7: [3, 4, 1]}
    2884        
     3195
    28853196        Order matters::
    2886        
     3197
    28873198            sage: K23 = graphs.CompleteBipartiteGraph(2,3)
    28883199            sage: K23.set_boundary([0,1,2,3])
    28893200            sage: K23.is_circular_planar()
     
    34663777            v = self.vertex_iterator().next()
    34673778            conn_verts = list(self.depth_first_search(v, ignore_direction=True))
    34683779            return len(conn_verts) == self.num_verts()
    3469    
     3780
    34703781    def connected_components(self):
    34713782        """
     3783        Returns the list of connected components.
     3784
    34723785        Returns a list of lists of vertices, each list representing a
    34733786        connected component. The list is ordered from largest to smallest
    34743787        component.
    3475        
    3476         EXAMPLES::
    3477        
     3788
     3789        EXAMPLES::
     3790
    34783791            sage: G = Graph( { 0 : [1, 3], 1 : [2], 2 : [3], 4 : [5, 6], 5 : [6] } )
    34793792            sage: G.connected_components()
    34803793            [[0, 1, 2, 3], [4, 5, 6]]
     
    35493862
    35503863    def blocks_and_cut_vertices(self):
    35513864        """
    3552         Computes the blocks and cut vertices of the graph. In the case of a
    3553         digraph, this computation is done on the underlying graph.
    3554        
     3865        Computes the blocks and cut vertices of the graph.
     3866
     3867        In the case of a digraph, this computation is done on the underlying
     3868        graph.
     3869
    35553870        A cut vertex is one whose deletion increases the number of
    35563871        connected components. A block is a maximal induced subgraph which
    35573872        itself has no cut vertices. Two distinct blocks cannot overlap in
    35583873        more than a single cut vertex.
    3559        
    3560         OUTPUT: ``( B, C )``, where ``B`` is a list of blocks- each is 
     3874
     3875        OUTPUT: ``( B, C )``, where ``B`` is a list of blocks- each is
    35613876        a list of vertices and the blocks are the corresponding induced
    35623877        subgraphs-and ``C`` is a list of cut vertices.
    3563        
    3564         EXAMPLES::
    3565        
     3878
     3879        EXAMPLES::
     3880
    35663881            sage: graphs.PetersenGraph().blocks_and_cut_vertices()
    35673882            ([[6, 4, 9, 7, 5, 8, 3, 2, 1, 0]], [])
    35683883            sage: graphs.PathGraph(6).blocks_and_cut_vertices()
     
    35783893            ([[2, 1, 0], [4, 3, 0]], [0])
    35793894            sage: graphs.StarGraph(3).blocks_and_cut_vertices()
    35803895            ([[1, 0], [2, 0], [3, 0]], [0])
    3581        
     3896
    35823897        TESTS::
    35833898
    35843899            sage: Graph(0).blocks_and_cut_vertices()
     
    74477762
    74487763    def vertex_iterator(self, vertices=None):
    74497764        """
    7450         Returns an iterator over the given vertices. Returns False if not
    7451         given a vertex, sequence, iterator or None. None is equivalent to a
    7452         list of every vertex. Note that ``for v in G`` syntax
    7453         is allowed.
    7454        
    7455         INPUT:
    7456        
    7457        
     7765        Returns an iterator over the given vertices.
     7766
     7767        Returns False if not given a vertex, sequence, iterator or None. None is
     7768        equivalent to a list of every vertex. Note that ``for v in G`` syntax is
     7769        allowed.
     7770
     7771        INPUT:
     7772
    74587773        -  ``vertices`` - iterated vertices are these
    74597774           intersected with the vertices of the (di)graph
    7460        
    7461        
    7462         EXAMPLES::
    7463        
     7775
     7776        EXAMPLES::
     7777
    74647778            sage: P = graphs.PetersenGraph()
    74657779            sage: for v in P.vertex_iterator():
    74667780            ...    print v
     
    74717785            ...
    74727786            8
    74737787            9
    7474        
    7475         ::
    7476        
     7788
     7789        ::
     7790
    74777791            sage: G = graphs.TetrahedralGraph()
    74787792            sage: for i in G:
    74797793            ...    print i
     
    89709284
    89719285    def degree_iterator(self, vertices=None, labels=False):
    89729286        """
    8973         Returns an iterator over the degrees of the (di)graph. In the case
    8974         of a digraph, the degree is defined as the sum of the in-degree and
    8975         the out-degree, i.e. the total number of edges incident to a given
    8976         vertex.
    8977 
    8978         INPUT: labels=False: returns an iterator over degrees. labels=True:
    8979         returns an iterator over tuples (vertex, degree).
    8980 
     9287        Returns an iterator over the degrees of the (di)graph.
     9288
     9289        In the case of a digraph, the degree is defined as the sum of the
     9290        in-degree and the out-degree, i.e. the total number of edges incident to
     9291        a given vertex.
     9292
     9293        INPUT:
     9294
     9295        - ``labels`` (boolean) -- if set to ``False`` (default) the method
     9296          returns an iterator over degrees. Otherwise it returns an iterator
     9297          over tuples (vertex, degree).
    89819298
    89829299        -  ``vertices`` - if specified, restrict to this
    89839300           subset.
     
    91179434    def subgraph(self, vertices=None, edges=None, inplace=False,
    91189435                       vertex_property=None, edge_property=None, algorithm=None):
    91199436        """
    9120         Returns the subgraph containing the given vertices and edges. If
    9121         either vertices or edges are not specified, they are assumed to be
    9122         all vertices or edges. If edges are not specified, returns the
    9123         subgraph induced by the vertices.
     9437        Returns the subgraph containing the given vertices and edges.
     9438
     9439        If either vertices or edges are not specified, they are assumed to be
     9440        all vertices or edges. If edges are not specified, returns the subgraph
     9441        induced by the vertices.
    91249442       
    91259443        INPUT:
    91269444       
     
    95859903
    95869904            This method also works on digraphs.
    95879905
     9906        .. SEEALSO::
     9907
     9908            - :meth:`~GenericGraph.subgraph_search_count` -- Counts the number
     9909              of copies of a graph `H` inside of a graph `G`
     9910
     9911            - :meth:`~GenericGraph.subgraph_search_iterator` -- Iterate on the
     9912              copies of a graph `H` inside of a graph `G`
     9913
    95889914        ALGORITHM:
    95899915
    95909916        Brute-force search.
     
    96729998                return self.subgraph(g)
    96739999            else:
    967410000                Gcopy=G.copy()
    9675                 Gcopy.relabel(g)           
     10001                Gcopy.relabel(g)
    967610002                return self.subgraph(vertices=Gcopy.vertices(), edges=Gcopy.edges())
    967710003
    967810004        return None
     
    969710023
    969810024            This method also works on digraphs.
    969910025
     10026        .. SEEALSO::
     10027
     10028            - :meth:`~GenericGraph.subgraph_search` -- finds an subgraph
     10029              isomorphic to `H` inside of a graph `G`
     10030
     10031            - :meth:`~GenericGraph.subgraph_search_iterator` -- Iterate on the
     10032              copies of a graph `H` inside of a graph `G`
     10033
    970010034        EXAMPLES:
    970110035
    970210036        Counting the number of paths `P_5` in a PetersenGraph::
     
    977310107
    977410108            This method also works on digraphs.
    977510109
     10110        .. SEEALSO::
     10111
     10112            - :meth:`~GenericGraph.subgraph_search` -- finds an subgraph
     10113              isomorphic to `H` inside of a graph `G`
     10114
     10115            - :meth:`~GenericGraph.subgraph_search_count` -- Counts the number
     10116              of copies of a graph `H` inside of a graph `G`
     10117
    977610118        EXAMPLE:
    977710119
    977810120        Iterating through all the labelled `P_3` of `P_5`::
     
    1030010642
    1030110643    def is_clique(self, vertices=None, directed_clique=False):
    1030210644        """
    10303         Returns True if the set ``vertices`` is a clique, False
    10304         if not. A clique is a set of vertices such that there is an edge
    10305         between any two vertices.
    10306        
    10307         INPUT:
    10308        
    10309        
     10645        Tests whether a set of vertices is a clique
     10646
     10647        A clique is a set of vertices such that there is an edge between any two
     10648        vertices.
     10649
     10650        INPUT:
     10651
    1031010652        -  ``vertices`` - Vertices can be a single vertex or an
    1031110653           iterable container of vertices, e.g. a list, set, graph, file or
    1031210654           numeric array. If not passed, defaults to the entire graph.
    10313        
     10655
    1031410656        -  ``directed_clique`` - (default False) If set to
    1031510657           False, only consider the underlying undirected graph. If set to
    1031610658           True and the graph is directed, only return True if all possible
    1031710659           edges in _both_ directions exist.
    10318        
    10319        
    10320         EXAMPLES::
    10321        
     10660
     10661        EXAMPLES::
     10662
    1032210663            sage: g = graphs.CompleteGraph(4)
    1032310664            sage: g.is_clique([1,2,3])
    1032410665            True
     
    1036110702        Returns True if the set ``vertices`` is an independent
    1036210703        set, False if not. An independent set is a set of vertices such
    1036310704        that there is no edge between any two vertices.
    10364        
    10365         INPUT:
    10366        
    10367        
     10705
     10706        INPUT:
     10707
    1036810708        -  ``vertices`` - Vertices can be a single vertex or an
    1036910709           iterable container of vertices, e.g. a list, set, graph, file or
    1037010710           numeric array. If not passed, defaults to the entire graph.
    10371        
    10372        
    10373         EXAMPLES::
    10374        
     10711
     10712        EXAMPLES::
     10713
    1037510714            sage: graphs.CycleGraph(4).is_independent_set([1,3])
    1037610715            True
    1037710716            sage: graphs.CycleGraph(4).is_independent_set([1,2,3])
     
    1038110720
    1038210721    def is_subgraph(self, other):
    1038310722        """
    10384         Tests whether self is a subgraph of other.
    10385        
    10386         EXAMPLES::
    10387        
     10723        Tests whether self is an induced subgraph of other.
     10724
     10725        .. WARNING::
     10726
     10727            Please note that this method does not check whether ``self``
     10728            contains a subgraph *isomorphic* to ``other``, but only if it
     10729            directly contains it as a subgraph ! This means that this method
     10730            returns ``True`` only if the vertices of ``other`` are also vertices
     10731            of ``self``, and that the edges of ``other`` are equal to the edges
     10732            of ``self`` between the vertices contained in ``other``.
     10733
     10734        .. SEEALSO::
     10735
     10736            If you are interested in the (possibly induced) subgraphs of
     10737            ``self`` to ``other``, you are looking for the following methods:
     10738
     10739            - :meth:`~GenericGraph.subgraph_search` -- finds an subgraph
     10740              isomorphic to `H` inside of a graph `G`
     10741
     10742            - :meth:`~GenericGraph.subgraph_search_count` -- Counts the number
     10743              of such copies.
     10744
     10745            - :meth:`~GenericGraph.subgraph_search_iterator` -- Iterate over all
     10746              the copies of `H` contained in `G`.
     10747
     10748        EXAMPLES::
     10749
    1038810750            sage: P = graphs.PetersenGraph()
    1038910751            sage: G = P.subgraph(range(6))
    1039010752            sage: G.is_subgraph(P)
     
    1039710759        return other.subgraph(self_verts) == self
    1039810760
    1039910761    ### Cluster
    10400    
     10762
    1040110763    def cluster_triangles(self, nbunch=None, with_labels=False):
    1040210764        r"""
    1040310765        Returns the number of triangles for nbunch of vertices as a
    1040410766        dictionary keyed by vertex.
    10405        
     10767
    1040610768        The clustering coefficient of a graph is the fraction of possible
    1040710769        triangles that are triangles, `c_i = triangles_i /
    1040810770        (k_i\*(k_i-1)/2)` where `k_i` is the degree of vertex `i`, [1]. A
    1040910771        coefficient for the whole graph is the average of the `c_i`.
    1041010772        Transitivity is the fraction of all possible triangles which are
    1041110773        triangles, T = 3\*triangles/triads, [HSSNX]_.
    10412        
    10413         INPUT:
    10414        
    10415        
     10774
     10775        INPUT:
     10776
    1041610777        -  ``nbunch`` - The vertices to inspect. If
    1041710778           nbunch=None, returns data for all vertices in the graph
    10418        
    10419        
     10779
    1042010780        REFERENCE:
    1042110781
    1042210782        .. [HSSNX] Aric Hagberg, Dan Schult and Pieter Swart. NetworkX
    1042310783          documentation. [Online] Available:
    1042410784          https://networkx.lanl.gov/reference/networkx/
    10425        
    10426         EXAMPLES::
    10427        
     10785
     10786        EXAMPLES::
     10787
    1042810788            sage: (graphs.FruchtGraph()).cluster_triangles().values()
    1042910789            [1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0]
    1043010790            sage: (graphs.FruchtGraph()).cluster_triangles()
     
    1157111931                                         bidirectional=True,
    1157211932                                         weight_sum=None):
    1157311933        """
    11574         Returns the minimal length of paths from u to v: if there is no
    11575         path from u to v, returns Infinity.
    11576        
    11577         INPUT:
    11578        
    11579        
     11934        Returns the minimal length of paths from u to v.
     11935
     11936        If there is no path from u to v, returns Infinity.
     11937
     11938        INPUT:
     11939
    1158011940        -  ``by_weight`` - if False, uses a breadth first
    1158111941           search. If True, takes edge weightings into account, using
    1158211942           Dijkstra's algorithm.
    11583        
     11943
    1158411944        -  ``bidirectional`` - if True, the algorithm will
    1158511945           expand vertices from u and v at the same time, making two spheres
    1158611946           of half the usual radius. This generally doubles the speed
    1158711947           (consider the total volume in each case).
    11588        
     11948
    1158911949        -  ``weight_sum`` - if False, returns the number of
    1159011950           edges in the path. If True, returns the sum of the weights of these
    1159111951           edges. Default behavior is to have the same value as by_weight.
    11592        
    11593        
    11594         EXAMPLES::
    11595        
     11952
     11953        EXAMPLES::
     11954
    1159611955            sage: D = graphs.DodecahedralGraph()
    1159711956            sage: D.shortest_path_length(4, 9)
    1159811957            5
     
    1305713416        r"""
    1305813417        Computes the transitive closure of a graph and returns it. The
    1305913418        original graph is not modified.
    13060        
     13419
    1306113420        The transitive closure of a graph G has an edge (x,y) if and only
    1306213421        if there is a path between x and y in G.
    13063        
     13422
    1306413423        The transitive closure of any strongly connected component of a
    1306513424        graph is a complete graph. In particular, the transitive closure of
    1306613425        a connected undirected graph is a complete graph. The transitive
    1306713426        closure of a directed acyclic graph is a directed acyclic graph
    1306813427        representing the full partial order.
    13069        
    13070         EXAMPLES::
    13071        
     13428
     13429        EXAMPLES::
     13430
    1307213431            sage: g=graphs.PathGraph(4)
    1307313432            sage: g.transitive_closure()
    1307413433            Transitive closure of Path Graph: Graph on 4 vertices
     
    1309413453        r"""
    1309513454        Returns a transitive reduction of a graph. The original graph is
    1309613455        not modified.
    13097        
     13456
    1309813457        A transitive reduction H of G has a path from x to y if and only if
    1309913458        there was a path from x to y in G. Deleting any edge of H destroys
    1310013459        this property. A transitive reduction is not unique in general. A
     
    1313013489
    1313113490    def is_transitively_reduced(self):
    1313213491        r"""
    13133         Returns True if the digraph is transitively reduced and False
    13134         otherwise.
     13492        Tests whether the digraph is transitively reduced.
    1313513493
    1313613494        A digraph is transitively reduced if it is equal to its transitive
    1313713495        reduction.
    1313813496
    1313913497        EXAMPLES::
    13140        
     13498
    1314113499            sage: d = DiGraph({0:[1],1:[2],2:[3]})
    1314213500            sage: d.is_transitively_reduced()
    1314313501            True
     
    1617616534   
    1617716535    def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False):
    1617816536        """
    16179         Returns the unique graph on \{0,1,...,n-1\} ( n = self.order() ) which
     16537        Returns the unique graph on `\{0,1,...,n-1\}` ( ``n = self.order()`` ) which
    1618016538
    1618116539        - is isomorphic to self,
    1618216540
  • sage/graphs/graph.py

    diff --git a/sage/graphs/graph.py b/sage/graphs/graph.py
    a b  
    44This module implements functions and operations involving undirected
    55graphs.
    66
     7**Graph basic operations:**
     8
     9.. csv-table::
     10    :class: contentstable
     11    :widths: 30, 70
     12    :delim: |
     13
     14    :meth:`~Graph.write_to_eps` | Writes a plot of the graph to ``filename`` in ``eps`` format.
     15    :meth:`~Graph.to_undirected` | Since the graph is already undirected, simply returns a copy of itself.
     16    :meth:`~Graph.to_directed` | Returns a directed version of the graph.
     17    :meth:`~Graph.sparse6_string` | Returns the sparse6 representation of the graph as an ASCII string.
     18    :meth:`~Graph.graph6_string` | Returns the graph6 representation of the graph as an ASCII string.
     19    :meth:`~Graph.bipartite_sets` | Returns `(X,Y)` where X and Y are the nodes in each bipartite set of graph.
     20    :meth:`~Graph.bipartite_color` | Returns a dictionary with vertices as the keys and the color class as the values.
     21    :meth:`~Graph.is_directed` | Since graph is undirected, returns False.
     22
     23
     24**Distances:**
     25
     26.. csv-table::
     27    :class: contentstable
     28    :widths: 30, 70
     29    :delim: |
     30
     31    :meth:`~Graph.centrality_closeness` | Returns the closeness centrality (1/average distance to all vertices)
     32    :meth:`~Graph.centrality_degree` | Returns the degree centrality
     33    :meth:`~Graph.centrality_betweenness` | Returns the betweenness centrality
     34
     35
     36
     37**Graph properties:**
     38
     39.. csv-table::
     40    :class: contentstable
     41    :widths: 30, 70
     42    :delim: |
     43
     44    :meth:`~Graph.is_prime` | Tests whether the current graph is prime.
     45    :meth:`~Graph.is_split` | Returns ``True`` if the graph is a Split graph, ``False`` otherwise.
     46    :meth:`~Graph.is_triangle_free` | Returns whether ``self`` is triangle-free
     47    :meth:`~Graph.is_bipartite` | Returns True if graph G is bipartite, False if not.
     48    :meth:`~Graph.is_line_graph` | Tests wether the graph is a line graph.
     49    :meth:`~Graph.is_odd_hole_free` | Tests whether ``self`` contains an induced odd hole.
     50    :meth:`~Graph.is_even_hole_free` | Tests whether ``self`` contains an induced even hole.
     51
     52
     53
     54**Connectivity and orientations:**
     55
     56.. csv-table::
     57    :class: contentstable
     58    :widths: 30, 70
     59    :delim: |
     60
     61    :meth:`~Graph.gomory_hu_tree` | Returns a Gomory-Hu tree of self.
     62    :meth:`~Graph.bounded_outdegree_orientation` | Computes an orientation of ``self`` such that every vertex `v` has out-degree less than `b(v)`
     63    :meth:`~Graph.strong_orientation` | Returns a strongly connected orientation of the current graph.
     64    :meth:`~Graph.degree_constrained_subgraph` | Returns a degree-constrained subgraph.
     65
     66
     67
     68**Clique-related methods:**
     69
     70.. csv-table::
     71    :class: contentstable
     72    :widths: 30, 70
     73    :delim: |
     74
     75    :meth:`~Graph.clique_complex` | Returns the clique complex of self
     76    :meth:`~Graph.cliques_containing_vertex` | Returns the cliques containing each vertex
     77    :meth:`~Graph.cliques_vertex_clique_number` | Returns a dictionary of sizes of the largest maximal cliques containing each vertex
     78    :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
     79    :meth:`~Graph.cliques_get_max_clique_graph` | Returns a graph constructed with maximal cliques as vertices, and edges between maximal cliques sharing vertices.
     80    :meth:`~Graph.cliques_number_of` | Returns a dictionary of the number of maximal cliques containing each vertex, keyed by vertex.
     81    :meth:`~Graph.clique_number` | Returns the order of the largest clique of the graph.
     82    :meth:`~Graph.clique_maximum` | Returns the vertex set of a maximal order complete subgraph.
     83    :meth:`~Graph.cliques_maximum` | Returns the list of all maximum cliques
     84    :meth:`~Graph.cliques_maximal` | Returns the list of all maximal cliques
     85
     86
     87**Algorithmically hard stuff:**
     88
     89.. csv-table::
     90    :class: contentstable
     91    :widths: 30, 70
     92    :delim: |
     93
     94    :meth:`~Graph.vertex_cover` | Returns a minimum vertex cover of self
     95    :meth:`~Graph.independent_set` | Returns a maximum independent set.
     96    :meth:`~Graph.topological_minor` | Returns a topological `H`-minor from ``self`` if one exists.
     97    :meth:`~Graph.convexity_properties` | Returns a ``ConvexityProperties`` objet corresponding to ``self``.
     98    :meth:`~Graph.matching_polynomial` | Computes the matching polynomial of the graph `G`.
     99    :meth:`~Graph.rank_decomposition` | Returns an rank-decomposition of ``self`` achieving optiml rank-width.
     100    :meth:`~Graph.minor` | Returns the vertices of a minor isomorphic to `H` in the current graph.
     101    :meth:`~Graph.independent_set_of_representatives` | Returns an independent set of representatives.
     102    :meth:`~Graph.coloring` | Returns the first (optimal) proper vertex-coloring found.
     103    :meth:`~Graph.chromatic_number` | Returns the minimal number of colors needed to color the vertices of the graph.
     104    :meth:`~Graph.chromatic_polynomial` | Returns the chromatic polynomial of the graph.
     105    :meth:`~Graph.is_perfect` | Tests whether the graph is perfect.
     106
     107
     108
     109**Leftovers:**
     110
     111.. csv-table::
     112    :class: contentstable
     113    :widths: 30, 70
     114    :delim: |
     115
     116    :meth:`~Graph.fractional_chromatic_index` | Computes the fractional chromatic index of ``self``
     117    :meth:`~Graph.modular_decomposition` | Returns the modular decomposition of the current graph.
     118    :meth:`~Graph.two_factor_petersen` | Returns a decomposition of the graph into 2-factors.
     119
     120
    7121AUTHORS:
    8122
    9123-  Robert L. Miller (2006-10-22): initial version
     
    359473    \begin{tikzpicture}
    360474    ...
    361475    \end{tikzpicture}
     476
     477Methods
     478-------
    362479"""
    363480
    364481#*****************************************************************************
     
    43424459
    43434460    def modular_decomposition(self):
    43444461        r"""
    4345         Returns the modular decomposition corresponding
    4346         to the current graph.
     4462        Returns the modular decomposition of the current graph.
    43474463
    43484464        Crash course on modular decomposition:
    43494465       
  • sage/graphs/graph_coloring.py

    diff --git a/sage/graphs/graph_coloring.py b/sage/graphs/graph_coloring.py
    a b  
    11"""
    22Graph coloring
    33
     4This module gathers all methods related to graph coloring. Here is what it can
     5do :
     6
     7**Proper vertex coloring**
     8
     9.. csv-table::
     10    :class: contentstable
     11    :widths: 30, 70
     12    :delim: |
     13
     14    :meth:`all_graph_colorings` | Computes all `n`-colorings a graph
     15    :meth:`first_coloring` | Returns the first vertex coloring found
     16    :meth:`number_of_n_colorings` | Computes the number of `n`-colorings of a graph
     17    :meth:`numbers_of_colorings` | Computes the number of colorings of a graph
     18    :meth:`chromatic_number` | Returns the chromatic number of the graph
     19    :meth:`vertex_coloring` | Computes Vertex colorings and chromatic numbers
     20
     21
     22**Other colorings**
     23
     24.. csv-table::
     25    :class: contentstable
     26    :widths: 30, 70
     27    :delim: |
     28
     29    :meth:`grundy_coloring` | Computes Grundy numbers and Grundy colorings
     30    :meth:`b_coloring` | Computes a b-chromatic numbers and b-colorings
     31    :meth:`edge_coloring` | Compute chromatic index and edge colorings
     32    :meth:`round_robin` | Computes a round-robin coloring of the complete graph on `n` vertices
     33    :meth:`linear_arboricity` | Computes the linear arboricity of the given graph
     34    :meth:`acyclic_edge_coloring` | Computes an acyclic edge coloring of the current graph
     35
     36
     37
    438AUTHORS:
    539
    640- Tom Boothby (2008-02-21): Initial version
    741- Carlo Hamalainen (2009-03-28): minor change: switch to C++ DLX solver
    842- Nathann Cohen (2009-10-24): Coloring methods using linear programming
     43
     44Methods
     45-------
    946"""
    1047
    1148#*****************************************************************************
     
    177214
    178215def number_of_n_colorings(G,n):
    179216    r"""
    180     Given a graph `G` and a natural number `n`, returns the number of
    181     `n`-colorings of the graph.
     217    Computes the number of `n`-colorings of a graph
    182218
    183219    EXAMPLES::
    184220
     
    532568    EXAMPLES:
    533569
    534570    The Grundy number of a `P_4` is equal to 3::
    535    
     571
    536572        sage: from sage.graphs.graph_coloring import grundy_coloring
    537573        sage: g = graphs.PathGraph(4)
    538574        sage: grundy_coloring(g, 4)
     
    570606    for u,v in g.edges(labels = None):
    571607        for i in classes:
    572608            p.add_constraint(b[v][i] + b[u][i], max = 1)
    573    
     609
    574610    # The following constraints ensure that if v is colored with i,
    575611    # then it has a neighbor colored with j for every j<i
    576612
     
    588624    # is_used[i] can be set to 1 only if the color is used
    589625    for i in classes:
    590626        p.add_constraint( Sum( b[v][i] for v in g ) - is_used[i], min = 0)
    591          
     627
    592628    # Both variables are binary
    593629    p.set_binary(b)
    594630    p.set_binary(is_used)
    595631
    596632    # Trying to use as many colors as possible
    597633    p.set_objective( Sum( is_used[i] for i in classes ) )
    598    
     634
    599635    try:
    600636        obj = p.solve(log = verbose, objective_only = value_only)
    601637        from sage.rings.integer import Integer
     
    627663    number of colors, if such a coloring exists
    628664
    629665    Definition :
    630      
     666
    631667    Given a proper coloring of a graph `G` and a color class `C` such
    632668    that none of its vertices have neighbors in all the other color
    633     classes, one can eliminate color class `C` assigning to each of 
     669    classes, one can eliminate color class `C` assigning to each of
    634670    its elements a missing color in its neighborhood.
    635    
     671
    636672    Let a b-vertex be a vertex with neighbors in all other colorings.
    637     Then, one can repeat the above procedure until a coloring 
    638     is obtained where every color class contains a b-vertex, 
     673    Then, one can repeat the above procedure until a coloring
     674    is obtained where every color class contains a b-vertex,
    639675    in which case none of the color classes can be eliminated
    640     with the same ideia.  So, one can define a b-coloring as a 
     676    with the same ideia.  So, one can define a b-coloring as a
    641677    proper coloring where each color class has a b-vertex.
    642    
     678
    643679    In the worst case, after successive applications of the above procedure,
    644680    one get a proper coloring that uses a number of colors equal to the
    645681    the b-chromatic number of `G` (denoted `\chi_b(G)`):
     
    693729    EXAMPLES:
    694730
    695731    The b-chromatic number of a `P_5` is equal to 3::
    696    
     732
    697733        sage: from sage.graphs.graph_coloring import b_coloring
    698734        sage: g = graphs.PathGraph(5)
    699735        sage: b_coloring(g, 5)
     
    712748    from sage.numerical.mip import MixedIntegerLinearProgram
    713749    from sage.numerical.mip import MIPSolverException, Sum
    714750
    715        
     751
    716752    # Calculate the upper bound m(G)
    717753    # To do so, it takes the list of degrees in
    718754    # non-increasing order and computes the largest
     
    720756    # at least i - 1 (note that in the code we need
    721757    # to take in consideration that the indices
    722758    # of the list starts with 0)
    723    
     759
    724760    deg = g.degree()
    725761    deg.sort(reverse = True)
    726762    for i in xrange(g.order()):
     
    735771    if k > m:
    736772        k = m
    737773
    738    
     774
    739775    p = MixedIntegerLinearProgram(solver = solver)
    740776
    741777    # List of possible colors
     
    743779
    744780    #color[v][i] is set to 1 if and only if v is colored i
    745781    color = p.new_variable(dim=2)
    746          
     782
    747783    #b[v][i] is set to 1 if and only if v is a b-vertex from color class i
    748784    b = p.new_variable(dim=2)
    749785
    750786    #is_used[i] is set to 1 if and only if color [i] is used by some vertex
    751787    is_used = p.new_variable()
    752    
     788
    753789    # Each vertex is in exactly one class
    754790    for v in g.vertices():
    755791        p.add_constraint(Sum(color[v][i] for i in xrange(k)), min=1, max=1)
    756    
     792
    757793    # Adjacent vertices have distinct colors
    758794    for (u, v) in g.edge_iterator(labels=None):
    759795        for i in classes:
    760796            p.add_constraint(color[u][i] + color[v][i], max=1)
    761    
     797
    762798    # The following constraints ensure that if v is a b-vertex of color i
    763799    # then it has a neighbor colored j for every j != i
    764800
    765    
     801
    766802    for v in g.vertices():
    767803        for i in classes:
    768804            for j in classes:
    769805                if j != i:
    770                     # If v is not a b-vertex of color i, the constraint 
    771                     # is always satisfied, since the only possible 
     806                    # If v is not a b-vertex of color i, the constraint
     807                    # is always satisfied, since the only possible
    772808                    # negative term in this case is -is_used[j] which is
    773809                    # cancelled by + 1. If v is a b-vertex of color i
    774810                    # then we MUST have sum(color[w][j] for w in g.neighbors(v))
    775                     # valued at least 1, which means that v has a neighbour in 
     811                    # valued at least 1, which means that v has a neighbour in
    776812                    # color j, as desired.
    777                     p.add_constraint(Sum(color[w][j] for w in g.neighbors(v)) - b[v][i] 
     813                    p.add_constraint(Sum(color[w][j] for w in g.neighbors(v)) - b[v][i]
    778814                        + 1 - is_used[j], min=0)
    779    
     815
    780816    #if color i is used, there is a vertex colored i
    781817    for i in classes:
    782818        p.add_constraint(Sum(color[v][i] for v in g.vertices()) - is_used[i], min = 0)
     
    784820    #if there is a vertex colored with color i, then i is used
    785821    for v in g.vertices():
    786822        for i in classes:
    787             p.add_constraint(color[v][i] - is_used[i], max = 0) 
     823            p.add_constraint(color[v][i] - is_used[i], max = 0)
    788824
    789825
    790826    #a color class is used if and only if it has one b-vertex
     
    799835
    800836    #We want to maximize the number of used colors
    801837    p.set_objective(Sum(is_used[i] for i in classes))
    802  
     838
    803839
    804840    try:
    805841        obj = p.solve(log = verbose, objective_only = value_only)
     
    891927       In a few cases, it is possible to find very quickly the chromatic
    892928       index of a graph, while it remains a tedious job to compute
    893929       a corresponding coloring. For this reason, ``value_only = True``
    894        can sometimes be much faster, and it is a bad idea to compute 
     930       can sometimes be much faster, and it is a bad idea to compute
    895931       the whole coloring if you do not need it !
    896932
    897933    EXAMPLE::
     
    913949
    914950    if g.is_clique():
    915951        if value_only:
    916             return g.order()-1 if g.order() % 2 == 0 else g.order() 
     952            return g.order()-1 if g.order() % 2 == 0 else g.order()
    917953        vertices = g.vertices()
    918954        r = round_robin(g.order())
    919955        classes = [[] for v in g]
     
    961997            return k + 1
    962998        else:
    963999            # if the coloring with Delta colors fails, tries Delta + 1
    964             return edge_coloring(g, 
    965                                  vizing=True, 
    966                                  hex_colors=hex_colors, 
    967                                  verbose=verbose, 
     1000            return edge_coloring(g,
     1001                                 vizing=True,
     1002                                 hex_colors=hex_colors,
     1003                                 verbose=verbose,
    9681004                                 solver = solver)
    9691005    if value_only:
    9701006        return k
     
    10531089    Computes the linear arboricity of the given graph.
    10541090
    10551091    The linear arboricity of a graph `G` is the least
    1056     number `la(G)` such that the edges of `G` can be 
     1092    number `la(G)` such that the edges of `G` can be
    10571093    partitioned into linear forests (i.e. into forests
    10581094    of paths).
    10591095
     
    10711107          of edges (meant as an argument to the ``edge_colors``
    10721108          keyword of the ``plot`` method).
    10731109
    1074         - If ``hex_colors = False`` (default value), returns 
     1110        - If ``hex_colors = False`` (default value), returns
    10751111          a list of graphs corresponding to each color class.
    10761112
    10771113    - ``value_only`` (boolean)
     
    10841120
    10851121    - ``k`` (integer) -- the number of colors to use.
    10861122
    1087         - If ``0``, computes a decomposition of `G` into 
     1123        - If ``0``, computes a decomposition of `G` into
    10881124          `\lceil \frac {\Delta(G)} 2 \rceil`
    10891125          forests of paths
    10901126
     
    11461182      Mathematical Institute of the Slovak Academy of Sciences
    11471183      Mathematica Slovaca vol30, n4, pages 405--417, 1980
    11481184    """
    1149    
     1185
    11501186    from sage.rings.integer import Integer
    11511187
    11521188    if k is None:
    11531189        try:
    1154             return linear_arboricity(g, 
     1190            return linear_arboricity(g,
    11551191                                     k = (Integer(max(g.degree()))/2).ceil(),
    11561192                                     value_only = value_only,
    1157                                      hex_colors = hex_colors, 
     1193                                     hex_colors = hex_colors,
    11581194                                     solver = solver,
    11591195                                     verbose = verbose)
    11601196        except ValueError:
    1161             return linear_arboricity(g, 
     1197            return linear_arboricity(g,
    11621198                                     k = 0,
    11631199                                     value_only = value_only,
    1164                                      hex_colors = hex_colors, 
     1200                                     hex_colors = hex_colors,
    11651201                                     solver = solver,
    11661202                                     verbose = verbose)
    11671203    elif k==1:
     
    12181254            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 ")
    12191255        else:
    12201256            raise ValueError("This graph can not be colored with the given number of colors.")
    1221    
     1257
    12221258    c = p.get_values(c)
    12231259
    12241260    if hex_colors:
     
    12471283    An edge coloring of a graph is a assignment of colors
    12481284    to the edges of a graph such that :
    12491285
    1250     - the coloring is proper (no adjacent edges share a 
     1286    - the coloring is proper (no adjacent edges share a
    12511287      color)
    12521288    - For any two colors `i,j`, the union of the edges
    12531289      colored with `i` or `j` is a forest.
    12541290
    1255     The least number of colors such that such a coloring 
     1291    The least number of colors such that such a coloring
    12561292    exists for a graph `G` is written `\chi'_a(G)`, also
    12571293    called the acyclic chromatic index of `G`.
    12581294
     
    12711307          of edges (meant as an argument to the ``edge_colors``
    12721308          keyword of the ``plot`` method).
    12731309
    1274         - If ``hex_colors = False`` (default value), returns 
     1310        - If ``hex_colors = False`` (default value), returns
    12751311          a list of graphs corresponding to each color class.
    12761312
    12771313    - ``value_only`` (boolean)
     
    13111347
    13121348    EXAMPLE:
    13131349
    1314     The complete graph on 8 vertices can not be acyclically 
     1350    The complete graph on 8 vertices can not be acyclically
    13151351    edge-colored with less `\Delta+1` colors, but it can be
    13161352    colored with `\Delta+2=9`::
    13171353
    13181354        sage: from sage.graphs.graph_coloring import acyclic_edge_coloring
    1319         sage: g = graphs.CompleteGraph(8)   
     1355        sage: g = graphs.CompleteGraph(8)
    13201356        sage: colors = acyclic_edge_coloring(g)
    13211357
    13221358    Each color class is of course a matching ::
     
    13341370        sage: all([g1.union(g2).is_forest() for g1 in colors for g2 in colors])
    13351371        True
    13361372
    1337     If one wants to acyclically color a cycle on `4` vertices, 
     1373    If one wants to acyclically color a cycle on `4` vertices,
    13381374    at least 3 colors will be necessary. The function raises
    13391375    an exception when asked to color it with only 2::
    13401376
     
    13601396
    13611397        while True:
    13621398            try:
    1363                 return acyclic_edge_coloring(g, 
     1399                return acyclic_edge_coloring(g,
    13641400                                             value_only = value_only,
    1365                                              hex_colors = hex_colors, 
     1401                                             hex_colors = hex_colors,
    13661402                                             k = k,
    13671403                                             solver = solver,
    13681404                                             verbose = verbose)
     
    13731409
    13741410    elif k==0:
    13751411        k = max(g.degree())+2
    1376    
     1412
    13771413    from sage.numerical.mip import MixedIntegerLinearProgram, MIPSolverException, Sum
    13781414    from sage.plot.colors import rainbow
    13791415
  • sage/graphs/graph_decompositions/rankwidth.pyx

    diff --git a/sage/graphs/graph_decompositions/rankwidth.pyx b/sage/graphs/graph_decompositions/rankwidth.pyx
    a b  
    3232
    3333    * "Computing rank-width exactly" by Sang-il Oum [Oum]_
    3434    * "Sopra una formula numerica" by Ernesto Pascal
    35     * "Generation of a Vector from the Lexicographical Index" by B.P. Buckles and M. Lybanon [BL]_ 
     35    * "Generation of a Vector from the Lexicographical Index" by B.P. Buckles and M. Lybanon [BL]_
    3636    * "Fast additions on masked integers" by Michael D. Adams and David S. Wise [AW]_
    3737
    3838**OUTPUT:**
     
    110110    vol. 41, n.5, pages 39--45
    111111    ACM
    112112    http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.86.1801&rep=rep1&type=pdf
     113
     114Methods
     115-------
    113116"""
    114117
    115118#*****************************************************************************
     
    131134    r"""
    132135    Computes an optiml rank-decomposition of the given graph.
    133136
    134     This function is available as a method of the 
     137    This function is available as a method of the
    135138    :class:`Graph <sage.graphs.graph>` class. See
    136139    :meth:`rank_decomposition <sage.graphs.graph.rank_decomposition>`.
    137140
     
    162165        Exception: The rank decomposition cannot be computed on graphs of >= 32 vertices.
    163166
    164167    The empty graph::
    165    
     168
    166169        sage: g = Graph()
    167170        sage: rank_decomposition(g)
    168171        (0, Graph on 0 vertices)
     
    220223    Converts the given Sage graph as an adjacency matrix.
    221224    """
    222225    global id_to_vertices
    223     global vertices_to_id 
     226    global vertices_to_id
    224227    global adjacency_matrix
    225228    global slots
    226229    global cslots
    227230
    228231    id_to_vertices = []
    229232    vertices_to_id = {}
    230    
     233
    231234    global num_vertices
    232235    num_vertices = G.order()
    233236
     
    271274    (this function is a copy of what can be found in rankwidth/rw.c)
    272275    """
    273276    global adjacency_matrix
    274    
     277
    275278    adjacency_matrix[i] &= ~bitmask(j)
    276279    adjacency_matrix[j] &= ~bitmask(i)
    277280
     
    315318    global id_to_vertices
    316319
    317320    cdef subset_t s
    318    
     321
    319322    from sage.graphs.graph import Graph
    320323    g = Graph()
    321324
  • sage/graphs/matchpoly.pyx

    diff --git a/sage/graphs/matchpoly.pyx b/sage/graphs/matchpoly.pyx
    a b  
    11"""
    22Matching Polynomial Routine
    33
     4This module contains the following methods:
     5
     6.. csv-table::
     7    :class: contentstable
     8    :widths: 30, 70
     9    :delim: |
     10
     11    :meth:`matching_polynomial` | Computes the matching polynomial of a given graph
     12    :meth:`complete_poly` | Compute the matching polynomial of the complete graph on `n` vertices.
     13
    414AUTHORS:
    5     -- Robert Miller, Tom Boothby - original implementation
     15
     16    - Robert Miller, Tom Boothby - original implementation
    617
    718REFERENCE:
    819    Chris Godsil, Algebraic Combinatorics.
    920
     21Methods
     22-------
    1023"""
    1124
    1225#*****************************************************************************
     
    3851    .. MATH::
    3952
    4053        \mu(x)=\sum_{k \geq 0} (-1)^k p(G,k) x^{n-2k}
    41        
    42        
     54
     55
    4356    INPUT:
    44        
     57
    4558    - ``complement`` - (default: ``True``) whether to use Godsil's duality
    4659      theorem to compute the matching polynomial from that of the graphs
    4760      complement (see ALGORITHM).
    48        
     61
    4962    - ``name`` - optional string for the variable name in the polynomial
    5063
    5164    .. NOTE::
    52        
     65
    5366        The ``complement`` option uses matching polynomials of complete graphs,
    5467        which are cached. So if you are crazy enough to try computing the
    5568        matching polynomial on a graph with millions of vertices, you might not
     
    6073
    6174    The algorithm used is a recursive one, based on the following observation
    6275    [Godsil93]_:
    63        
     76
    6477    - If `e` is an edge of `G`, `G'` is the result of deleting the edge `e`, and
    6578      `G''` is the result of deleting each vertex in `e`, then the matching
    6679      polynomial of `G` is equal to that of `G'` minus that of `G''`.
     
    7588    .. MATH::
    7689
    7790        \mu(\overline{G}, x) = \sum_{k \geq 0} p(G,k) \mu( K_{n-2k}, x)
    78            
     91
    7992
    8093    Where `\overline{G}` is the complement of `G`, and `K_n` the complete graph
    8194    on `n` vertices.
    8295
    8396    EXAMPLES::
    84        
     97
    8598        sage: g = graphs.PetersenGraph()
    8699        sage: g.matching_polynomial()
    87100        x^10 - 15*x^8 + 75*x^6 - 145*x^4 + 90*x^2 - 6
     
    94107        sage: prod([h.matching_polynomial() for h in L]) == sum(L, g).matching_polynomial()  # long time (up to 10s on sage.math, 2011)
    95108        True
    96109
    97     :: 
     110    ::
    98111
    99112        sage: from sage.graphs.matchpoly import matching_polynomial
    100113        sage: for i in [1..12]:  # long time (10s on sage.math, 2011)
     
    196209
    197210
    198211    """
    199    
     212
    200213    cdef int nverts, nedges, i, j, v, cur
    201214    cdef int *edges1, *edges2, *edges_mem, **edges
    202215    cdef fmpz_poly_t pol
    203    
     216
    204217    if G.has_multiple_edges():
    205218        raise NotImplementedError
    206    
     219
    207220    nverts = G.num_verts()
    208221
    209222    # Using Godsil's duality theorem when the graph is dense
     
    217230        return f
    218231
    219232    nedges = G.num_edges()
    220    
     233
    221234    # Relabelling the vertices of the graph as [0...n-1] so that they are sorted
    222235    # in increasing order of degree
    223236
     
    230243        d[L[i][1]] = i
    231244    G = G.relabel(d, inplace=False)
    232245    G.allow_loops(False)
    233    
     246
    234247    # Initialization of pol, edges* variables.
    235248
    236249    # The edges_mem table is of size (2 * nedges * nedges), and is to be read as
     
    251264        if edges is not NULL:
    252265            sage_free(edges)
    253266        raise MemoryError("Error allocating memory for matchpoly.")
    254    
     267
    255268    for i from 0 <= i < 2*nedges:
    256269        edges[i] = edges_mem + i * nedges
    257270
     
    263276        edges1[cur] = i
    264277        edges2[cur] = j
    265278        cur += 1
    266    
     279
    267280    # Computing the signless matching polynomial
    268281
    269282    sig_on()
     
    271284    sig_off()
    272285
    273286    # Building the actual matching polynomial
    274    
     287
    275288    coeffs_ZZ = []
    276289    cdef Integer c_ZZ
    277290    for i from 0 <= i <= nverts:
     
    299312
    300313    - ``n`` -- order of the complete graph
    301314
    302     TODO:
     315    .. TODO::
    303316
    304     This code could probably be made more efficient by using FLINT polynomials
    305     and being written in Cython, using an array of fmpz_poly_t pointers or
    306     something...  Right now just about the whole complement optimization is
    307     written in Python, and could be easily sped up.
     317        This code could probably be made more efficient by using FLINT
     318        polynomials and being written in Cython, using an array of
     319        fmpz_poly_t pointers or something...  Right now just about the
     320        whole complement optimization is written in Python, and could
     321        be easily sped up.
    308322
    309323    EXAMPLES::
    310    
     324
    311325        sage: from sage.graphs.matchpoly import complete_poly
    312326        sage: f = complete_poly(10)
    313327        sage: f
     
    372386        else:
    373387            fmpz_add_ui_inplace(coeff, 1)
    374388        return
    375    
     389
    376390    edges1 = edges[2*depth]
    377391    edges2 = edges[2*depth + 1]
    378392    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 b  
    11r"""
    22PQ-Trees
    33
    4 This module implements PQ-Trees and methods to help recognise Interval Graphs.
     4This module implements PQ-Trees and methods to help recognise Interval
     5Graphs. It is used by :meth:`is_interval
     6<sage.graphs.generic_graph.GenericGraph.is_interval>`.
    57"""
    68
    79# Constants, to make the code more readable
     
    2426
    2527set_contiguous = lambda tree, x : (
    2628    tree.set_contiguous(x) if isinstance(tree, PQ) else
    27     ((FULL, ALIGNED) if x in tree 
     29    ((FULL, ALIGNED) if x in tree
    2830     else (EMPTY, ALIGNED)))
    2931
    3032new_P = lambda liste : P(liste) if len(liste) > 1 else liste[0]
     
    9092    return tree.ordering()
    9193
    9294class PQ:
    93     r""" 
     95    r"""
    9496    This class implements the PQ-Tree, used for the recognition of
    9597    Interval Graphs, or equivalently for matrices having the so-caled
    9698    "consecutive ones property".
     
    236238        False
    237239
    238240    def split(self, v):
    239         r""" 
     241        r"""
    240242        Returns the subsequences of children containing and not
    241243        containing ``v``
    242244
     
    313315
    314316            sage: from sage.graphs.pq_trees import P, Q
    315317            sage: p = Q([[1,2], [2,3], P([[2,4], [2,8], [2,9]])])
    316             sage: p.cardinality() 
     318            sage: p.cardinality()
    317319            3
    318320        """
    319321        return len(self._children)
    320322
    321323    def ordering(self):
    322         r""" 
     324        r"""
    323325        Returns the current ordering given by listing the leaves from
    324326        left to right.
    325327
     
    327329
    328330            sage: from sage.graphs.pq_trees import P, Q
    329331            sage: p = Q([[1,2], [2,3], P([[2,4], [2,8], [2,9]])])
    330             sage: p.ordering()                               
     332            sage: p.ordering()
    331333            [{1, 2}, {2, 3}, {2, 4}, {8, 2}, {9, 2}]
    332334        """
    333335        value = []
     
    409411        else:
    410412
    411413            contains, does_not_contain = self.split(v)
    412            
     414
    413415            A = new_P(does_not_contain)
    414416            B = new_P(contains)
    415417
     
    471473
    472474class P(PQ):
    473475    r"""
    474     A P-Tree is a PQ-Tree whose children are 
     476    A P-Tree is a PQ-Tree whose children are
    475477    not ordered (they can be permuted in any way)
    476478    """
    477479    def set_contiguous(self, v):
    478         r""" 
     480        r"""
    479481        Updates ``self`` so that its sets containing ``v`` are
    480482        contiguous for any admissible permutation of its subtrees.
    481483
     
    615617            self._children = set_EMPTY + set_PARTIAL_ALIGNED
    616618            return (PARTIAL, ALIGNED)
    617619
    618        
     620
    619621        ################################################################
    620622        # 2/2                                                          #
    621623        #                                                              #
     
    641643            # We must also make sure these elements will not be
    642644            # reordered in such a way that the elements containing v
    643645            # are not contiguous
    644    
     646
    645647            # ==> We create a Q-tree
    646648
    647649            if n_PARTIAL_ALIGNED < 2:
     
    667669                # We lock all of them in a Q-tree
    668670
    669671                self._children.append(new_Q(new))
    670                
     672
    671673                return PARTIAL, True
    672674
    673675            # If there are 2 partial elements, we take care of both
     
    707709
    708710class Q(PQ):
    709711    r"""
    710     A Q-Tree is a PQ-Tree whose children are 
     712    A Q-Tree is a PQ-Tree whose children are
    711713    ordered up to reversal
    712714    """
    713715
    714716    def set_contiguous(self, v):
    715         r""" 
     717        r"""
    716718        Updates ``self`` so that its sets containing ``v`` are
    717719        contiguous for any admissible permutation of its subtrees.
    718720
     
    835837        #                                                                 #
    836838        # * if the last element is empty (as we checked the whole         #
    837839        #   vector is not empty                                           #
    838         #                                                                 # 
     840        #                                                                 #
    839841        # * if the last element is partial, aligned, and all the          #
    840842        #   others are full                                               #
    841843        ###################################################################
    842        
     844
    843845        if (f_seq[self._children[-1]] == (EMPTY, ALIGNED) or
    844846            (f_seq[self._children[-1]] == (PARTIAL, ALIGNED) and n_FULL == self.cardinality() - 1)):
    845847
     
    887889
    888890            if set_PARTIAL_ALIGNED[0] == self._children[-1]:
    889891                return (PARTIAL, ALIGNED)
    890            
     892
    891893            else:
    892894                return (PARTIAL, UNALIGNED)
    893895
     
    911913
    912914            new_children = []
    913915
    914             # Two variables to remember where we are 
     916            # Two variables to remember where we are
    915917            # according to the interval
    916918
    917919            seen_nonempty = False
     
    919921
    920922
    921923            for i in self:
    922                
    923                 type, aligned = f_seq[i]               
     924
     925                type, aligned = f_seq[i]
    924926
    925927                # We met an empty element
    926928                if type == EMPTY:
     
    937939                    #    of the interval
    938940
    939941                    new_children.append(i)
    940                        
     942
    941943                    if seen_nonempty:
    942944                        seen_right_end = True
    943945
     
    965967                        # If we see an UNALIGNED partial element after
    966968                        # having met a nonempty element, there is no
    967969                        # solution to the alignment problem
    968                            
     970
    969971                        elif seen_nonempty and not aligned:
    970972                            raise ValueError(impossible_msg)
    971973
     
    983985                            subtree = i
    984986
    985987                            new_children.extend(subtree.simplify(v, right = True))
    986                        
     988
    987989
    988990                    else:
    989                         new_children.append(i)                       
     991                        new_children.append(i)
    990992
    991993                    seen_nonempty = True
    992994
    993995            # Setting the updated sequence of children
    994996            self._children = new_children
    995997
    996            
     998
    997999            # Whether we achieved an alignment to the right is the
    9981000            # complement of whether we have seen the right end
    9991001
    10001002            return (PARTIAL, not seen_right_end)
    1001            
     1003
  • sage/graphs/spanning_tree.pyx

    diff --git a/sage/graphs/spanning_tree.pyx b/sage/graphs/spanning_tree.pyx
    a b  
    3232
    3333.. [Sahni2000] Sartaj Sahni. *Data Structures, Algorithms, and Applications
    3434  in Java*. McGraw-Hill, 2000.
     35
     36Methods
     37-------
    3538"""
    3639
    3740###########################################################################