Ticket #3853: trac_3853-rebased-3.1.1-trac_3880.patch

File trac_3853-rebased-3.1.1-trac_3880.patch, 40.7 kB (added by jason, 5 months ago)

apply instead of trac_3853.patch

  • a/sage/calculus/desolvers.py

    old new  
    3535########################################################################## 
    3636 
    3737from sage.interfaces.maxima import MaximaElement, Maxima 
    38 from sage.plot.plot import LineFactory 
    39 line = LineFactory() 
     38from sage.plot.plot import line 
    4039 
    4140maxima = Maxima() 
    4241 
  • a/sage/groups/perm_gps/cubegroup.py

    old new  
    7777from sage.rings.finite_field import FiniteField as GF 
    7878from sage.rings.arith import factor 
    7979from sage.groups.abelian_gps.abelian_group import AbelianGroup 
    80 from sage.plot.plot import PolygonFactory, TextFactory 
    81 polygon = PolygonFactory() 
    82 text = TextFactory() 
     80from sage.plot.plot import polygon, text 
    8381from sage.calculus.calculus import sin, cos 
    8482pi = RDF.pi() 
    8583 
  • a/sage/gsl/dft.py

    old new  
    5353########################################################################## 
    5454 
    5555from sage.rings.number_field.number_field import CyclotomicField 
    56 from sage.plot.plot import PolygonFactory, line 
     56from sage.plot.plot import polygon, line 
    5757from sage.plot.plot import (Graphics, polygon) 
    5858from sage.groups.abelian_gps.dual_abelian_group import DualAbelianGroup 
    5959from sage.groups.abelian_gps.abelian_group import AbelianGroup 
  • a/sage/plot/plot.py

    old new  
    902902        g.__aspect_ratio = max(self.__aspect_ratio, other.__aspect_ratio) 
    903903        return g 
    904904   
     905    def add_primitive(self, primitive): 
     906        """ 
     907        Adds a primitive to this graphics object. 
     908        """ 
     909        self.__objects.append(primitive) 
     910 
    905911    def _arrow(self, xtail, ytail, xhead, yhead, options): 
    906912        """ 
    907913        Add an arrow with given bounding box to this graphics object. 
     
    9971003        ymax = point[1] + r 
    9981004        self.__objects.append(GraphicPrimitive_Disk(point, r, angle, options)) 
    9991005        self._extend_axes(xmin, xmax, ymin, ymax) 
    1000  
    1001     def _line(self, xdata, ydata, options): 
    1002         """ 
    1003         Add a line to this graphics object. 
    1004  
    1005         (For internal use -- you should just use addition.) 
    1006  
    1007         INPUT: 
    1008             xdata -- list of floats; the x coordinates of points in the data 
    1009             ydata -- list of floats; the y coordinates of points in the data 
    1010             options -- dictionary of options 
    1011         """ 
    1012         self.__objects.append(GraphicPrimitive_Line(xdata, ydata, options)) 
    1013         self._extend_axes(*minmax_data(xdata, ydata)) 
    10141006 
    10151007      
    10161008    def _matrix_plot(self, xy_data_array, xrange, yrange, options): 
     
    17291721    Primitive class that initializes the arrow graphics type 
    17301722 
    17311723    EXAMPLES: 
    1732     We crate an arrow graphics object, then take the 0th entry 
     1724    We create an arrow graphics object, then take the 0th entry 
    17331725    in it to get the actual Arrow graphics primitive: 
    17341726        sage: P = arrow((0,1), (2,3))[0] 
    17351727        sage: type(P) 
     
    26442636                    labels[v] = str(v) 
    26452637                NX.draw_networkx_labels(self.__nxg, self.__pos, labels=labels, ax=subplot) 
    26462638 
    2647 ###################################################################### 
    2648 #                                                                    #     
    2649 #    Graphics Primitives Factories -- construct GraphicPrimitives    # 
    2650 #                                                                    # 
    2651 ###################################################################### 
    2652 
    2653 # The current method of writing a new Graphic Primitive 
    2654 # involves writing a specific Factory for a given  
    2655 # primitive, for example, 'GraphicPrimitive_circle' for 'circle'. 
    2656 # This class should inherit from GraphicPrimitiveFactory,  
    2657 # which should define any general Graphic Primitive attributes.     
    2658 
    2659 # As of now, the Graphic Primitive Factories, have  
    2660 # only a __call__ method that deals with setting kwargs  
    2661 # and coercing data into a correct form to present to 
    2662 # one of the matplotlib functions. 
    2663 
    2664  
    2665 class GraphicPrimitiveFactory: 
    2666     def __init__(self): 
    2667         # options for this specific graphics primitive. 
    2668         self.reset() 
    2669  
    2670     def reset(self): 
    2671         # First the default options for all graphics primitives 
    2672         self.options = {'alpha':1,'thickness':1,'rgbcolor':(0,0,1)} 
    2673         self._reset() 
    2674  
    2675     def _coerce(self, xdata, ydata): 
    2676         return to_float_list(xdata), to_float_list(ydata) 
    2677  
    2678     def _graphic3d(self, *args, **kwds): 
    2679         """ 
    2680         Return 3d version of this graphics primitive. 
    2681  
    2682         We call this if the user tries to create a graphic but gives 
    2683         points (etc) in 3-space instead of in the plane. 
    2684         """ 
    2685         raise NotImplementedError, "3d plotting of this primitive not yet implemented" 
    2686  
    2687  
    2688 #class GraphicPrimitiveFactory_points(GraphicPrimitiveFactory): 
    2689 #    def __call__(self, xdata, ydata, **kwds): 
    2690 #        options = dict(self.options) 
    2691 #        for k, v in kwds.iteritems(): 
    2692 #            options[k] = v 
    2693 #        return self._from_xdata_ydata(xdata, ydata, options=options) 
    2694  
    2695 # WARNING: The below GraphicPrimitiveFactory_from_point_list 
    2696 # class can potentially be very slow for large point sets. 
     2639 
     2640# WARNING: The below function xydata_from_point_list 
     2641# can potentially be very slow for large point sets. 
    26972642# 
    26982643# It exists because it provides the following functionality: 
    26992644# Allows user to give as input to the function 'point' 
     
    27042649# x-values in one list and all the y-values in another list. 
    27052650# This is needed to be done because that is how the input is 
    27062651# taken in the matplotlib function 'scatter'. 
    2707 class GraphicPrimitiveFactory_from_point_list(GraphicPrimitiveFactory): 
    2708     def __call__(self, points, coerce=True, **kwds): 
    2709         try: 
    2710             return points.plot(**kwds) 
    2711         except AttributeError: 
     2652def xydata_from_point_list(points): 
     2653    if not isinstance(points, (list,tuple)) or \ 
     2654       (isinstance(points,(list,tuple)) and len(points) <= 3 \ 
     2655        and len(points) > 0 \ 
     2656        and not isinstance(points[0], (list,tuple))): 
     2657        try: 
     2658            points = [[float(z) for z in points]] 
     2659        except TypeError: 
    27122660            pass 
    2713         options = dict(self.options) 
    2714         for k, v in kwds.iteritems(): 
    2715             options[k] = v 
    2716  
    2717         if not isinstance(points, (list,tuple)) or \ 
    2718            (isinstance(points,(list,tuple)) and len(points) <= 3 \ 
    2719             and len(points) > 0 \ 
    2720             and not isinstance(points[0], (list,tuple))): 
    2721             try: 
    2722                 points = [[float(z) for z in points]] 
    2723             except TypeError: 
    2724                 pass 
    2725  
    2726         try: 
    2727             if len(points) > 0 and len(points[0]) == 3: 
    2728                 return self._graphic3d()(points, coerce=coerce, **kwds) 
    2729         except (AttributeError, TypeError): 
    2730             pass 
    2731         xdata = [] 
    2732         ydata = [] 
    2733         if coerce: 
    2734             xdata = [float(z[0]) for z in points] 
    2735             ydata = [float(z[1]) for z in points]             
    2736         else: 
    2737             xdata = [z[0] for z in points] 
    2738             ydata = [z[1] for z in points]             
    2739  
    2740         return self._from_xdata_ydata(xdata, ydata, True, options=options) 
    2741  
    2742 class ArrowFactory(GraphicPrimitiveFactory): 
    2743     """ 
    2744  
     2661    xdata = [float(z[0]) for z in points] 
     2662    ydata = [float(z[1]) for z in points]             
     2663 
     2664    return xdata, ydata 
     2665 
     2666def arrow(tailpoint, headpoint, **kwds): 
     2667    """ 
    27452668    An arrow from (xmin, ymin) to (xmax, ymax). 
    27462669 
    27472670    EXAMPLES: 
     
    27622685        1.0 
    27632686        sage: a.xmax() 
    27642687        5.0 
    2765  
    2766     """ 
    2767     def __call__(self, tailpoint, headpoint, **kwds): 
    2768         options = dict(self.options) 
    2769         for k, v in kwds.iteritems(): 
    2770             options[k] = v 
    2771         xtail = float(tailpoint[0]) 
    2772         ytail = float(tailpoint[1]) 
    2773         xhead = float(headpoint[0]) 
    2774         yhead = float(headpoint[1]) 
    2775         xmin = min(xtail, xhead) 
    2776         xmax = max(xtail, xhead) 
    2777         ymin = min(ytail, yhead) 
    2778         ymax = max(ytail, yhead) 
    2779  
    2780         g = Graphics(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) 
    2781         g._arrow(xtail, ytail, xhead, yhead, options=options) 
    2782         return g 
    2783  
    2784     def _reset(self): 
    2785         self.options={'width':0.02,'rgbcolor':(0, 0, 1)} 
    2786      
    2787     def __repr__(self): 
    2788         """ 
    2789         Returns a string representation of this ArrowFactory object. 
    2790  
    2791         TESTS: 
    2792             sage: arrow 
    2793             type arrow? for help and examples 
    2794         """ 
    2795         return "type arrow? for help and examples" 
    2796  
    2797 #an unique arrow instance 
    2798 arrow = ArrowFactory() 
    2799  
    2800 class BarChartFactory(GraphicPrimitiveFactory): 
     2688    """ 
     2689 
     2690    options = {'width':0.02,'rgbcolor':(0, 0, 1)} 
     2691    options.update(kwds) 
     2692 
     2693    #Get the x/y min/max data 
     2694    xtail = float(tailpoint[0]) 
     2695    ytail = float(tailpoint[1]) 
     2696    xhead = float(headpoint[0]) 
     2697    yhead = float(headpoint[1]) 
     2698    xmin = min(xtail, xhead) 
     2699    xmax = max(xtail, xhead) 
     2700    ymin = min(ytail, yhead) 
     2701    ymax = max(ytail, yhead) 
     2702 
     2703    g = Graphics(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) 
     2704    g._arrow(xtail, ytail, xhead, yhead, options=options) 
     2705    return g 
     2706 
     2707def bar_chart(datalist, **kwds): 
    28012708    """ 
    28022709    A bar chart of (currently) one list of numerical data. 
    28032710    Support for more datalists in progress. 
     
    28122719    A bar_chart with negative values and red bars: 
    28132720        sage: bar_chart([-3,5,-6,11], rgbcolor=(1,0,0)) 
    28142721    """ 
    2815     def __call__(self, datalist, **kwds): 
    2816         options = dict(self.options) 
    2817         for k, v in kwds.iteritems(): 
    2818             options[k] = v 
    2819         dl = len(datalist) 
    2820         #if dl > 1: 
    2821         #    print "WARNING, currently only 1 data set allowed" 
    2822         #    datalist = datalist[0] 
    2823         if dl == 3: 
    2824             datalist = datalist+[0] 
    2825         #bardata = [] 
    2826         #cnt = 1 
    2827         #for pnts in datalist: 
    2828             #ind = [i+cnt/dl for i in range(len(pnts))] 
    2829         ind = range(len(datalist)) 
    2830         xrange = (0, len(datalist)) 
    2831         yrange = (min(datalist), max(datalist)) 
    2832             #bardata.append([ind, pnts, xrange, yrange]) 
    2833             #cnt += 1 
    2834  
    2835         g = Graphics() 
    2836         #TODO: improve below for multiple data sets! 
    2837         #cnt = 1 
    2838         #for ind, pnts, xrange, yrange in bardata: 
    2839             #options={'rgbcolor':hue(cnt/dl),'width':0.5/dl} 
    2840         #    g._bar_chart(ind, pnts, xrange, yrange, options=options) 
    2841         #    cnt += 1 
    2842         #else: 
    2843         g._bar_chart(ind, datalist, xrange, yrange, options=options) 
    2844         return g 
    2845  
    2846     def _reset(self): 
    2847         self.options={'width':0.5,'rgbcolor':(0, 0, 1)} 
    2848      
    2849     def __repr__(self): 
    2850         """ 
    2851         Returns a string representation of this BarChartFactory object. 
    2852  
    2853         TESTS: 
    2854             sage: bar_chart 
    2855             type bar_chart? for help and examples 
    2856         """ 
    2857         return "type bar_chart? for help and examples" 
    2858  
    2859 #an unique bar_chart instance 
    2860 bar_chart = BarChartFactory() 
    2861  
    2862  
    2863 class CircleFactory(GraphicPrimitiveFactory): 
     2722    options = {'width':0.5,'rgbcolor':(0, 0, 1)} 
     2723    options.update(kwds) 
     2724 
     2725    dl = len(datalist) 
     2726    #if dl > 1: 
     2727    #    print "WARNING, currently only 1 data set allowed" 
     2728    #    datalist = datalist[0] 
     2729    if dl == 3: 
     2730        datalist = datalist+[0] 
     2731    #bardata = [] 
     2732    #cnt = 1 
     2733    #for pnts in datalist: 
     2734        #ind = [i+cnt/dl for i in range(len(pnts))] 
     2735    ind = range(len(datalist)) 
     2736    xrange = (0, len(datalist)) 
     2737    yrange = (min(datalist), max(datalist)) 
     2738        #bardata.append([ind, pnts, xrange, yrange]) 
     2739        #cnt += 1 
     2740 
     2741    g = Graphics() 
     2742    #TODO: improve below for multiple data sets! 
     2743    #cnt = 1 
     2744    #for ind, pnts, xrange, yrange in bardata: 
     2745        #options={'rgbcolor':hue(cnt/dl),'width':0.5/dl} 
     2746    #    g._bar_chart(ind, pnts, xrange, yrange, options=options) 
     2747    #    cnt += 1 
     2748    #else: 
     2749    g._bar_chart(ind, datalist, xrange, yrange, options=options) 
     2750    return g 
     2751 
     2752 
     2753def circle(point, radius, **kwds): 
    28642754    """ 
    28652755    Return a circle at a point = $(x,y)$ with radius = $r$. 
    28662756    Type \code{circle.options} to see all options 
     
    29052795        sage: p.ymin() 
    29062796        2.0 
    29072797    """ 
    2908     def __call__(self, point, radius, **kwds): 
    2909         options = dict(self.options) 
    2910         for k, v in kwds.iteritems(): 
    2911             options[k] = v 
    2912  
    2913         r = float(radius) 
    2914         point = (float(point[0]), float(point[1])) 
    2915         g = Graphics(xmin=point[0]-r, xmax=point[0]+r, ymin=point[1]-r, ymax=point[1]+r) 
    2916         g._circle(point[0], point[1], r, options) 
    2917         return g 
    2918  
    2919     def _reset(self): 
    2920         self.options={'alpha':1,'fill':False,'thickness':1,'rgbcolor':(0, 0, 1)} 
    2921      
    2922     def __repr__(self): 
    2923         """ 
    2924         Returns a string representation of this CircleFactory object. 
    2925  
    2926         TESTS: 
    2927             sage: circle 
    2928             type circle? for help and examples 
    2929         """ 
    2930         return "type circle? for help and examples" 
    2931  
    2932  
    2933 #an unique circle instance 
    2934 circle = CircleFactory() 
    2935  
    2936 class ContourPlotFactory(GraphicPrimitiveFactory): 
     2798    options={'alpha':1,'fill':False,'thickness':1,'rgbcolor':(0, 0, 1)} 
     2799    for k, v in kwds.iteritems(): 
     2800        options[k] = v 
     2801 
     2802    r = float(radius) 
     2803    point = (float(point[0]), float(point[1])) 
     2804    g = Graphics(xmin=point[0]-r, xmax=point[0]+r, ymin=point[1]-r, ymax=point[1]+r) 
     2805    g._circle(point[0], point[1], r, options) 
     2806    return g 
     2807 
     2808def contour_plot(f, xrange, yrange, **kwds): 
    29372809    r""" 
    29382810     
    29392811    \code{contour_plot} takes a function of two variables, $f(x,y)$ 
     
    30052877        sage: p.ymin() 
    30062878        3.0 
    30072879    """ 
    3008     def __call__(self, f, xrange, yrange, **kwds): 
    3009         options = dict(self.options) 
    3010         for k, v in kwds.iteritems(): 
    3011             options[k] = v 
    3012  
    3013         g, xstep, ystep, xrange, yrange = setup_for_eval_on_grid([f], xrange, yrange, options['plot_points']) 
    3014         g = g[0] 
    3015         xy_data_array = [[g(x, y) for x in \ 
    3016                           sage.misc.misc.xsrange(xrange[0], xrange[1], xstep)] 
    3017                           for y in sage.misc.misc.xsrange(yrange[0], yrange[1], ystep)] 
    3018  
    3019         g = Graphics(xmin=float(xrange[0]), xmax=float(xrange[1]), ymin=float(yrange[0]), ymax=float(yrange[1])) 
    3020         g._contour_plot(xy_data_array, xrange, yrange, options) 
    3021         return g         
    3022  
    3023     def _reset(self): 
    3024         self.options={'plot_points':25, 'fill':True, 'cmap':'gray', 'contours':None} 
    3025      
    3026     def __repr__(self): 
    3027         """ 
    3028         Returns a string representation of this ContourPlotFactory object. 
    3029  
    3030         TESTS: 
    3031             sage: contour_plot 
    3032             type contour_plot? for help and examples 
    3033         """ 
    3034         return "type contour_plot? for help and examples" 
    3035  
    3036  
    3037 #unique contour_plot instance 
    3038 contour_plot = ContourPlotFactory()  
    3039  
    3040 class ImplicitPlotFactory(ContourPlotFactory): 
     2880    options = {'plot_points':25, 'fill':True, 'cmap':'gray', 'contours':None} 
     2881    for k, v in kwds.iteritems(): 
     2882        options[k] = v 
     2883 
     2884    g, xstep, ystep, xrange, yrange = setup_for_eval_on_grid([f], xrange, yrange, options['plot_points']) 
     2885    g = g[0] 
     2886    xy_data_array = [[g(x, y) for x in \ 
     2887                      sage.misc.misc.xsrange(xrange[0], xrange[1], xstep)] 
     2888                      for y in sage.misc.misc.xsrange(yrange[0], yrange[1], ystep)] 
     2889 
     2890    g = Graphics(xmin=float(xrange[0]), xmax=float(xrange[1]), ymin=float(yrange[0]), ymax=float(yrange[1])) 
     2891    g._contour_plot(xy_data_array, xrange, yrange, options) 
     2892    return g         
     2893 
     2894def implicit_plot(f, xrange, yrange, **kwds): 
    30412895    r""" 
    30422896    \code{implicit_plot} takes a function of two variables, $f(x,y)$ 
    30432897    and plots the curve $f(x,y)=0$ over the specified  
     
    30792933    (plot_points=200 looks even better, but it's about 16 times slower.) 
    30802934        sage: implicit_plot(mandel(7), (-0.3, 0.05), (-1.15, -0.9),plot_points=50).show(aspect_ratio=1) 
    30812935    """ 
    3082     def _reset(self): 
    3083         """ 
    3084         Sets the default options for this ImplicitPlotFactory object. 
    3085  
    3086         TESTS: 
    3087             sage: implicit_plot._reset() 
    3088             sage: implicit_plot.options['contours'] 
    3089             (0.0,) 
    3090         """ 
    3091         self.options={'plot_points':25, 'fill':False, 'cmap':'gray', 'contours':(0.0,)} 
    3092      
    3093     def __repr__(self): 
    3094         """ 
    3095         Returns a string representation of this ImplicitPlotFactory object. 
    3096  
    3097         TESTS: 
    3098             sage: implicit_plot 
    3099             type implicit_plot? for help and examples 
    3100         """ 
    3101         return "type implicit_plot? for help and examples" 
    3102  
    3103 #unique implicit_plot instance 
    3104 implicit_plot = ImplicitPlotFactory()  
    3105  
    3106 class LineFactory(GraphicPrimitiveFactory_from_point_list): 
     2936    options = {'plot_points':25, 'fill':False, 'cmap':'gray', 'contours':(0.0,)} 
     2937    options.update(kwds) 
     2938    return contour_plot(f, xrange, yrange, **kwds) 
     2939 
     2940def line(points, **kwds): 
    31072941    r""" 
    31082942    Create the line through the given list of points. 
    31092943     
     
    32033037    A line with no points or one point: 
    32043038        sage: line([]) 
    32053039        sage: line([(1,1)]) 
    3206     """ 
    3207     def _reset(self): 
    3208         self.options = {'alpha':1,'rgbcolor':(0,0,1),'thickness':1} 
    3209      
    3210     def __repr__(self): 
    3211         """ 
    3212         Returns a string representation of this LineFactory object. 
    3213  
    3214         TESTS: 
    3215             sage: line 
    3216             type line? for help and examples 
    3217         """ 
    3218         return "type line? for help and examples" 
    3219          
    3220     def _from_xdata_ydata(self, xdata, ydata, coerce, options): 
    3221         """ 
    3222         TESTS: 
    3223         We test to make sure that the x/y min/max data are set correctly. 
    3224             sage: l = line([(100, 100), (120, 120)])  
    3225             sage: l.xmin() 
    3226             100.0 
    3227             sage: l.xmax() 
    3228             120.0 
    3229         """ 
    3230         if coerce: 
    3231             xdata, ydata = self._coerce(xdata, ydata) 
    3232          
    3233         g = Graphics(**minmax_data(xdata, ydata, dict=True)) 
    3234         g._Graphics__objects.append(GraphicPrimitive_Line(xdata, ydata, options)) 
    3235         return g 
    3236  
    3237     def _graphic3d(self): 
    3238         from sage.plot.plot3d.shapes2 import line3d 
    3239         return line3d 
    3240  
    3241 # unique line instance 
    3242 line = LineFactory() 
    3243  
    3244 class MatrixPlotFactory(GraphicPrimitiveFactory): 
     3040 
     3041    TESTS: 
     3042    We test to make sure that the x/y min/max data are set correctly. 
     3043        sage: l = line([(100, 100), (120, 120)])  
     3044        sage: l.xmin() 
     3045        100.0 
     3046        sage: l.xmax() 
     3047        120.0 
     3048 
     3049    """ 
     3050    options = {'alpha':1,'rgbcolor':(0,0,1),'thickness':1} 
     3051    options.update(kwds) 
     3052 
     3053    xdata, ydata = xydata_from_point_list(points) 
     3054    g = Graphics(**minmax_data(xdata, ydata, dict=True)) 
     3055    g._Graphics__objects.append(GraphicPrimitive_Line(xdata, ydata, options)) 
     3056    return g 
     3057 
     3058 
     3059def matrix_plot(mat, **kwds): 
    32453060    r""" 
    32463061    A plot of a given matrix or 2D array. 
    32473062     
     
    32673082        sage: matrix_plot(random_matrix(GF(389), 10), cmap='Oranges') 
    32683083 
    32693084    """ 
    3270     def __call__(self, mat, **kwds): 
    3271         from sage.matrix.all import is_Matrix  
    3272         from matplotlib.numerix import array 
    3273         if not is_Matrix(mat) or (isinstance(mat, (list, tuple)) and isinstance(mat[0], (list, tuple))): 
    3274             raise TypeError, "mat must be of type Matrix or a two dimensional array" 
    3275         options = dict(self.options) 
    3276         for k, v in kwds.iteritems(): 
    3277             options[k] = v 
    3278         if is_Matrix(mat): 
    3279             xrange = (0, mat.ncols()) 
    3280             yrange = (0, mat.nrows()) 
    3281         else: 
    3282             xrange = (0, len(mat[0])) 
    3283             yrange = (0, len(mat)) 
    3284         xy_data_array = [array(r, dtype=float) for r in mat] 
    3285  
    3286         g = Graphics() 
    3287         g._matrix_plot(xy_data_array, xrange, yrange, options) 
    3288         return g 
    3289  
    3290     def _reset(self): 
    3291         self.options={'cmap':'gray'} 
    3292      
    3293     def __repr__(self): 
    3294         """ 
    3295         Returns a string representation of this MatrixPlotFactory object. 
    3296  
    3297         TESTS: 
    3298             sage: matrix_plot 
    3299             type matrix_plot? for help and examples 
    3300         """ 
    3301         return "type matrix_plot? for help and examples" 
    3302  
    3303  
    3304 #unique matrix_plot instance 
    3305 matrix_plot = MatrixPlotFactory() 
     3085    options = {'cmap':'gray'} 
     3086    options.update(kwds) 
     3087 
     3088    from sage.matrix.all import is_Matrix  
     3089    from matplotlib.numerix import array 
     3090    if not is_Matrix(mat) or (isinstance(mat, (list, tuple)) and isinstance(mat[0], (list, tuple))): 
     3091        raise TypeError, "mat must be of type Matrix or a two dimensional array" 
     3092 
     3093    if is_Matrix(mat): 
     3094        xrange = (0, mat.ncols()) 
     3095        yrange = (0, mat.nrows()) 
     3096    else: 
     3097        xrange = (0, len(mat[0])) 
     3098        yrange = (0, len(mat)) 
     3099    xy_data_array = [array(r, dtype=float) for r in mat] 
     3100 
     3101    g = Graphics() 
     3102    g._matrix_plot(xy_data_array, xrange, yrange, options) 
     3103    return g 
     3104 
     3105 
    33063106 
    33073107 
    33083108# Below is the base class that is used to make 'plot_vector_field'. 
    33093109# Its implementation is motivated by 'PlotVectorField'. 
    33103110# TODO: make class similiar to this one to implement:  
    33113111# 'plot_gradient_field' and 'plot_hamiltonian_field' 
    3312 class PlotFieldFactory(GraphicPrimitiveFactory): 
     3112def plot_vector_field((f, g), xrange, yrange, **kwds): 
    33133113    r""" 
    33143114     
    33153115    \code{plot_vector_field} takes two functions of two variables, $(f(x,y), g(x,y))$ 
     
    33383138        10.0 
    33393139 
    33403140    """ 
    3341     def __call__(self, (f, g), xrange, yrange, **kwds): 
    3342         options = dict(self.options) 
    3343         for k, v in kwds.iteritems(): 
    3344             options[k] = v 
    3345         z, xstep, ystep, xrange, yrange = setup_for_eval_on_grid([f,g], xrange, yrange, options['plot_points']) 
    3346         f,g = z 
    3347          
    3348         xpos_array, ypos_array, xvec_array, yvec_array = [],[],[],[] 
    3349         for x in sage.misc.misc.xsrange(xrange[0], xrange[1], xstep): 
    3350             for y in sage.misc.misc.xsrange(yrange[0], yrange[1], ystep): 
    3351                 xpos_array.append(x) 
    3352                 ypos_array.append(y) 
    3353                 xvec_array.append(f(x,y)) 
    3354                 yvec_array.append(g(x,y)) 
    3355  
    3356         import numpy 
    3357         xvec_array = numpy.array(xvec_array, dtype=float) 
    3358         yvec_array = numpy.array(yvec_array, dtype=float) 
    3359         g = Graphics(xmin=xrange[0], xmax=xrange[1], ymin=yrange[0],  ymax=yrange[1]) 
    3360         g._plot_field(xpos_array, ypos_array, xvec_array, yvec_array, xrange, yrange, options) 
    3361         return g 
    3362  
    3363     def _reset(self): 
    3364         self.options={'plot_points':20, 'cmap':'gray'} 
    3365      
    3366     def _repr_(self): 
    3367         return "type plot_vector_field? for help and examples" 
    3368  
    3369 #unique plot_vector_field instance 
    3370 plot_vector_field = PlotFieldFactory()  
    3371  
    3372  
    3373 class DiskFactory(GraphicPrimitiveFactory): 
     3141    options = {'plot_points':20, 'cmap':'gray'} 
     3142    options.update(kwds) 
     3143 
     3144    z, xstep, ystep, xrange, yrange = setup_for_eval_on_grid([f,g], xrange, yrange, options['plot_points']) 
     3145    f,g = z 
     3146 
     3147    xpos_array, ypos_array, xvec_array, yvec_array = [],[],[],[] 
     3148    for x in sage.misc.misc.xsrange(xrange[0], xrange[1], xstep): 
     3149        for y in sage.misc.misc.xsrange(yrange[0], yrange[1], ystep): 
     3150            xpos_array.append(x) 
     3151            ypos_array.append(y) 
     3152            xvec_array.append(f(x,y)) 
     3153            yvec_array.append(g(x,y)) 
     3154 
     3155    import numpy 
     3156    xvec_array = numpy.array(xvec_array, dtype=float) 
     3157    yvec_array = numpy.array(yvec_array, dtype=float) 
     3158    g = Graphics(xmin=xrange[0], xmax=xrange[1], ymin=yrange[0],  ymax=yrange[1]) 
     3159    g._plot_field(xpos_array, ypos_array, xvec_array, yvec_array, xrange, yrange, options) 
     3160    return g 
     3161 
     3162 
     3163def disk(point, radius, angle, **kwds): 
    33743164    r""" 
    33753165     
    33763166    A disk at a point = $(x,y)$ with radius = $r$  
     
    33973187        sage: d.xmax() 
    33983188        6.0 
    33993189    """ 
    3400     def __call__(self, point, radius, angle, **kwds): 
    3401         options = dict(self.options) 
    3402         for k, v in kwds.iteritems(): 
    3403             options[k] = v 
    3404      
    3405         r = float(radius) 
    3406         point = (float(point[0]), float(point[1])) 
    3407         angle = (float(angle[0]), float(angle[1])) 
    3408  
    3409         xmin = point[0] - r 
    3410         xmax = point[0] + r 
    3411         ymin = point[1] - r 
    3412         ymax = point[1] + r 
    3413         g = Graphics(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) 
    3414         g._disk(point, r, angle, options) 
    3415         return g 
    3416  
    3417     def _reset(self): 
    3418         self.options={'alpha':1,'fill':True,'rgbcolor':(0,0,1),'thickness':0} 
    3419      
    3420     def __repr__(self): 
    3421         """ 
    3422         Returns a string representation of this DiskFactory object. 
    3423  
    3424         TESTS: 
    3425             sage: disk 
    3426             type disk? for help and examples 
    3427         """ 
    3428         return "type disk? for help and examples" 
    3429  
    3430 #an unique disk instance 
    3431 disk = DiskFactory() 
    3432  
    3433 class PointFactory(GraphicPrimitiveFactory_from_point_list): 
     3190    options = {'alpha':1,'fill':True,'rgbcolor':(0,0,1),'thickness':0} 
     3191    options.update(kwds) 
     3192 
     3193    r = float(radius) 
     3194    point = (float(point[0]), float(point[1])) 
     3195    angle = (float(angle[0]), float(angle[1])) 
     3196 
     3197    xmin = point[0] - r 
     3198    xmax = point[0] + r 
     3199    ymin = point[1] - r 
     3200    ymax = point[1] + r 
     3201    g = Graphics(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax) 
     3202    g._disk(point, r, angle, options) 
     3203    return g 
     3204 
     3205def point(points, **kwds): 
    34343206    r""" 
    34353207     
    34363208    A point of size `pointsize' defined by point = $(x,y)$. 
     
    34533225        3.0 
    34543226 
    34553227    """ 
    3456     def _reset(self): 
    3457         self.options = {'alpha':1,'pointsize':10,'faceted':False,'rgbcolor':(0,0,1)} 
    3458  
    3459     def __repr__(self): 
    3460         """ 
    3461         Returns a string representation of this PointFactory object. 
    3462  
    3463         TESTS: 
    3464             sage: point 
    3465             type point? for help and examples 
    3466         """ 
    3467         return "type point? for help and examples" 
    3468  
    3469     def _from_xdata_ydata(self, xdata, ydata, coerce, options): 
    3470         if coerce: 
    3471             xdata, ydata = self._coerce(xdata, ydata) 
    3472         g = Graphics(**minmax_data(xdata, ydata, dict=True)) 
    3473         g._Graphics__objects.append(GraphicPrimitive_Point(xdata, ydata, options)) 
    3474         return g 
    3475  
    3476 # unique point instance 
    3477 point = PointFactory() 
     3228    options = {'alpha':1,'pointsize':10,'faceted':False,'rgbcolor':(0,0,1)} 
     3229    options.update(kwds) 
     3230 
     3231    xdata, ydata = xydata_from_point_list(points) 
     3232    g = Graphics(**minmax_data(xdata, ydata, dict=True)) 
     3233    g._Graphics__objects.append(GraphicPrimitive_Point(xdata, ydata, options)) 
     3234    return g 
     3235 
    34783236points = point 
    34793237 
    3480  
    3481 class PolygonFactory(GraphicPrimitiveFactory_from_point_list): 
     3238def polygon(points, **kwds): 
    34823239    r""" 
    34833240    Type \code{polygon.options} for a dictionary of the default 
    34843241    options for polygons.  You can change this to change 
     
    35483305        -- David Joyner (2006-04-14): the long list of examples above. 
    35493306     
    35503307    """ 
    3551     def _reset(self): 
    3552         self.options={'alpha':1,'rgbcolor':(0,0,1),'thickness':0} 
    3553      
    3554     def __repr__(self): 
    3555         """ 
    3556         Returns a string representation of this PolygonFactory object. 
    3557  
    3558         TESTS: 
    3559             sage: polygon 
    3560             Sage polygon; type polygon? for help and examples 
    3561         """ 
    3562         return "Sage polygon; type polygon? for help and examples" 
    3563          
    3564     def _from_xdata_ydata(self, xdata, ydata, coerce, options): 
    3565         if coerce: 
    3566             xdata, ydata = self._coerce(xdata, ydata) 
    3567         g = Graphics(**minmax_data(xdata, ydata, dict=True)) 
    3568         g._Graphics__objects.append(GraphicPrimitive_Polygon(xdata, ydata, options)) 
    3569         return g  
    3570  
    3571 # unique polygon instance  
    3572 polygon = PolygonFactory()  
    3573  
    3574 class PlotFactory(GraphicPrimitiveFactory): 
     3308    options = {'alpha':1,'rgbcolor':(0,0,1),'thickness':0} 
     3309    options.update(kwds) 
     3310     
     3311    xdata, ydata = xydata_from_point_list(points) 
     3312    g = Graphics(**minmax_data(xdata, ydata, dict=True)) 
     3313    g._Graphics__objects.append(GraphicPrimitive_Polygon(xdata, ydata, options)) 
     3314    return g  
     3315     
     3316def plot(funcs, *args, **kwds): 
    35753317    r""" 
    35763318    Use plot by writing  
    35773319     
     
    37123454        True 
    37133455        sage: p[0].xdata[-1] == 1 
    37143456        True 
    3715          
    3716     """ 
    3717     def _reset(self): 
    3718         o = self.options 
    3719         o['plot_points'] = 200 
    3720         o['plot_division'] = 1000  
    3721         o['max_bend'] = 0.1        
    3722         o['rgbcolor'] = (0,0,1)    
    3723  
    3724     def __repr__(self): 
    3725         """ 
    3726         Returns a string representation of this PlotFactory object. 
    3727  
    3728         TESTS: 
    3729             sage: plot 
    3730             type plot? for help and examples 
    3731         """ 
    3732         return "type plot? for help and examples" 
    3733  
    3734     def __call__(self, funcs, *args, **kwds): 
    3735         do_show = False 
    3736         if kwds.has_key('show') and kwds['show']: 
    3737             do_show = True 
    3738             del kwds['show'] 
    3739         if hasattr(funcs, 'plot'): 
    3740             G = funcs.plot(*args, **kwds) 
    3741         # if we are using the generic plotting method 
    3742         else: 
    3743             n = len(args) 
    3744             # if there are no extra args, pick some silly default 
    3745             if n == 0: 
    3746                 G = self._call(funcs, (-1, 1), *args, **kwds) 
    3747             # if there is one extra arg, then it had better be a tuple 
    3748             elif n == 1: 
    3749                 G = self._call(funcs, *args, **kwds) 
    3750             elif n == 2: 
    3751             # if there are two extra args, then pull them out and pass them as a tuple 
    3752                 xmin = args[0] 
    3753                 xmax = args[1] 
    3754                 args = args[2:] 
    3755                 G = self._call(funcs, (xmin, xmax), *args, **kwds) 
    3756             else: 
    3757                 sage.misc.misc.verbose("there were %s extra arguments (besides %s)" % (n, funcs), level=0) 
    3758         if do_show: 
    3759             G.show() 
    3760         return G 
    3761              
    3762     def _call(self, funcs, xrange, parametric=False, 
     3457 
     3458    We check to make sure that the x/y min/max data get set correctly 
     3459    when there are multiple functions. 
     3460     
     3461        sage: p = plot([sin(x), cos(x)], 100, 120) 
     3462        sage: p.xmin() 
     3463        100.0 
     3464        sage: p.xmax() 
     3465        120.0    
     3466    """ 
     3467    do_show = False 
     3468    if kwds.has_key('show') and kwds['show']: 
     3469        do_show = True 
     3470        del kwds['show'] 
     3471    if hasattr(funcs, 'plot'): 
     3472        G = funcs.plot(*args, **kwds) 
     3473    # if we are using the generic plotting method 
     3474    else: 
     3475        n = len(args) 
     3476        # if there are no extra args, pick some silly default 
     3477        if n == 0: 
     3478            G = _plot(funcs, (-1, 1), *args, **kwds) 
     3479        # if there is one extra arg, then it had better be a tuple 
     3480        elif n == 1: 
     3481            G = _plot(funcs, *args, **kwds) 
     3482        elif n == 2: 
     3483        # if there are two extra args, then pull them out and pass them as a tuple 
     3484            xmin = args[0] 
     3485            xmax = args[1] 
     3486            args = args[2:] 
     3487            G = _plot(funcs, (xmin, xmax), *args, **kwds) 
     3488        else: 
     3489            sage.misc.misc.verbose("there were %s extra arguments (besides %s)" % (n, funcs), level=0) 
     3490    if do_show: 
     3491        G.show() 
     3492    return G 
     3493 
     3494def _plot(funcs, xrange, parametric=False, 
    37633495              polar=False, label='', randomize=True, **kwds): 
    3764         options = dict(self.options) 
    3765         """ 
    3766         TESTS: 
    3767         We check to make sure that the x/y min/max data get set correctly 
    3768         when there are multiple functions. 
    3769      
    3770             sage: p = plot([sin(x), cos(x)], 100, 120) 
    3771             sage: p.xmin() 
    3772             100.0 
    3773             sage: p.xmax() 
    3774             120.0 
    3775         """ 
    3776         if kwds.has_key('color') and not kwds.has_key('rgbcolor'): 
    3777             kwds['rgbcolor'] = kwds['color'] 
    3778             del kwds['color'] 
    3779         for k, v in kwds.iteritems(): 
    3780             options[k] = v 
    3781  
    3782         #parametric_plot will be a list or tuple of two functions (f,g) 
    3783         #and will plotted as (f(x), g(x)) for all x in the given range 
    3784         if parametric: 
    3785             if len(funcs) == 3: 
    3786                 raise ValueError, "use parametric_plot3d for parametric plots in 3d dimensions." 
    3787             elif len(funcs) == 2: 
    3788                 # 2d 
    3789                 f,g = funcs 
    3790             else: 
    3791                 raise ValueError, "parametric plots only implemented in 2 and 3 dimensions." 
    3792              
    3793         #or we have only a single function to be plotted: 
    3794         else: 
    3795             f = funcs 
    3796  
    3797         plot_points = int(options['plot_points']) 
    3798         del options['plot_points'] 
    3799         x, data = var_and_list_of_values(xrange, plot_points) 
    3800         data = list(data) 
    3801         xmin = data[0] 
    3802         xmax = data[-1] 
    3803  
    3804         #check to see if funcs is a list of functions that will 
    3805         #be all plotted together. 
    3806         if isinstance(funcs, (list, tuple)) and not parametric: 
    3807             return reduce(operator.add, (plot(f, (xmin, xmax), polar=polar, **kwds) for f in funcs)) 
    3808  
    3809         if len(data) >= 2: 
    3810             delta = data[1]-data[0] 
    3811         else: 
    3812             delta = 0 
    3813  
    3814         random = current_randstate().python_random().random 
    3815         exceptions = 0; msg='' 
    3816         exception_indices = [] 
    3817         for i in range(len(data)): 
    3818             xi = data[i] 
    3819             # Slightly randomize the interior sample points if 
    3820             # randomize is true 
    3821             if i > 0 and i < plot_points-1: 
    3822                 if randomize: 
    3823                     xi += delta*random() 
    3824                 if xi > xmax: 
    3825                     xi = xmax 
    3826             elif i == plot_points-1:  
    3827                 xi = xmax  # guarantee that we get the last point. 
    3828                  
    3829             try: 
    3830                 data[i] = (float(xi), float(f(xi))) 
    3831             except (ZeroDivisionError, TypeError, ValueError, OverflowError), msg: 
     3496    options = {'alpha':1,'thickness':1,'rgbcolor':(0,0,1), 
     3497               'plot_points':200, 'plot_division':1000, 
     3498               'max_bend': 0.1, 'rgbcolor': (0,0,1) } 
     3499 
     3500    if kwds.has_key('color') and not kwds.has_key('rgbcolor'): 
     3501        kwds['rgbcolor'] = kwds['color'] 
     3502        del kwds['color'] 
     3503 
     3504    options.update(kwds) 
     3505 
     3506    #parametric_plot will be a list or tuple of two functions (f,g) 
     3507    #and will plotted as (f(x), g(x)) for all x in the given range 
     3508    if parametric: 
     3509        if len(funcs) == 3: 
     3510            raise ValueError, "use parametric_plot3d for parametric plots in 3d dimensions." 
     3511        elif len(funcs) == 2: 
     3512            # 2d 
     3513            f,g = funcs 
     3514        else: 
     3515            raise ValueError, "parametric plots only implemented in 2 and 3 dimensions." 
     3516 
     3517    #or we have only a single function to be plotted: 
     3518    else: 
     3519        f = funcs 
     3520 
     3521    plot_points = int(options['plot_points']) 
     3522    del options['plot_points'] 
     3523    x, data = var_and_list_of_values(xrange, plot_points) 
     3524    data = list(data) 
     3525    xmin = data[0] 
     3526    xmax = data[-1] 
     3527 
     3528    #check to see if funcs is a list of functions that will 
     3529    #be all plotted together. 
     3530    if isinstance(funcs, (list, tuple)) and not parametric: 
     3531        return reduce(operator.add, (plot(f, (xmin, xmax), polar=polar, **kwds) for f in funcs)) 
     3532 
     3533    if len(data) >= 2: 
     3534        delta = data[1]-data[0] 
     3535    else: 
     3536        delta = 0 
     3537 
     3538    random = current_randstate().python_random().random 
     3539    exceptions = 0; msg='' 
     3540    exception_indices = [] 
     3541    for i in range(len(data)): 
     3542        xi = data[i] 
     3543        # Slightly randomize the interior sample points if 
     3544        # randomize is true 
     3545        if i > 0 and i < plot_points-1: 
     3546            if randomize: 
     3547                xi += delta*random() 
     3548            if xi > xmax: 
     3549                xi = xmax 
     3550        elif i == plot_points-1:  
     3551            xi = xmax  # guarantee that we get the last point. 
     3552 
     3553        try: 
     3554            data[i] = (float(xi), float(f(xi))) 
     3555        except (ZeroDivisionError, TypeError, ValueError, OverflowError), msg: 
     3556            sage.misc.misc.verbose("%s\nUnable to compute f(%s)"%(msg, x),1) 
     3557            exceptions += 1 
     3558            exception_indices.append(i) 
     3559 
     3560        if str(data[i][1]) in ['nan', 'NaN']: 
     3561            sage.misc.misc.verbose("%s\nUnable to compute f(%s)"%(msg, x),1) 
     3562            exceptions += 1 
     3563            exception_indices.append(i) 
     3564 
     3565    data = [data[i] for i in range(len(data)) if i not in exception_indices] 
     3566 
     3567    # adaptive refinement 
     3568    i, j = 0, 0 
     3569    max_bend = float(options['max_bend']) 
     3570    del options['max_bend'] 
     3571    plot_division = int(options['plot_division']) 
     3572    del options['plot_division'] 
     3573    while i < len(data) - 1: 
     3574        if abs(data[i+1][1] - data[i][1]) > max_bend: 
     3575            x = float((data[i+1][0] + data[i][0])/2) 
     3576            try: 
     3577                y = float(f(x)) 
     3578                data.insert(i+1, (x, y)) 
     3579            except (ZeroDivisionError, TypeError, ValueError), msg: 
    38323580                sage.misc.misc.verbose("%s\nUnable to compute f(%s)"%(msg, x),1) 
    38333581                exceptions += 1 
    3834                 exception_indices.append(i) 
    3835  
    3836             if str(data[i][1]) in ['nan', 'NaN']: 
    3837                 sage.misc.misc.verbose("%s\nUnable to compute f(%s)"%(msg, x),1) 
    3838                 exceptions += 1 
    3839                 exception_indices.append(i) 
    3840  
    3841         data = [data[i] for i in range(len(data)) if i not in exception_indices] 
    3842              
    3843         # adaptive refinement 
    3844         i, j = 0, 0 
    3845         max_bend = float(options['max_bend']) 
    3846         del options['max_bend'] 
    3847         plot_division = int(options['plot_division']) 
    3848         del options['plot_division'] 
    3849         while i < len(data) - 1: 
    3850             if abs(data[i+1][1] - data[i][1]) > max_bend: 
    3851                 x = float((data[i+1][0] + data[i][0])/2) 
    3852                 try: 
    3853                     y = float(f(x)) 
    3854                     data.insert(i+1, (x, y)) 
    3855                 except (ZeroDivisionError, TypeError, ValueError), msg: 
    3856                     sage.misc.misc.verbose("%s\nUnable to compute f(%s)"%(msg, x),1) 
    3857                     exceptions += 1 
    3858                 j += 1 
    3859                 if j > plot_division: 
    3860                     break 
    3861             else: 
    3862                 i += 1 
    3863  
    3864         if (len(data) == 0 and exceptions > 0) or exceptions > 10: 
    3865             sage.misc.misc.verbose("WARNING: When plotting, failed to evaluate function at %s points."%exceptions, level=0) 
    3866             sage.misc.misc.verbose("Last error message: '%s'"%msg, level=0) 
    3867         if parametric: 
    3868             data = [(fdata, g(x)) for x, fdata in data] 
    3869         if polar: 
    3870             data = [(y*cos(x), y*sin(x)) for x, y in data] 
    3871         G = line(data, coerce=False, **options) 
    3872  
    3873