Ticket #13891: trac_13891-second_pass.patch

File trac_13891-second_pass.patch, 22.4 KB (added by ncohen, 6 years ago)
  • sage/combinat/posets/posets.py

    # HG changeset patch
    # User Nathann Cohen <nathann.cohen@gmail.com>
    # Date 1359049408 -3600
    # Node ID 495f445eabfeaccc79f3b6e3b0cc90c60346b833
    # Parent  bfe01d26d03974d60e81c532c2a278be9e8afffd
    Default parameters for Graph.plot() and Graph.show() -- second pass
    
    diff --git a/sage/combinat/posets/posets.py b/sage/combinat/posets/posets.py
    a b  
    13101310        return list(self.linear_extension())
    13111311
    13121312    def plot(self, label_elements=True, element_labels=None,
    1313              label_font_size=12,label_font_color='black',
    13141313             vertex_size=300, vertex_colors=None,
    13151314             layout = 'acyclic',
    13161315             **kwds):
     
    13701369        if label_elements and element_labels is not None:
    13711370            graph = graph.relabel(dict((self(element),label) for (element,label) in element_labels.items()), inplace = False)
    13721371        return graph.plot(vertex_labels=label_elements,
    1373                           label_font_size=label_font_size,
    1374                           label_font_color=label_font_color,
    13751372                          vertex_size=vertex_size,
    13761373                          vertex_colors=vertex_colors,
    13771374                          layout = layout,
    13781375                          **kwds)
    13791376
    13801377    def show(self, label_elements=True, element_labels=None,
    1381             label_font_size=12,label_font_color='black',
    13821378            vertex_size=300, vertex_colors=None, layout='acyclic', **kwds):
    13831379        """
    13841380        Shows the Graphics object corresponding the Hasse diagram of the
  • sage/graphs/generic_graph.py

    diff --git a/sage/graphs/generic_graph.py b/sage/graphs/generic_graph.py
    a b  
    1429614296        .. NOTE::
    1429714297
    1429814298            - See the documentation of the :mod:`sage.graphs.graph_plot` module
    14299               for information on default arguments of this method.
    14300 
    14301             - Default parameters for this method can also be set through the
    14302               :class:`~sage.misc.decorators.options` mechanism.
     14299              for information and examples of how to define parameters that will
     14300              be applied to **all** graph plots.
     14301
     14302            - Default parameters for this method *and a specific graph* can also
     14303              be set through the :class:`~sage.misc.decorators.options`
     14304              mechanism. For more information on this different way to set
     14305              default parameters, see the help of the :class:`options decorator
     14306              <~sage.misc.decorators.options>`.
    1430314307
    1430414308            - See also the :mod:`sage.graphs.graph_latex` module for ways to use
    1430514309              LaTeX to produce an image of a graph.
     
    1448214486       
    1448314487            sage: G=Graph({'a':['a','b','b','b','e'],'b':['c','d','e'],'c':['c','d','d','d'],'d':['e']},sparse=True)
    1448414488            sage: G.show(pos={'a':[0,1],'b':[1,1],'c':[2,0],'d':[1,0],'e':[0,0]})
    14485        
    1448614489        """
    1448714490        from sage.graphs.graph_plot import GraphPlot
    1448814491        return GraphPlot(graph=self, options=options).plot()
     
    1450814511        from sage.graphs.graph_plot import GraphPlot
    1450914512        from graph_plot import graphplot_options
    1451014513
    14511         # This dictinary only contains the options that graphplot
     14514        # This dictionary only contains the options that graphplot
    1451214515        # understands. These options are removed from kwds at the same
    1451314516        # time.
    1451414517        plot_kwds = {k:kwds.pop(k) for k in graphplot_options if k in kwds}
  • sage/graphs/graph_plot.py

    diff --git a/sage/graphs/graph_plot.py b/sage/graphs/graph_plot.py
    a b  
    2424random and empty graphs), the position dictionary is filled in, instead of using
    2525the spring-layout algorithm.
    2626
     27**Plot options**
     28
     29Here is the list of options accepted by :meth:`GraphPlot.plot` and the
     30constructor of :class:`GraphPlot`.
     31
     32.. csv-table::
     33    :class: contentstable
     34    :widths: 30, 70
     35    :delim: |
     36
     37"""
     38
     39layout_options =   {
     40                    'layout': 'A layout algorithm -- one of : "acyclic", "circular" (plots the graph with vertices evenly distributed on a circle), "ranked", "graphviz", "planar", "spring" (traditional spring layout, using the graph\'s current positions as initial positions), or "tree" (the tree will be plotted in levels, depending on minimum distance for the root).',
     41                    'iterations': 'The number of times to execute the spring layout algorithm.',
     42                    'heights': 'A dictionary mapping heights to the list of vertices at this height.',
     43                    'spring': 'Use spring layout to finalize the current layout.',
     44                    'tree_root': 'A vertex designation for drawing trees. a vertex of the tree to be used as the root for the ``layout="tree"`` option. If no root is specified, then one is chosen at random. Ignored unless ``layout=\'tree\'``',
     45                    'tree_orientation': 'The direction of tree branches -- "up" or "down".',
     46                    'save_pos': 'Whether or not to save the computed position for the graph.',
     47                    'dim': 'The dimension of the layout -- 2 or 3.',
     48                    'prog': 'Which graphviz layout program to use -- one of "circo", "dot", "fdp", "neato", or "twopi".',
     49                    'by_component': 'Whether to do the spring layout by connected component -- a boolean.',
     50                    }
     51
     52graphplot_options = layout_options.copy()
     53
     54graphplot_options.update(
     55                   {'pos': 'The position dictionary of vertices',
     56                    'vertex_labels': 'Whether or not to draw vertex labels.',
     57                    'vertex_colors': 'Dictionary of vertex coloring : each key is a color recognizable by matplotlib, and each corresponding entry is a list of vertices. If a vertex is not listed, it looks invisible on the resulting plot (it doesn\'t get drawn).',
     58                    'vertex_size': 'The size to draw the vertices.',
     59                    'vertex_shape': 'The shape to draw the vertices, Currently unavailable for Multi-edged DiGraphs.',
     60                    'edge_labels': 'Whether or not to draw edge labels.',
     61                    'edge_style': 'The linestyle of the edges-- one of "solid", "dashed", "dotted", dashdot". This currently only works for directed graphs, since we pass off the undirected graph to networkx',
     62                    'edge_color': 'The default color for edges.',
     63                    'edge_colors': 'a dictionary specifying edge colors: each key is a color recognized by matplotlib, and each entry is a list of edges.',
     64                    'color_by_label': 'Whether or not to color the edges by their label values.',
     65                    'partition': 'A partition of the vertex set.  If specified, plot will show each cell in a different color. vertex_colors takes precedence.',
     66                    'loop_size': 'The radius of the smallest loop.',
     67                    'dist': 'The distance between multiedges.',
     68                    'max_dist': 'The max distance range to allow multiedges.',
     69                    'talk': 'Whether to display the vertices in talk mode (larger and white)',
     70                    'graph_border': 'Whether or not to draw a frame around the graph.'})
     71
     72for key, value in graphplot_options.iteritems():
     73    __doc__ += "    ``"+str(key)+"`` | "+str(value)+"\n"
     74
     75__doc__ += """
     76
    2777**Default options**
    2878
    2979This module defines two dictionaries containing default options for the
    30 :meth:`~GraphPlot.plot` and :meth:`~GraphPlot.show` methods. Obviously, these
    31 values are overruled when arguments are given explicitely.
     80:meth:`~GraphPlot.plot` and :meth:`~GraphPlot.show` methods. These two
     81dictionaries are ``sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS`` and
     82``sage.graphs.graph_plot.DEFAULT_PLOT_OPTIONS``.
    3283
    33 Here is how to define the default size of a graph drawing to be ``[4,4]``. The
    34 first call to :meth:`~sage.graphs.generic_graph.show` uses this option, while
    35 the second one does not (a value for ``figsize`` is explicitely given)::
     84Obviously, these values are overruled when arguments are given explicitely.
     85
     86Here is how to define the default size of a graph drawing to be ``[6,6]``. The
     87first two calls to :meth:`~sage.graphs.generic_graph.show` use this option,
     88while the third does not (a value for ``figsize`` is explicitely given)::
     89
     90    sage: sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS['figsize'] = [6,6]
     91    sage: graphs.PetersenGraph().show() # long time
     92    sage: graphs.ChvatalGraph().show()  # long time
     93    sage: graphs.PetersenGraph().show(figsize=[4,4]) # long time
     94
     95We can now reset the default to its initial value, and now display graphs as
     96previously::
    3697
    3798    sage: sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS['figsize'] = [4,4]
    38     sage: g = graphs.PetersenGraph()
    39     sage: g.show() # long time
    40     sage: g.show(figsize=[7,7])
    41 
    42 These two dictionaries are ``sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS`` and
    43 ``sage.graphs.graph_plot.DEFAULT_PLOT_OPTIONS``.
     99    sage: graphs.PetersenGraph().show() # long time
     100    sage: graphs.ChvatalGraph().show()  # long time
    44101
    45102.. NOTE::
    46103
     
    92149from sage.misc.decorators import options
    93150from math import sqrt, cos, sin, atan, pi
    94151
    95 layout_options =   {
    96                     'layout': 'A layout algorithm -- one of "acyclic", "circular", "ranked", "graphviz", "planar", "spring", or "tree".',
    97                     'iterations': 'The number of times to execute the spring layout algorithm.',
    98                     'heights': 'A dictionary mapping heights to the list of vertices at this height.',
    99                     'spring': 'Use spring layout to finalize the current layout.',
    100                     'tree_root': 'A vertex designation for drawing trees.',
    101                     'tree_orientation': 'The direction of tree branches -- "up" or "down".',
    102                     'save_pos': 'Whether or not to save the computed position for the graph.',
    103                     'dim': 'The dimension of the layout -- 2 or 3.',
    104                     'prog': 'Which graphviz layout program to use -- one of "circo", "dot", "fdp", "neato", or "twopi".',
    105                     'by_component': 'Whether to do the spring layout by connected component -- a boolean.',
    106                     }
    107 
    108 graphplot_options = layout_options.copy()
    109 
    110 graphplot_options.update(
    111                    {'pos': 'The position dictionary of vertices',
    112                     'vertex_labels': 'Whether or not to draw vertex labels.',
    113                     'vertex_colors': 'Dictionary of vertex coloring.',
    114                     'vertex_size': 'The size to draw the vertices.',
    115                     'vertex_shape': 'The shape to draw the vertices, Currently unavailable for Multi-edged DiGraphs.',
    116                     'edge_labels': 'Whether or not to draw edge labels.',
    117                     'edge_style': 'The linestyle of the edges-- one of "solid", "dashed", "dotted", dashdot".',
    118                     'edge_color': 'The default color for edges.',
    119                     'edge_colors': 'Dictionary of edge coloring.',
    120                     'color_by_label': 'Whether or not to color the edges by their label values.',
    121                     'partition': 'A partition of the vertex set.  (Draws each cell of vertices in a different color).',
    122                     'loop_size': 'The radius of the smallest loop.',
    123                     'dist': 'The distance between multiedges.',
    124                     'max_dist': 'The max distance range to allow multiedges.',
    125                     'talk': 'Whether to display the vertices in talk mode (larger and white)',
    126                     'graph_border': 'Whether or not to draw a frame around the graph.'})
    127 
    128152DEFAULT_SHOW_OPTIONS = {
    129153    "figsize"             : [4,4]
    130154    }
     
    149173    "loop_size"           : .075
    150174    }
    151175
    152 
    153176class GraphPlot(SageObject):
    154177    def __init__(self, graph, options):
    155178        """
     
    157180        plotting (Di)Graphs.  A ``GraphPlot`` has a plot and show function, as well
    158181        as some functions to set parameters for vertices and edges.  This constructor
    159182        assumes default options are set.  Defaults are shown in the example below.
    160        
     183
    161184        EXAMPLE::
    162185
    163186            sage: from sage.graphs.graph_plot import GraphPlot
    164187            sage: options = {
    165             ...     'vertex_size':200, 
    166             ...     'vertex_labels':True, 
     188            ...     'vertex_size':200,
     189            ...     'vertex_labels':True,
    167190            ...     'layout':None,
    168             ...     'edge_style':'solid', 
    169             ...     'edge_color':'black', 
    170             ...     'edge_colors':None, 
    171             ...     'edge_labels':False, 
    172             ...     'iterations':50, 
    173             ...     'tree_orientation':'down', 
    174             ...     'heights':None, 
    175             ...     'graph_border':False, 
    176             ...     'talk':False, 
    177             ...     'color_by_label':False, 
     191            ...     'edge_style':'solid',
     192            ...     'edge_color':'black',
     193            ...     'edge_colors':None,
     194            ...     'edge_labels':False,
     195            ...     'iterations':50,
     196            ...     'tree_orientation':'down',
     197            ...     'heights':None,
     198            ...     'graph_border':False,
     199            ...     'talk':False,
     200            ...     'color_by_label':False,
    178201            ...     'partition':None,
    179             ...     'dist':.075, 
    180             ...     'max_dist':1.5, 
     202            ...     'dist':.075,
     203            ...     'max_dist':1.5,
    181204            ...     'loop_size':.075}
    182205            sage: g = Graph({0:[1,2], 2:[3], 4:[0,1]})
    183206            sage: GP = GraphPlot(g, options)
     
    186209
    187210            sage: g = graphs.CompleteGraph(2); g.show()
    188211
     212        Wrong input::
     213
     214            sage: graphs.PetersenGraph().plot(kujhfuhf="23")
     215            doctest:...: DeprecationWarning: kujhfuhf is not a registered argument forGraphPlot ! Please tell us that if it should be by writing to sage-devel !
     216            ...
    189217        """
    190218        # Setting the default values if needed
    191219        for k,value in DEFAULT_PLOT_OPTIONS.iteritems():
    192220            if k not in options:
    193221                options[k] = value
    194222
     223        for opt in options:
     224            if not opt in graphplot_options:
     225                from sage.misc.superseded import deprecation
     226                deprecation(13891, (str(opt)+" is not a registered argument for"+
     227                                      "GraphPlot ! Please tell us that if it "+
     228                                      "should be by writing to sage-devel !"))
     229
    195230        self._plot_components = {}
    196231        self._nodelist = graph.vertices()
    197232        self._graph = graph
     
    276311        is called by the constructor but can also be called to make updates to
    277312        the vertex options of an existing ``GraphPlot`` object.  Note that the
    278313        changes are cumulative.
    279        
     314
    280315        EXAMPLES::
    281316
    282317            sage: g = Graph({}, loops=True, multiedges=True, sparse=True)
     
    666701
    667702        self.plot().show(**kwds)
    668703
    669     def plot(self, **kwds):
     704    def plot(self):
    670705        """
    671706        Returns a graphics object representing the (di)graph.
    672707
    673         INPUT:
    674 
    675         - ``pos`` -- an optional positioning dictionar
    676 
    677         - ``layout`` -- what kind of layout to use, takes precedence over ``pos``
    678 
    679           - 'circular' -- plots the graph with vertices evenly distributed
    680             on a circle
    681 
    682           - 'spring' -- uses the traditional spring layout, using the
    683             graph's current positions as initial positions
    684 
    685           - 'tree' -- the (di)graph must be a tree. One can specify the root
    686             of the tree using the keyword ``tree_root``, otherwise a root
    687             will be selected at random. Then the tree will be plotted in
    688             levels, depending on minimum distance for the root.
    689 
    690         - ``vertex_labels`` -- whether to print vertex labels
    691 
    692         - ``edge_labels`` -- whether to print edge labels. By default, ``False``,
    693           but if ``True``, the result of ``str(l)`` is printed on the edge for
    694           each label l. Labels equal to None are not printed (to set edge
    695           labels, see :meth:`~sage.graphs.generic_graph.GenericGraph.set_edge_label`).
    696 
    697         - ``vertex_size`` -- size of vertices displayed
    698 
    699         - ``vertex_shape`` -- the shape to draw the vertices (Not available for
    700           multiedge digraphs.
    701 
    702         - ``graph_border`` -- whether to include a box around the graph
    703 
    704         - ``vertex_colors`` -- optional dictionary to specify vertex colors: each
    705           key is a color recognizable by matplotlib, and each corresponding
    706           entry is a list of vertices. If a vertex is not listed, it looks
    707           invisible on the resulting plot (it doesn't get drawn).
    708 
    709         - ``edge_colors`` -- a dictionary specifying edge colors: each key is a
    710           color recognized by matplotlib, and each entry is a list of edges.
    711 
    712         - ``partition`` -- a partition of the vertex set. if specified, plot will
    713           show each cell in a different color. vertex_colors takes precedence.
    714 
    715         - ``talk`` -- if ``True``, prints large vertices with white backgrounds
    716           so that labels are legible on slides
    717 
    718         - ``iterations`` -- how many iterations of the spring layout algorithm to
    719           go through, if applicable
    720 
    721         - ``color_by_label`` -- if ``True``, color edges by their labels
    722 
    723         - ``heights`` -- if specified, this is a dictionary from a set of
    724           floating point heights to a set of vertices
    725 
    726         - ``edge_style`` -- keyword arguments passed into the
    727           edge-drawing routine.  This currently only works for
    728           directed graphs, since we pass off the undirected graph to
    729           networkx
    730 
    731         - ``tree_root`` -- a vertex of the tree to be used as the root for
    732           the ``layout="tree"`` option. If no root is specified, then one
    733           is chosen at random. Ignored unless ``layout='tree'``.
    734 
    735         - ``tree_orientation`` -- "up" or "down" (default is "down").
    736           If "up" (resp., "down"), then the root of the tree will
    737           appear on the bottom (resp., top) and the tree will grow
    738           upwards (resp. downwards). Ignored unless ``layout='tree'``.
    739 
    740         - ``save_pos`` -- save position computed during plotting
    741 
    742708        .. NOTE::
    743709
    744710            See :mod:`the module's documentation <sage.graphs.graph_plot>` for
    745711            information on default values of this method.
    746712
    747         EXAMPLES:
    748 
    749         Let's list all possible options::
    750 
    751             sage: from sage.graphs.graph_plot import graphplot_options
    752             sage: list(sorted(graphplot_options.iteritems()))
    753             [('by_component', 'Whether to do the spring layout by connected component -- a boolean.'),
    754              ('color_by_label', 'Whether or not to color the edges by their label values.'),
    755              ('dim', 'The dimension of the layout -- 2 or 3.'),
    756              ('dist', 'The distance between multiedges.'),
    757              ('edge_color', 'The default color for edges.'),
    758              ('edge_colors', 'Dictionary of edge coloring.'),
    759              ('edge_labels', 'Whether or not to draw edge labels.'),
    760              ('edge_style', 'The linestyle of the edges-- one of "solid", "dashed", "dotted", dashdot".'),
    761              ('graph_border', 'Whether or not to draw a frame around the graph.'),
    762              ('heights', 'A dictionary mapping heights to the list of vertices at this height.'),
    763              ('iterations', 'The number of times to execute the spring layout algorithm.'),
    764              ('layout', 'A layout algorithm -- one of "acyclic", "circular", "ranked", "graphviz", "planar", "spring", or "tree".'),
    765              ('loop_size', 'The radius of the smallest loop.'),
    766              ('max_dist', 'The max distance range to allow multiedges.'),
    767              ('partition', 'A partition of the vertex set.  (Draws each cell of vertices in a different color).'),
    768              ('pos', 'The position dictionary of vertices'),
    769              ('prog', 'Which graphviz layout program to use -- one of "circo", "dot", "fdp", "neato", or "twopi".'),
    770              ('save_pos', 'Whether or not to save the computed position for the graph.'),
    771              ('spring', 'Use spring layout to finalize the current layout.'),
    772              ('talk', 'Whether to display the vertices in talk mode (larger and white)'),
    773              ('tree_orientation', 'The direction of tree branches -- "up" or "down".'),
    774              ('tree_root', 'A vertex designation for drawing trees.'),
    775              ('vertex_colors', 'Dictionary of vertex coloring.'),
    776              ('vertex_labels', 'Whether or not to draw vertex labels.'),
    777              ('vertex_shape', 'The shape to draw the vertices, Currently unavailable for Multi-edged DiGraphs.'),
    778              ('vertex_size', 'The size to draw the vertices.')]
    779 
    780713        We can specify some pretty precise plotting of familiar graphs::
    781714
    782715            sage: from math import sin, cos, pi
     
    814747            ...    D.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')')
    815748            sage: D.graphplot(edge_labels=True, layout='circular').show()
    816749
    817 
    818750        This example shows off the coloring of edges::
    819751
    820752            sage: from sage.plot.colors import rainbow
     
    848780
    849781            sage: D = DiGraph({0:[0,1], 1:[2], 2:[3]}, loops=True)
    850782            sage: D.show()
    851             sage: D.show(edge_colors={(0,1,0):[(0,1,None),(1,2,None)],(0,0,0):[(2,3,None)]}) 
     783            sage: D.show(edge_colors={(0,1,0):[(0,1,None),(1,2,None)],(0,0,0):[(2,3,None)]})
    852784
    853785        More options::
    854786
     
    900832
    901833            sage: D = DiGraph({0:[1,2,3], 2:[1,4], 3:[0]})
    902834            sage: D.graphplot().show()
    903            
     835
    904836            sage: D = DiGraph(multiedges=True, sparse=True)
    905837            sage: for i in range(5):
    906838            ...     D.add_edge((i,i+1,'a'))
    907839            ...     D.add_edge((i,i-1,'b'))
    908840            sage: D.graphplot(edge_labels=True,edge_colors=D._color_by_label()).plot()
    909            
     841
    910842            sage: g = Graph({}, loops=True, multiedges=True, sparse=True)
    911843            sage: g.add_edges([(0,0,'a'),(0,0,'b'),(0,1,'c'),(0,1,'d'),
    912844            ...     (0,1,'e'),(0,1,'f'),(0,1,'f'),(2,1,'g'),(2,2,'h')])
     
    940872        Compute a nice layout of a tree.
    941873
    942874        INPUT:
    943        
     875
    944876        - ``root`` -- the root vertex.
    945        
     877
    946878        - ``orientation`` -- Whether to place the root
    947879          at the top or at the bottom :
    948880
    949             - ``orientation="down"`` -- children are placed below 
     881            - ``orientation="down"`` -- children are placed below
    950882              their parent
    951883            - ``orientation="top"`` -- children are placed above
    952884              their parent
    953        
    954885
    955886        EXAMPLES::
    956887