Ticket #13891: trac_13891-all_in_one.patch

File trac_13891-all_in_one.patch, 47.3 KB (added by ncohen, 6 years ago)

Apply only this.

  • sage/combinat/cluster_algebra_quiver/quiver.py

    # HG changeset patch
    # User Nathann Cohen <nathann.cohen@gmail.com>
    # Date 1356905040 -3600
    # Node ID bf66fe56f1850d728bfa5ea478b2e8d92475f2cc
    # Parent  f4cbda7c354e4f5c27adb054b495dcafce5d5db1
    Default parameters for Graph.plot() and Graph.show()
    * * *
    Default parameters for Graph.plot() and Graph.show() -- second pass
    * * *
    Default parameters for Graph.plot() and Graph.show() -- third pass
    * * *
    Default parameters for Graph.plot() and Graph.show() -- typos and useless graphplot method
    * * *
    Default parameters for Graph.plot() and Graph.show() -- fifth pass
    * * *
    Default parameters for Graph.plot() and Graph.show() -- smallfix
    * * *
    Default parameters for Graph.plot() and Graph.show() -- Doc. Again.
    * * *
    Default parameters for Graph.plot() and Graph.show() -- docfix again
    
    diff --git a/sage/combinat/cluster_algebra_quiver/quiver.py b/sage/combinat/cluster_algebra_quiver/quiver.py
    a b  
    453453            'edge_colors': color_dict,
    454454            'vertex_colors': vertex_color_dict,
    455455            'edge_labels' : True,
    456             'scaling_term' : 0.1
    457456        }
    458457        if circular:
    459458            pp = _graphs_concentric_circles( n, m )
  • sage/combinat/posets/posets.py

    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
     
    14031399            sage: D.show(element_labels=elm_labs)
    14041400        """
    14051401        self.plot(label_elements=label_elements, element_labels=element_labels,
    1406             label_font_size=label_font_size,label_font_color=label_font_color,
    14071402            vertex_size=vertex_size, vertex_colors=vertex_colors, layout=layout).show(**kwds)
    14081403
    14091404    def level_sets(self):
  • sage/graphs/generic_graph.py

    diff --git a/sage/graphs/generic_graph.py b/sage/graphs/generic_graph.py
    a b  
    309309from sage.rings.rational import Rational
    310310from generic_graph_pyx import GenericGraph_pyx, spring_layout_fast
    311311from sage.graphs.dot2tex_utils import assert_have_dot2tex
     312from sage.misc.superseded import deprecated_function_alias
    312313
    313314class GenericGraph(GenericGraph_pyx):
    314315    """
     
    323324        Every graph carries a dictionary of options, which is set
    324325        here to ``None``.  Some options are added to the global
    325326        :data:`sage.misc.latex.latex` instance which will insure
    326         that if `\mbox{\rm\LaTeX}` is used to render the graph,
     327        that if LaTeX is used to render the graph,
    327328        then the right packages are loaded and MathJax reacts
    328329        properly.
    329330
     
    592593        return s
    593594
    594595    def _latex_(self):
    595         r""" Returns a string to render the graph using
    596         `\mbox{\rm{\LaTeX}}`.
     596        r"""
     597
     598        Returns a string to render the graph using LaTeX.
    597599
    598600        To adjust the string, use the
    599601        :meth:`set_latex_options` method to set options,
     
    1369913701        Returns an instance of
    1370013702        :class:`~sage.graphs.graph_latex.GraphLatex` for the graph.
    1370113703
    13702         Changes to this object will affect the `\mbox{\rm\LaTeX}`
    13703         version of the graph.    For a full explanation of
    13704         how to use LaTeX to render graphs, see the introduction to the
    13705         :mod:`~sage.graphs.graph_latex` module.
     13704        Changes to this object will affect the LaTeX version of the graph.  For
     13705        a full explanation of how to use LaTeX to render graphs, see the
     13706        introduction to the :mod:`~sage.graphs.graph_latex` module.
    1370613707
    1370713708        EXAMPLES::
    1370813709
     
    1380013801        Here is the list of all the available layout options::
    1380113802
    1380213803            sage: from sage.graphs.graph_plot import layout_options
    13803             sage: list(sorted(layout_options.iteritems()))
    13804             [('by_component', 'Whether to do the spring layout by connected component -- a boolean.'),
    13805              ('dim', 'The dimension of the layout -- 2 or 3.'),
    13806              ('heights', 'A dictionary mapping heights to the list of vertices at this height.'),
    13807              ('iterations', 'The number of times to execute the spring layout algorithm.'),
    13808              ('layout', 'A layout algorithm -- one of "acyclic", "circular", "ranked", "graphviz", "planar", "spring", or "tree".'),
    13809              ('prog', 'Which graphviz layout program to use -- one of "circo", "dot", "fdp", "neato", or "twopi".'),
    13810              ('save_pos', 'Whether or not to save the computed position for the graph.'),
    13811              ('spring', 'Use spring layout to finalize the current layout.'),
    13812              ('tree_orientation', 'The direction of tree branches -- "up" or "down".'),
    13813              ('tree_root', 'A vertex designation for drawing trees.')]
     13804            sage: for key, value in list(sorted(layout_options.iteritems())):
     13805            ...      print "option", key, ":", value
     13806            option by_component : Whether to do the spring layout by connected component -- a boolean.
     13807            option dim : The dimension of the layout -- 2 or 3.
     13808            option heights : A dictionary mapping heights to the list of vertices at this height.
     13809            option iterations : The number of times to execute the spring layout algorithm.
     13810            option 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).
     13811            option prog : Which graphviz layout program to use -- one of "circo", "dot", "fdp", "neato", or "twopi".
     13812            option save_pos : Whether or not to save the computed position for the graph.
     13813            option spring : Use spring layout to finalize the current layout.
     13814            option tree_orientation : The direction of tree branches -- "up" or "down".
     13815            option 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'``
    1381413816
    1381513817        Some of them only apply to certain layout algorithms. For
    1381613818        details, see :meth:`.layout_acyclic`, :meth:`.layout_planar`,
     
    1418714189
    1418814190        return [xmin, xmax, ymin, ymax]
    1418914191
    14190 
    14191 
    14192     @options(vertex_size=200, vertex_labels=True, layout=None,
    14193             edge_style='solid', edge_color='black',edge_colors=None, edge_labels=False,
    14194             iterations=50, tree_orientation='down', heights=None, graph_border=False,
    14195             talk=False, color_by_label=False, partition=None,
    14196             dist = .075, max_dist=1.5, loop_size=.075)
    1419714192    def graphplot(self, **options):
    1419814193        """
    1419914194        Returns a GraphPlot object.
    14200        
    14201        
     14195
    1420214196        EXAMPLES:
    14203        
     14197
    1420414198        Creating a graphplot object uses the same options as graph.plot()::
    14205        
     14199
    1420614200            sage: g = Graph({}, loops=True, multiedges=True, sparse=True)
    1420714201            sage: g.add_edges([(0,0,'a'),(0,0,'b'),(0,1,'c'),(0,1,'d'),
    1420814202            ...     (0,1,'e'),(0,1,'f'),(0,1,'f'),(2,1,'g'),(2,2,'h')])
     
    1421114205            sage: GP.plot()
    1421214206
    1421314207        We can modify the graphplot object.  Notice that the changes are cumulative::
    14214        
     14208
    1421514209            sage: GP.set_edges(edge_style='solid')
    1421614210            sage: GP.plot()
    1421714211            sage: GP.set_vertices(talk=True)
     
    1422014214        from sage.graphs.graph_plot import GraphPlot
    1422114215        return GraphPlot(graph=self, options=options)
    1422214216
    14223     @options(vertex_size=200, vertex_labels=True, layout=None,
    14224             edge_style='solid', edge_color = 'black', edge_colors=None, edge_labels=False,
    14225             iterations=50, tree_orientation='down', heights=None, graph_border=False,
    14226             talk=False, color_by_label=False, partition=None,
    14227             dist = .075, max_dist=1.5, loop_size=.075)
     14217    @options()
    1422814218    def plot(self, **options):
    1422914219        r"""
    1423014220        Returns a graphics object representing the (di)graph.
    14231         See also the :mod:`sage.graphs.graph_latex` module for ways
    14232         to use  `\mbox{\rm\LaTeX}` to produce an image of a graph.
    14233        
    14234         INPUT:
    14235            
     14221
     14222        INPUT:
     14223
    1423614224        - ``pos`` - an optional positioning dictionary
    14237            
     14225
    1423814226        - ``layout`` - what kind of layout to use, takes precedence
    1423914227          over pos
    14240                
     14228
    1424114229           - 'circular' -- plots the graph with vertices evenly
    1424214230             distributed on a circle
    14243              
     14231
    1424414232           - 'spring' - uses the traditional spring layout, using the
    1424514233             graph's current positions as initial positions
    14246                
     14234
    1424714235           - 'tree' - the (di)graph must be a tree. One can specify
    1424814236             the root of the tree using the keyword tree_root,
    1424914237             otherwise a root will be selected at random. Then the
    1425014238             tree will be plotted in levels, depending on minimum
    1425114239             distance for the root.
    14252            
     14240
    1425314241        - ``vertex_labels`` - whether to print vertex labels
    1425414242
    1425514243        - ``edge_labels`` - whether to print edge labels. By default,
    1425614244          False, but if True, the result of str(l) is printed on the
    1425714245          edge for each label l. Labels equal to None are not printed
    1425814246          (to set edge labels, see set_edge_label).
    14259            
     14247
    1426014248        - ``vertex_size`` - size of vertices displayed
    1426114249
    1426214250        - ``vertex_shape`` - the shape to draw the vertices (Not
    1426314251          available for multiedge digraphs.)
    14264                
     14252
    1426514253        - ``graph_border`` - whether to include a box around the graph
    1426614254
    1426714255        - ``vertex_colors`` - optional dictionary to specify vertex
     
    1426914257          each corresponding entry is a list of vertices. If a vertex
    1427014258          is not listed, it looks invisible on the resulting plot (it
    1427114259          doesn't get drawn).
    14272                
     14260
    1427314261        - ``edge_colors`` - a dictionary specifying edge colors: each
    1427414262          key is a color recognized by matplotlib, and each entry is a
    1427514263          list of edges.
     
    1428814276
    1428914277        - ``heights`` - if specified, this is a dictionary from a set
    1429014278          of floating point heights to a set of vertices
    14291                
     14279
    1429214280        - ``edge_style`` - keyword arguments passed into the
    1429314281          edge-drawing routine.  This currently only works for
    1429414282          directed graphs, since we pass off the undirected graph to
     
    1429614284
    1429714285        - ``tree_root`` - a vertex of the tree to be used as the root
    1429814286          for the layout="tree" option. If no root is specified, then one
    14299           is chosen at random. Ignored unless layout='tree'. 
    14300 
    14301         - ``tree_orientation`` - "up" or "down" (default is "down"). 
     14287          is chosen at random. Ignored unless layout='tree'.
     14288
     14289        - ``tree_orientation`` - "up" or "down" (default is "down").
    1430214290          If "up" (resp., "down"), then the root of the tree will
    1430314291          appear on the bottom (resp., top) and the tree will grow
    1430414292          upwards (resp. downwards). Ignored unless layout='tree'.
    1430514293
    1430614294        - ``save_pos`` - save position computed during plotting
    14307            
    14308         EXAMPLES::
    14309        
     14295
     14296        .. NOTE::
     14297
     14298            - See the documentation of the :mod:`sage.graphs.graph_plot` module
     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>`.
     14307
     14308            - See also the :mod:`sage.graphs.graph_latex` module for ways to use
     14309              LaTeX to produce an image of a graph.
     14310
     14311        EXAMPLES::
     14312
    1431014313            sage: from sage.graphs.graph_plot import graphplot_options
    1431114314            sage: list(sorted(graphplot_options.iteritems()))
    1431214315            [...]
     
    1442714430             7: [1.46..., -0.473...],
    1442814431             8: [0.902..., 0.773...],
    1442914432             9: [2.48..., -0.119...]}
    14430        
    14431         ::
    14432        
     14433
     14434        ::
     14435
    1443314436            sage: T = list(graphs.trees(7))
    1443414437            sage: t = T[3]
    1443514438            sage: t.plot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]})
    14436        
    14437         ::
    14438        
     14439
     14440        ::
     14441
    1443914442            sage: T = list(graphs.trees(7))
    1444014443            sage: t = T[3]
    1444114444            sage: t.plot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]})
     
    1444714450            sage: t.set_edge_label(2,6,3/2)
    1444814451            sage: t.set_edge_label(0,4,66)
    1444914452            sage: t.plot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}, edge_labels=True)
    14450        
    14451         ::
    14452        
     14453
     14454        ::
     14455
    1445314456            sage: T = list(graphs.trees(7))
    1445414457            sage: t = T[3]
    1445514458            sage: t.plot(layout='tree')
    14456        
    14457         ::
    14458        
     14459
     14460        ::
     14461
    1445914462            sage: t = DiGraph('JCC???@A??GO??CO??GO??')
    1446014463            sage: t.plot(layout='tree', tree_root=0, tree_orientation="up")
    1446114464            sage: D = DiGraph({0:[1,2,3], 2:[1,4], 3:[0]})
    1446214465            sage: D.plot()
    14463            
     14466
    1446414467            sage: D = DiGraph(multiedges=True,sparse=True)
    1446514468            sage: for i in range(5):
    1446614469            ...     D.add_edge((i,i+1,'a'))
    1446714470            ...     D.add_edge((i,i-1,'b'))
    1446814471            sage: D.plot(edge_labels=True,edge_colors=D._color_by_label())
    14469            
     14472
    1447014473            sage: g = Graph({}, loops=True, multiedges=True,sparse=True)
    1447114474            sage: g.add_edges([(0,0,'a'),(0,0,'b'),(0,1,'c'),(0,1,'d'),
    1447214475            ...     (0,1,'e'),(0,1,'f'),(0,1,'f'),(2,1,'g'),(2,2,'h')])
     
    1448014483            sage: P = D.plot()
    1448114484
    1448214485        ::
    14483        
     14486
    1448414487            sage: G=Graph({'a':['a','b','b','b','e'],'b':['c','d','e'],'c':['c','d','d','d'],'d':['e']},sparse=True)
    1448514488            sage: G.show(pos={'a':[0,1],'b':[1,1],'c':[2,0],'d':[1,0],'e':[0,0]})
    14486        
    14487         """
    14488         from sage.graphs.graph_plot import GraphPlot
    14489         return GraphPlot(graph=self, options=options).plot()
     14489        """
     14490        return self.graphplot(**options).plot()
    1449014491
    1449114492    def show(self, **kwds):
    1449214493        """
    1449314494        Shows the (di)graph.
    14494        
    14495         For syntax and lengthy documentation, see G.plot?. Any options not
    14496         used by plot will be passed on to the Graphics.show method.
    14497        
    14498         EXAMPLES::
    14499        
     14495
     14496        INPUT:
     14497
     14498        This method accepts any option understood by
     14499        :meth:`~sage.graphs.generic_graph.plot` (graph-specific) or by
     14500        :meth:`sage.plot.graphics.Graphics.show`.
     14501
     14502        .. NOTE::
     14503
     14504            See the documentation of the :mod:`sage.graphs.graph_plot` module
     14505            for information on default arguments of this method.
     14506
     14507        EXAMPLES::
     14508
    1450014509            sage: C = graphs.CubeGraph(8)
    1450114510            sage: P = C.plot(vertex_labels=False, vertex_size=0, graph_border=True)
    1450214511            sage: P.show()  # long time (3s on sage.math, 2011)
    1450314512        """
    14504         kwds.setdefault('figsize', [4,4])
     14513        from sage.graphs.graph_plot import GraphPlot
    1450514514        from graph_plot import graphplot_options
    14506         vars = graphplot_options.keys()
    14507         plot_kwds = {}
    14508         for kwd in vars:
    14509             if kwds.has_key(kwd):
    14510                 plot_kwds[kwd] = kwds.pop(kwd)
    14511         self.plot(**plot_kwds).show(**kwds)
     14515
     14516        # This dictionary only contains the options that graphplot
     14517        # understands. These options are removed from kwds at the same
     14518        # time.
     14519        plot_kwds = {k:kwds.pop(k) for k in graphplot_options if k in kwds}
     14520
     14521        return self.graphplot(**plot_kwds).show(**kwds)
    1451214522
    1451314523    def plot3d(self, bgcolor=(1,1,1), vertex_colors=None, vertex_size=0.06,
    1451414524                     edge_colors=None, edge_size=0.02, edge_size2=0.0325,
    1451514525                     pos3d=None, color_by_label=False,
    1451614526                     engine='jmol', **kwds):
    1451714527        r"""
    14518         Plot a graph in three dimensions.    See also the
    14519         :mod:`sage.graphs.graph_latex` module for ways to use
    14520         `\mbox{\rm\LaTeX}` to produce an image of a graph.
    14521        
    14522         INPUT:
    14523        
    14524        
     14528        Plot a graph in three dimensions.
     14529
     14530        See also the :mod:`sage.graphs.graph_latex` module for ways to use LaTeX
     14531        to produce an image of a graph.
     14532
     14533        INPUT:
     14534
    1452514535        -  ``bgcolor`` - rgb tuple (default: (1,1,1))
    14526        
     14536
    1452714537        -  ``vertex_size`` - float (default: 0.06)
    14528        
     14538
    1452914539        -  ``vertex_colors`` - optional dictionary to specify
    1453014540           vertex colors: each key is a color recognizable by tachyon (rgb
    1453114541           tuple (default: (1,0,0))), and each corresponding entry is a list
    1453214542           of vertices. If a vertex is not listed, it looks invisible on the
    1453314543           resulting plot (it doesn't get drawn).
    14534        
     14544
    1453514545        -  ``edge_colors`` - a dictionary specifying edge
    1453614546           colors: each key is a color recognized by tachyon ( default:
    1453714547           (0,0,0) ), and each entry is a list of edges.
  • sage/graphs/graph_plot.py

    diff --git a/sage/graphs/graph_plot.py b/sage/graphs/graph_plot.py
    a b  
    11"""
    22Graph Plotting
    33
     4*(For LaTeX drawings of graphs, see the* :mod:`~sage.graphs.graph_latex` *module.)*
     5
    46All graphs have an associated Sage graphics object, which you can display::
    57
    68    sage: G = graphs.WheelGraph(15)
     
    2224random and empty graphs), the position dictionary is filled in, instead of using
    2325the spring-layout algorithm.
    2426
    25 Functions and methods
    26 ---------------------
     27**Plot options**
     28
     29Here is the list of options accepted by :meth:`GenericGraph.plot
     30<sage.graphs.generic_graph.GenericGraph.plot>` and the constructor of
     31:class:`GraphPlot`.
     32
     33.. csv-table::
     34    :class: contentstable
     35    :widths: 30, 70
     36    :delim: |
     37
     38"""
     39
     40layout_options =   {
     41                    '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).',
     42                    'iterations': 'The number of times to execute the spring layout algorithm.',
     43                    'heights': 'A dictionary mapping heights to the list of vertices at this height.',
     44                    'spring': 'Use spring layout to finalize the current layout.',
     45                    '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\'``',
     46                    'tree_orientation': 'The direction of tree branches -- "up" or "down".',
     47                    'save_pos': 'Whether or not to save the computed position for the graph.',
     48                    'dim': 'The dimension of the layout -- 2 or 3.',
     49                    'prog': 'Which graphviz layout program to use -- one of "circo", "dot", "fdp", "neato", or "twopi".',
     50                    'by_component': 'Whether to do the spring layout by connected component -- a boolean.',
     51                    }
     52
     53graphplot_options = layout_options.copy()
     54
     55graphplot_options.update(
     56                   {'pos': 'The position dictionary of vertices',
     57                    'vertex_labels': 'Whether or not to draw vertex labels.',
     58                    '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).',
     59                    'vertex_size': 'The size to draw the vertices.',
     60                    'vertex_shape': 'The shape to draw the vertices, Currently unavailable for Multi-edged DiGraphs.',
     61                    'edge_labels': 'Whether or not to draw edge labels.',
     62                    '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',
     63                    'edge_color': 'The default color for edges.',
     64                    'edge_colors': 'a dictionary specifying edge colors: each key is a color recognized by matplotlib, and each entry is a list of edges.',
     65                    'color_by_label': 'Whether or not to color the edges by their label values.',
     66                    'partition': 'A partition of the vertex set.  If specified, plot will show each cell in a different color. vertex_colors takes precedence.',
     67                    'loop_size': 'The radius of the smallest loop.',
     68                    'dist': 'The distance between multiedges.',
     69                    'max_dist': 'The max distance range to allow multiedges.',
     70                    'talk': 'Whether to display the vertices in talk mode (larger and white)',
     71                    'graph_border': 'Whether or not to draw a frame around the graph.'})
     72
     73for key, value in graphplot_options.iteritems():
     74    __doc__ += "    ``"+str(key)+"`` | "+str(value)+"\n"
     75
     76
     77__doc__ += """
     78**Default options**
     79
     80This module defines two dictionaries containing default options for the
     81:meth:`GenericGraph.plot` and :meth:`GenericGraph.show` methods. These two
     82dictionaries are ``sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS`` and
     83``sage.graphs.graph_plot.DEFAULT_PLOT_OPTIONS``.
     84
     85Obviously, these values are overruled when arguments are given explicitely.
     86
     87Here is how to define the default size of a graph drawing to be ``[6,6]``. The
     88first two calls to :meth:`~sage.graphs.generic_graph.show` use this option,
     89while the third does not (a value for ``figsize`` is explicitely given)::
     90
     91    sage: sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS['figsize'] = [6,6]
     92    sage: graphs.PetersenGraph().show() # long time
     93    sage: graphs.ChvatalGraph().show()  # long time
     94    sage: graphs.PetersenGraph().show(figsize=[4,4]) # long time
     95
     96We can now reset the default to its initial value, and now display graphs as
     97previously::
     98
     99    sage: sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS['figsize'] = [4,4]
     100    sage: graphs.PetersenGraph().show() # long time
     101    sage: graphs.ChvatalGraph().show()  # long time
     102
     103.. NOTE::
     104
     105    * While ``DEFAULT_PLOT_OPTIONS`` affects both ``G.show()`` and ``G.plot()``,
     106      settings from ``DEFAULT_SHOW_OPTIONS`` only affects ``G.show()``.
     107
     108    * In order to define a default value permanently, you can add a couple of
     109      lines to :doc:`Sage's startup scripts <../../startup>`. Example ::
     110
     111       sage: import sage.graphs.graph_plot
     112       sage: sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS['figsize'] = [4,4]
     113
     114**Index of methods and functions**
     115
     116.. csv-table::
     117    :class: contentstable
     118    :widths: 30, 70
     119    :delim: |
     120
     121    :meth:`GraphPlot.set_pos` | Sets the position plotting parameters for this GraphPlot.
     122    :meth:`GraphPlot.set_vertices` | Sets the vertex plotting parameters for this GraphPlot.
     123    :meth:`GraphPlot.set_edges` | Sets the edge (or arrow) plotting parameters for the GraphPlot object.
     124    :meth:`GraphPlot.show` | Shows the (Di)Graph associated with this GraphPlot object.
     125    :meth:`GraphPlot.plot` | Returns a graphics object representing the (di)graph.
     126    :meth:`GraphPlot.layout_tree` | Compute a nice layout of a tree.
     127    :meth:`~sage.graphs.graph_plot._circle_embedding` | Sets some vertices on a circle in the embedding of a graph G.
     128    :meth:`~sage.graphs.graph_plot._line_embedding` | Sets some vertices on a line in the embedding of a graph G.
     129
     130Methods and classes
     131-------------------
     132.. autofunction:: _circle_embedding
     133.. autofunction:: _line_embedding
    27134"""
    28135
    29136#*****************************************************************************
     
    46153from sage.misc.decorators import options
    47154from math import sqrt, cos, sin, atan, pi
    48155
    49 layout_options =   {
    50                     'layout': 'A layout algorithm -- one of "acyclic", "circular", "ranked", "graphviz", "planar", "spring", or "tree".',
    51                     'iterations': 'The number of times to execute the spring layout algorithm.',
    52                     'heights': 'A dictionary mapping heights to the list of vertices at this height.',
    53                     'spring': 'Use spring layout to finalize the current layout.',
    54                     'tree_root': 'A vertex designation for drawing trees.',
    55                     'tree_orientation': 'The direction of tree branches -- "up" or "down".',
    56                     'save_pos': 'Whether or not to save the computed position for the graph.',
    57                     'dim': 'The dimension of the layout -- 2 or 3.',
    58                     'prog': 'Which graphviz layout program to use -- one of "circo", "dot", "fdp", "neato", or "twopi".',
    59                     'by_component': 'Whether to do the spring layout by connected component -- a boolean.',
    60                     }
     156DEFAULT_SHOW_OPTIONS = {
     157    "figsize"             : [4,4]
     158    }
    61159
    62 graphplot_options = layout_options.copy()
    63 graphplot_options.update(
    64                    {'pos': 'The position dictionary of vertices',
    65                     'vertex_labels': 'Whether or not to draw vertex labels.',
    66                     'vertex_colors': 'Dictionary of vertex coloring.',
    67                     'vertex_size': 'The size to draw the vertices.',
    68                     'vertex_shape': 'The shape to draw the vertices, Currently unavailable for Multi-edged DiGraphs.',
    69                     'edge_labels': 'Whether or not to draw edge labels.',
    70                     'edge_style': 'The linestyle of the edges-- one of "solid", "dashed", "dotted", dashdot".',
    71                     'edge_color': 'The default color for edges.',
    72                     'edge_colors': 'Dictionary of edge coloring.',
    73                     'color_by_label': 'Whether or not to color the edges by their label values.',
    74                     'partition': 'A partition of the vertex set.  (Draws each cell of vertices in a different color).',
    75                     'loop_size': 'The radius of the smallest loop.',
    76                     'dist': 'The distance between multiedges.',
    77                     'max_dist': 'The max distance range to allow multiedges.',
    78                     'talk': 'Whether to display the vertices in talk mode (larger and white)',
    79                     'graph_border': 'Whether or not to draw a frame around the graph.'})
     160DEFAULT_PLOT_OPTIONS = {
     161    "vertex_size"         : 200,
     162    "vertex_labels"       : True,
     163    "layout"              : None,
     164    "edge_style"          : 'solid',
     165    "edge_color"          : 'black',
     166    "edge_colors"         : None,
     167    "edge_labels"         : False,
     168    "iterations"          : 50,
     169    "tree_orientation"    : 'down',
     170    "heights"             : None,
     171    "graph_border"        : False,
     172    "talk"                : False,
     173    "color_by_label"      : False,
     174    "partition"           : None,
     175    "dist"                : .075,
     176    "max_dist"            : 1.5,
     177    "loop_size"           : .075
     178    }
    80179
    81180class GraphPlot(SageObject):
    82181    def __init__(self, graph, options):
     
    85184        plotting (Di)Graphs.  A ``GraphPlot`` has a plot and show function, as well
    86185        as some functions to set parameters for vertices and edges.  This constructor
    87186        assumes default options are set.  Defaults are shown in the example below.
    88        
     187
    89188        EXAMPLE::
    90189
    91190            sage: from sage.graphs.graph_plot import GraphPlot
    92191            sage: options = {
    93             ...     'vertex_size':200, 
    94             ...     'vertex_labels':True, 
     192            ...     'vertex_size':200,
     193            ...     'vertex_labels':True,
    95194            ...     'layout':None,
    96             ...     'edge_style':'solid', 
    97             ...     'edge_color':'black', 
    98             ...     'edge_colors':None, 
    99             ...     'edge_labels':False, 
    100             ...     'iterations':50, 
    101             ...     'tree_orientation':'down', 
    102             ...     'heights':None, 
    103             ...     'graph_border':False, 
    104             ...     'talk':False, 
    105             ...     'color_by_label':False, 
     195            ...     'edge_style':'solid',
     196            ...     'edge_color':'black',
     197            ...     'edge_colors':None,
     198            ...     'edge_labels':False,
     199            ...     'iterations':50,
     200            ...     'tree_orientation':'down',
     201            ...     'heights':None,
     202            ...     'graph_border':False,
     203            ...     'talk':False,
     204            ...     'color_by_label':False,
    106205            ...     'partition':None,
    107             ...     'dist':.075, 
    108             ...     'max_dist':1.5, 
     206            ...     'dist':.075,
     207            ...     'max_dist':1.5,
    109208            ...     'loop_size':.075}
    110209            sage: g = Graph({0:[1,2], 2:[3], 4:[0,1]})
    111210            sage: GP = GraphPlot(g, options)
     
    114213
    115214            sage: g = graphs.CompleteGraph(2); g.show()
    116215
     216        Wrong input::
     217
     218            sage: graphs.PetersenGraph().plot(kujhfuhf="23")
     219            doctest:...: DeprecationWarning: You provided kujhfuhf as an
     220            argument to a function which has always silently ignored its
     221            inputs. This method may soon be updated so that the method raises an
     222            exception instead of this warning, which will break your code : to
     223            be on the safe side, update it !
     224            ...
    117225        """
     226        # Setting the default values if needed
     227        for k,value in DEFAULT_PLOT_OPTIONS.iteritems():
     228            if k not in options:
     229                options[k] = value
     230
     231        for opt in options:
     232            if not opt in graphplot_options:
     233                from sage.misc.superseded import deprecation
     234                deprecation(13891, ("You provided "+str(opt)+" as an argument to a "
     235                                    "function which has always silently ignored "
     236                                    "its inputs. This method may soon be updated "
     237                                    "so that the method raises an exception "
     238                                    "instead of this warning, which will break "
     239                                    "your code : to be on the safe side, update it !"))
     240
    118241        self._plot_components = {}
    119242        self._nodelist = graph.vertices()
    120243        self._graph = graph
     
    126249            self._arcdigraph = True
    127250        else:
    128251            self._arcdigraph = False
     252
    129253        self.set_vertices()
    130254        self.set_edges()
    131        
     255
    132256    def _repr_(self):
    133257        """
    134258        Returns a string representation of a ``GraphPlot`` object.
     
    198322        is called by the constructor but can also be called to make updates to
    199323        the vertex options of an existing ``GraphPlot`` object.  Note that the
    200324        changes are cumulative.
    201        
     325
    202326        EXAMPLES::
    203327
    204328            sage: g = Graph({}, loops=True, multiedges=True, sparse=True)
     
    303427            for v in self._nodelist:
    304428                self._plot_components['vertex_labels'].append(text(str(v),
    305429                    self._pos[v], rgbcolor=(0,0,0), zorder=8))
    306    
     430
    307431    def set_edges(self, **edge_options):
    308432        """
    309433        Sets the edge (or arrow) plotting parameters for the ``GraphPlot`` object.
     434
    310435        This function is called by the constructor but can also be called to make
    311436        updates to the vertex options of an existing ``GraphPlot`` object.  Note
    312437        that the changes are cumulative.
    313        
     438
    314439        EXAMPLES::
    315440
    316441            sage: g = Graph({}, loops=True, multiedges=True, sparse=True)
     
    321446            sage: GP.plot()
    322447            sage: GP.set_edges(edge_color='black')
    323448            sage: GP.plot()
    324            
     449
    325450            sage: d = DiGraph({}, loops=True, multiedges=True, sparse=True)
    326451            sage: d.add_edges([(0,0,'a'),(0,0,'b'),(0,1,'c'),(0,1,'d'),
    327452            ...     (0,1,'e'),(0,1,'f'),(0,1,'f'),(2,1,'g'),(2,2,'h')])
     
    332457            sage: GP.plot()
    333458
    334459        TESTS::
    335        
     460
    336461            sage: G = Graph("Fooba")
    337462            sage: G.show(edge_colors={'red':[(3,6),(2,5)]})
    338463
     
    355480            ...           vn = vector(((x-(vx[v0]+vx[v1])/2.),y-(vy[v0]+vy[v1])/2.)).norm()
    356481            ...           assert vn < tol
    357482
    358 
    359483        """
    360484        for arg in edge_options:
    361485            self._options[arg] = edge_options[arg]
    362486        if 'edge_colors' in edge_options: self._options['color_by_label'] = False
    363        
     487
    364488        # Handle base edge options: thickness, linestyle
    365489        eoptions={}
    366490        if 'edge_style' in self._options:
    367491            eoptions['linestyle'] = self._options['edge_style']
    368492        if 'thickness' in self._options:
    369493            eoptions['thickness'] = self._options['thickness']
    370            
     494
    371495        # Set labels param to add labels on the fly
    372496        labels = False
    373497        if self._options['edge_labels']:
    374498            labels = True
    375499            self._plot_components['edge_labels'] = []
    376500
    377         # Make dict collection of all edges (keep label and edge color)           
     501        # Make dict collection of all edges (keep label and edge color)
    378502        edges_to_draw = {}
    379503        if self._options['color_by_label'] or isinstance(self._options['edge_colors'], dict):
    380504            if self._options['color_by_label']: edge_colors = self._graph._color_by_label()
     
    383507                for edge in edge_colors[color]:
    384508                    key = tuple(sorted([edge[0],edge[1]]))
    385509                    if key == (edge[0],edge[1]): head = 1
    386                     else: head = 0 
    387                    
     510                    else: head = 0
     511
    388512                    if len(edge) < 3:
    389513                        label = self._graph.edge_label(edge[0],edge[1])
    390514                        if isinstance(label, list):
     
    396520                                edges_to_draw[key].append((label[-1], color, head))
    397521                    else:
    398522                        label = edge[2]
    399                        
     523
    400524                    if key in edges_to_draw:
    401525                        edges_to_draw[key].append((label, color, head))
    402526                    else:
     
    413537                            break
    414538                if not specified:
    415539                    if key == (edge[0],edge[1]): head = 1
    416                     else: head = 0 
     540                    else: head = 0
    417541                    edges_to_draw[key] = [(label, 'black', head)]
    418542        else:
    419543            for edge in self._graph.edges(sort=True):
    420544                key = tuple(sorted([edge[0],edge[1]]))
    421545                if key == (edge[0],edge[1]): head = 1
    422                 else: head = 0 
     546                else: head = 0
    423547                if key in edges_to_draw:
    424548                    edges_to_draw[key].append((edge[2], self._options['edge_color'], head))
    425549                else:
    426550                    edges_to_draw[key] = [(edge[2], self._options['edge_color'], head)]
    427                
     551
    428552        if edges_to_draw:
    429553            self._plot_components['edges'] = []
    430554        else:
    431555            return
    432                        
     556
    433557        # Check for multi-edges or loops
    434558        if self._arcs or self._loops:
    435559            tmp = edges_to_draw.copy()
     
    439563            from sage.functions.all import sqrt
    440564            for (a,b) in tmp:
    441565                if a == b:
    442                     # Loops 
     566                    # Loops
    443567                    distance = dist
    444568                    local_labels = edges_to_draw.pop((a,b))
    445569                    if len(local_labels)*dist > max_dist:
     
    559683        elif D[1] > 0:
    560684            theta = pi/2
    561685        return ([VR*cos(theta)+A[0], VR*sin(theta)+A[1]], [(R-VR)*cos(theta)+A[0], (R-VR)*sin(theta)+A[1]])
    562        
     686
    563687    def show(self, **kwds):
    564688        """
    565689        Shows the (Di)Graph associated with this ``GraphPlot`` object.
    566        
    567         For syntax and lengthy documentation, see :meth:`GraphPlot.plot`.
    568         Any options not used by plot will be passed on to the
    569         :meth:`~sage.plot.plot.Graphics.show` method.
     690
     691        INPUT:
     692
     693        This method accepts all parameters of
     694        :meth:`sage.plot.graphics.Graphics.show`.
     695
     696        .. NOTE::
     697
     698            - See :mod:`the module's documentation <sage.graphs.graph_plot>` for
     699              information on default values of this method.
     700
     701            - Any options not used by plot will be passed on to the
     702              :meth:`~sage.plot.plot.Graphics.show` method.
    570703
    571704        EXAMPLE::
    572705
     
    574707            sage: P = C.graphplot(vertex_labels=False, vertex_size=0, graph_border=True)
    575708            sage: P.show()
    576709        """
     710        # Setting the default values if needed
     711        for k,value in DEFAULT_SHOW_OPTIONS.iteritems():
     712            if k not in kwds:
     713                kwds[k] = value
     714
    577715        self.plot().show(**kwds)
    578        
     716
    579717    def plot(self, **kwds):
    580718        """
    581719        Returns a graphics object representing the (di)graph.
    582        
     720
    583721        INPUT:
    584722
    585         - ``pos`` -- an optional positioning dictionar
     723        The options accepted by this method are to be found in the documentation
     724        of module :mod:`sage.graphs.graph_plot`.
    586725
    587         - ``layout`` -- what kind of layout to use, takes precedence over ``pos``
     726        .. NOTE::
    588727
    589           - 'circular' -- plots the graph with vertices evenly distributed
    590             on a circle
    591 
    592           - 'spring' -- uses the traditional spring layout, using the
    593             graph's current positions as initial positions
    594 
    595           - 'tree' -- the (di)graph must be a tree. One can specify the root
    596             of the tree using the keyword ``tree_root``, otherwise a root
    597             will be selected at random. Then the tree will be plotted in
    598             levels, depending on minimum distance for the root.
    599 
    600         - ``vertex_labels`` -- whether to print vertex labels
    601 
    602         - ``edge_labels`` -- whether to print edge labels. By default, ``False``,
    603           but if ``True``, the result of ``str(l)`` is printed on the edge for
    604           each label l. Labels equal to None are not printed (to set edge
    605           labels, see :meth:`~sage.graphs.generic_graph.GenericGraph.set_edge_label`).
    606 
    607         - ``vertex_size`` -- size of vertices displayed
    608 
    609         - ``vertex_shape`` -- the shape to draw the vertices (Not available for
    610           multiedge digraphs.
    611 
    612         - ``graph_border`` -- whether to include a box around the graph
    613 
    614         - ``vertex_colors`` -- optional dictionary to specify vertex colors: each
    615           key is a color recognizable by matplotlib, and each corresponding
    616           entry is a list of vertices. If a vertex is not listed, it looks
    617           invisible on the resulting plot (it doesn't get drawn).
    618 
    619         - ``edge_colors`` -- a dictionary specifying edge colors: each key is a
    620           color recognized by matplotlib, and each entry is a list of edges.
    621 
    622         - ``partition`` -- a partition of the vertex set. if specified, plot will
    623           show each cell in a different color. vertex_colors takes precedence.
    624 
    625         - ``talk`` -- if ``True``, prints large vertices with white backgrounds
    626           so that labels are legible on slides
    627 
    628         - ``iterations`` -- how many iterations of the spring layout algorithm to
    629           go through, if applicable
    630 
    631         - ``color_by_label`` -- if ``True``, color edges by their labels
    632 
    633         - ``heights`` -- if specified, this is a dictionary from a set of
    634           floating point heights to a set of vertices
    635 
    636         - ``edge_style`` -- keyword arguments passed into the
    637           edge-drawing routine.  This currently only works for
    638           directed graphs, since we pass off the undirected graph to
    639           networkx
    640 
    641         - ``tree_root`` -- a vertex of the tree to be used as the root for
    642           the ``layout="tree"`` option. If no root is specified, then one
    643           is chosen at random. Ignored unless ``layout='tree'``.
    644 
    645         - ``tree_orientation`` -- "up" or "down" (default is "down").
    646           If "up" (resp., "down"), then the root of the tree will
    647           appear on the bottom (resp., top) and the tree will grow
    648           upwards (resp. downwards). Ignored unless ``layout='tree'``.
    649 
    650         - ``save_pos`` -- save position computed during plotting
    651 
    652         EXAMPLES:
    653 
    654         Let's list all possible options::
    655 
    656             sage: from sage.graphs.graph_plot import graphplot_options
    657             sage: list(sorted(graphplot_options.iteritems()))
    658             [('by_component', 'Whether to do the spring layout by connected component -- a boolean.'),
    659              ('color_by_label', 'Whether or not to color the edges by their label values.'),
    660              ('dim', 'The dimension of the layout -- 2 or 3.'),
    661              ('dist', 'The distance between multiedges.'),
    662              ('edge_color', 'The default color for edges.'),
    663              ('edge_colors', 'Dictionary of edge coloring.'),
    664              ('edge_labels', 'Whether or not to draw edge labels.'),
    665              ('edge_style', 'The linestyle of the edges-- one of "solid", "dashed", "dotted", dashdot".'),
    666              ('graph_border', 'Whether or not to draw a frame around the graph.'),
    667              ('heights', 'A dictionary mapping heights to the list of vertices at this height.'),
    668              ('iterations', 'The number of times to execute the spring layout algorithm.'),
    669              ('layout', 'A layout algorithm -- one of "acyclic", "circular", "ranked", "graphviz", "planar", "spring", or "tree".'),
    670              ('loop_size', 'The radius of the smallest loop.'),
    671              ('max_dist', 'The max distance range to allow multiedges.'),
    672              ('partition', 'A partition of the vertex set.  (Draws each cell of vertices in a different color).'),
    673              ('pos', 'The position dictionary of vertices'),
    674              ('prog', 'Which graphviz layout program to use -- one of "circo", "dot", "fdp", "neato", or "twopi".'),
    675              ('save_pos', 'Whether or not to save the computed position for the graph.'),
    676              ('spring', 'Use spring layout to finalize the current layout.'),
    677              ('talk', 'Whether to display the vertices in talk mode (larger and white)'),
    678              ('tree_orientation', 'The direction of tree branches -- "up" or "down".'),
    679              ('tree_root', 'A vertex designation for drawing trees.'),
    680              ('vertex_colors', 'Dictionary of vertex coloring.'),
    681              ('vertex_labels', 'Whether or not to draw vertex labels.'),
    682              ('vertex_shape', 'The shape to draw the vertices, Currently unavailable for Multi-edged DiGraphs.'),
    683              ('vertex_size', 'The size to draw the vertices.')]
    684 
     728            See :mod:`the module's documentation <sage.graphs.graph_plot>` for
     729            information on default values of this method.
    685730
    686731        We can specify some pretty precise plotting of familiar graphs::
    687732
     
    720765            ...    D.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')')
    721766            sage: D.graphplot(edge_labels=True, layout='circular').show()
    722767
    723 
    724768        This example shows off the coloring of edges::
    725769
    726770            sage: from sage.plot.colors import rainbow
     
    754798
    755799            sage: D = DiGraph({0:[0,1], 1:[2], 2:[3]}, loops=True)
    756800            sage: D.show()
    757             sage: D.show(edge_colors={(0,1,0):[(0,1,None),(1,2,None)],(0,0,0):[(2,3,None)]}) 
     801            sage: D.show(edge_colors={(0,1,0):[(0,1,None),(1,2,None)],(0,0,0):[(2,3,None)]})
    758802
    759803        More options::
    760804
     
    806850
    807851            sage: D = DiGraph({0:[1,2,3], 2:[1,4], 3:[0]})
    808852            sage: D.graphplot().show()
    809            
     853
    810854            sage: D = DiGraph(multiedges=True, sparse=True)
    811855            sage: for i in range(5):
    812856            ...     D.add_edge((i,i+1,'a'))
    813857            ...     D.add_edge((i,i-1,'b'))
    814858            sage: D.graphplot(edge_labels=True,edge_colors=D._color_by_label()).plot()
    815            
     859
    816860            sage: g = Graph({}, loops=True, multiedges=True, sparse=True)
    817861            sage: g.add_edges([(0,0,'a'),(0,0,'b'),(0,1,'c'),(0,1,'d'),
    818862            ...     (0,1,'e'),(0,1,'f'),(0,1,'f'),(2,1,'g'),(2,2,'h')])
    819863            sage: g.graphplot(edge_labels=True, color_by_label=True, edge_style='dashed').plot()
     864
     865        Wrong input (any input) :trac:`13891`::
     866
     867            sage: graphs.PetersenGraph().graphplot().plot(aertataert=346345345)
     868            doctest:...: DeprecationWarning: This method takes no argument ! You may want to give it as an argument to graphplot instead.
     869            See http://trac.sagemath.org/13891 for details.
     870            <BLANKLINE>
    820871        """
     872        # This method takes NO input
     873        # This has been added in early 2013. Remove it before my death, please.
     874        if kwds:
     875            from sage.misc.superseded import deprecation
     876            deprecation(13891, "This method takes no argument ! You may want "
     877                               "to give it as an argument to graphplot instead.")
     878
    821879        G = Graphics()
    822880        for comp in self._plot_components.values():
    823881            if not isinstance(comp, list):
     
    825883            else:
    826884                for item in comp:
    827885                    G += item
     886
    828887        G.set_axes_range(*(self._graph._layout_bounding_box(self._pos)))
    829888        if self._options['graph_border']:
    830889            xmin = G.xmin()
     
    846905        Compute a nice layout of a tree.
    847906
    848907        INPUT:
    849        
     908
    850909        - ``root`` -- the root vertex.
    851        
     910
    852911        - ``orientation`` -- Whether to place the root
    853912          at the top or at the bottom :
    854913
    855             - ``orientation="down"`` -- children are placed below 
     914            - ``orientation="down"`` -- children are placed below
    856915              their parent
    857916            - ``orientation="top"`` -- children are placed above
    858917              their parent
    859        
    860918
    861919        EXAMPLES::
    862920
     
    9501008
    9511009def _circle_embedding(g, vertices, center=(0, 0), radius=1, shift=0):
    9521010    r"""
    953     Set some vertices on a circle in the embedding of a graph G.
     1011    Sets some vertices on a circle in the embedding of a graph G.
    9541012
    9551013    This method modifies the graph's embedding so that the vertices
    9561014    listed in ``vertices`` appear in this ordering on a circle of given
  • sage/modular/arithgroup/arithgroup_perm.py

    diff --git a/sage/modular/arithgroup/arithgroup_perm.py b/sage/modular/arithgroup/arithgroup_perm.py
    a b  
    12901290            res.plot.options['edge_labels'] = True
    12911291
    12921292        return res
    1293      
     1293
    12941294    def generalised_level(self):
    12951295        r"""
    12961296        Return the generalised level of this subgroup.