def my_hyperbolic_triangle(a, b, c, **options): """ Return a hyperbolic triangle in the complex hyperbolic plane with points (a, b, c). Type ``?hyperbolic_triangle`` to see all options. INPUT: - ``a, b, c`` - complex numbers in the upper half complex plane OPTIONS: - ``alpha`` - default: 1 - ``fill`` - default: False - ``thickness`` - default: 1 - ``rgbcolor`` - default: 'blue' - ``linestyle`` - default: 'solid' EXAMPLES: Show a hyperbolic triangle with coordinates 0, `1/2+i\sqrt{3}/2` and `-1/2+i\sqrt{3}/2`:: sage: hyperbolic_triangle(0, -1/2+I*sqrt(3)/2, 1/2+I*sqrt(3)/2) A hyperbolic triangle with coordinates 0, 1 and 2+i:: sage: hyperbolic_triangle(0, 1, 2+i, fill=true, rgbcolor='red') """ from sage.plot.all import Graphics g = Graphics() g._set_extra_kwds(g._extract_kwds_for_show(options)) model = options['model'] npts = options.get('npts',10) sides = options.pop('sides',[1,2,3]) ## Which of the sides we will draw. verbose = options.get('verbose',0) options.pop('model',None); options.pop('method',None) if model=="D": #g.add_primitive(HyperbolicTriangleDisc(a, b, c, **options)) #print "options=",options options['sides']=sides H = HyperbolicTriangleDisc(a, b, c, **options) g += H() else: options.pop('npts',None) if sides == [1,2,3]: if verbose>0: print "adding HyperbolicTriangle({0}, {1}, {2},options={3})".format(a,b,c,options) options.pop('verbose',0) g.add_primitive(HyperbolicTriangle(a, b, c, options)) else: options['sides']=sides if verbose>0: print "adding MyHyperbolicTriangle({0}, {1}, {2},options={3})".format(a,b,c,options) g.add_primitive(MyHyperbolicTriangle(a, b, c, options)) g.set_aspect_ratio(1) return g
def draw_funddom_d(coset_reps,format="MP",z0=I): r""" Draw a fundamental domain for self in the circle model INPUT: - ''format'' -- (default 'Disp') How to present the f.d. = 'S' -- Display directly on the screen - z0 -- (default I) the upper-half plane is mapped to the disk by z-->(z-z0)/(z-z0.conjugate()) EXAMPLES:: sage: G=MySubgroup(Gamma0(3)) sage: G._draw_funddom_d() """ # The fundamental domain consists of copies of the standard fundamental domain pi=RR.pi() from sage.plot.plot import (Graphics,line) g=Graphics() bdcirc=_circ_arc(0 ,2 *pi,0 ,1 ,1000 ) g=g+bdcirc # Corners x1=-RR(0.5) ; y1=RR(sqrt(3 )/2) x2=RR(0.5) ; y2=RR(sqrt(3 )/2) z_inf=1 l1 = _geodesic_between_two_points_d(x1,y1,x1,infinity) l2 = _geodesic_between_two_points_d(x2,y2,x2,infinity) c0 = _geodesic_between_two_points_d(x1,y1,x2,y2) tri=c0+l1+l2 g=g+tri for A in coset_reps: [a,b,c,d]=A if(a==1 and b==0 and c==0 and d==1 ): continue if(a<0 ): a=-a; b=-b; c=-c; d=-1 if(c==0 ): # then this is easier l1 = _geodesic_between_two_points_d(x1+b,y1,x1+b,infinity) l2 = _geodesic_between_two_points_d(x2+b,y2,x2+b,infinity) c0 = _geodesic_between_two_points_d(x1+b,y1,x2+b,y2) # c0=line(L0); l1=line(L1); l2=line(L2); l3=line(L3) tri=c0+l1+l2 g=g+tri else: den=(c*x1+d)**2 +c**2 *y1**2 x1_t=(a*c*(x1**2 +y1**2 )+(a*d+b*c)*x1+b*d)/den y1_t=y1/den den=(c*x2+d)**2 +c**2 *y2**2 x2_t=(a*c*(x2**2 +y2**2 )+(a*d+b*c)*x2+b*d)/den y2_t=y2/den inf_t=a/c c0=_geodesic_between_two_points_d(x1_t,y1_t,x2_t,y2_t) c1=_geodesic_between_two_points_d(x1_t,y1_t,inf_t,0.0 ) c2=_geodesic_between_two_points_d(x2_t,y2_t,inf_t,0.0 ) tri=c0+c1+c2 g=g+tri g.xmax(1 ) g.ymax(1 ) g.xmin(-1 ) g.ymin(-1 ) g.set_aspect_ratio(1 ) return g
def newton_plot(self): S = [QQ(s) for s in self.slopes] C = Counter(S) pts = [(0,0)] x = y = 0 for s in sorted(C): c = C[s] x += c y += c*s pts.append((x,y)) L = Graphics() L += line([(0,0),(0,y+0.2)],color="grey") for i in range(1,y+1): L += line([(0,i),(0.06,i)],color="grey") for i in range(1,C[0]): L += line([(i,0),(i,0.06)],color="grey") for i in range(len(pts)-1): P = pts[i] Q = pts[i+1] for x in range(P[0],Q[0]+1): L += line([(x,P[1]),(x,P[1] + (x-P[0])*(Q[1]-P[1])/(Q[0]-P[0]))],color="grey") for y in range(P[1],Q[1]): L += line([(P[0] + (y-P[1])*(Q[0]-P[0])/(Q[1]-P[1]),y),(Q[0],y)],color="grey") L += line(pts, thickness = 2) L.axes(False) L.set_aspect_ratio(1) return encode_plot(L, pad=0, pad_inches=0, bbox_inches='tight')
def newton_plot(self): S = [QQ(s) for s in self.polygon_slopes] C = Counter(S) pts = [(0, 0)] x = y = 0 for s in sorted(C): c = C[s] x += c y += c * s pts.append((x, y)) L = Graphics() L += line([(0, 0), (0, y + 0.2)], color="grey") for i in range(1, y + 1): L += line([(0, i), (0.06, i)], color="grey") for i in range(1, C[0]): L += line([(i, 0), (i, 0.06)], color="grey") for i in range(len(pts) - 1): P = pts[i] Q = pts[i + 1] for x in range(P[0], Q[0] + 1): L += line( [(x, P[1]), (x, P[1] + (x - P[0]) * (Q[1] - P[1]) / (Q[0] - P[0]))], color="grey", ) for y in range(P[1], Q[1]): L += line( [(P[0] + (y - P[1]) * (Q[0] - P[0]) / (Q[1] - P[1]), y), (Q[0], y)], color="grey", ) L += line(pts, thickness=2) L.axes(False) L.set_aspect_ratio(1) return encode_plot(L, pad=0, pad_inches=0, bbox_inches="tight")
def hyperbolic_polygon(pts, **options): r""" Return a hyperbolic polygon in the hyperbolic plane with vertices ``pts``. Type ``?hyperbolic_polygon`` to see all options. INPUT: - ``pts`` -- a list or tuple of complex numbers OPTIONS: - ``alpha`` -- default: 1 - ``fill`` -- default: ``False`` - ``thickness`` -- default: 1 - ``rgbcolor`` -- default: ``'blue'`` - ``linestyle`` -- (default: ``'solid'``) The style of the line, which is one of ``'dashed'``, ``'dotted'``, ``'solid'``, ``'dashdot'``, or ``'--'``, ``':'``, ``'-'``, ``'-.'``, respectively. EXAMPLES: Show a hyperbolic polygon with coordinates `-1`, `3i`, `2+2i`, `1+i`:: sage: hyperbolic_polygon([-1,3*I,2+2*I,1+I]) Graphics object consisting of 1 graphics primitive .. PLOT:: P = hyperbolic_polygon([-1,3*I,2+2*I,1+I]) sphinx_plot(P) With more options:: sage: hyperbolic_polygon([-1,3*I,2+2*I,1+I], fill=True, color='red') Graphics object consisting of 1 graphics primitive .. PLOT:: P = hyperbolic_polygon([-1,3*I,2+2*I,1+I], fill=True, color='red') sphinx_plot(P) """ from sage.plot.all import Graphics g = Graphics() g._set_extra_kwds(g._extract_kwds_for_show(options)) g.add_primitive(HyperbolicPolygon(pts, options)) g.set_aspect_ratio(1) return g
def hyperbolic_arc(a, b, **options): """ Plot an arc from a to b in hyperbolic geometry in the complex upper half plane. INPUT: - ``a, b`` - complex numbers in the upper half complex plane connected bye the arc OPTIONS: - ``alpha`` - default: 1 - ``thickness`` - default: 1 - ``rgbcolor`` - default: 'blue' - ``linestyle`` - (default: ``'solid'``) The style of the line, which is one of ``'dashed'``, ``'dotted'``, ``'solid'``, ``'dashdot'``, or ``'--'``, ``':'``, ``'-'``, ``'-.'``, respectively. Examples: Show a hyperbolic arc from 0 to 1:: sage: hyperbolic_arc(0, 1) Graphics object consisting of 1 graphics primitive Show a hyperbolic arc from 1/2 to `i` with a red thick line:: sage: hyperbolic_arc(1/2, I, color='red', thickness=2) Graphics object consisting of 1 graphics primitive Show a hyperbolic arc form `i` to `2 i` with dashed line:: sage: hyperbolic_arc(I, 2*I, linestyle='dashed') Graphics object consisting of 1 graphics primitive sage: hyperbolic_arc(I, 2*I, linestyle='--') Graphics object consisting of 1 graphics primitive """ from sage.plot.all import Graphics g = Graphics() g._set_extra_kwds(g._extract_kwds_for_show(options)) g.add_primitive(HyperbolicArc(a, b, options)) g.set_aspect_ratio(1) return g
def hyperbolic_arc(a, b, **options): """ Plot an arc from a to b in hyperbolic geometry in the complex upper half plane. INPUT: - ``a, b`` - complex numbers in the upper half complex plane connected bye the arc OPTIONS: - ``alpha`` - default: 1 - ``thickness`` - default: 1 - ``rgbcolor`` - default: 'blue' - ``linestyle`` - (default: ``'solid'``) The style of the line, which is one of ``'dashed'``, ``'dotted'``, ``'solid'``, ``'dashdot'``, or ``'--'``, ``':'``, ``'-'``, ``'-.'``, respectively. Examples: Show a hyperbolic arc from 0 to 1:: sage: hyperbolic_arc(0, 1) Graphics object consisting of 1 graphics primitive Show a hyperbolic arc from 1/2 to `i` with a red thick line:: sage: hyperbolic_arc(1/2, I, color='red', thickness=2) Graphics object consisting of 1 graphics primitive Show a hyperbolic arc form `i` to `2 i` with dashed line:: sage: hyperbolic_arc(I, 2*I, linestyle='dashed') Graphics object consisting of 1 graphics primitive sage: hyperbolic_arc(I, 2*I, linestyle='--') Graphics object consisting of 1 graphics primitive """ from sage.plot.all import Graphics g = Graphics() g._set_extra_kwds(g._extract_kwds_for_show(options)) g.add_primitive(HyperbolicArc(a, b, options)) g.set_aspect_ratio(1) return g
def my_hyperbolic_triangle(a, b, c, **options): """ Return a hyperbolic triangle in the complex hyperbolic plane with points (a, b, c). Type ``?hyperbolic_triangle`` to see all options. INPUT: - ``a, b, c`` - complex numbers in the upper half complex plane OPTIONS: - ``alpha`` - default: 1 - ``fill`` - default: False - ``thickness`` - default: 1 - ``rgbcolor`` - default: 'blue' - ``linestyle`` - default: 'solid' EXAMPLES: Show a hyperbolic triangle with coordinates 0, `1/2+i\sqrt{3}/2` and `-1/2+i\sqrt{3}/2`:: sage: hyperbolic_triangle(0, -1/2+I*sqrt(3)/2, 1/2+I*sqrt(3)/2) A hyperbolic triangle with coordinates 0, 1 and 2+i:: sage: hyperbolic_triangle(0, 1, 2+i, fill=true, rgbcolor='red') """ from sage.plot.all import Graphics g = Graphics() g._set_extra_kwds(g._extract_kwds_for_show(options)) model = options['model'] options.pop('model',None); options.pop('method',None) if model=="D": #g.add_primitive(HyperbolicTriangleDisc(a, b, c, **options)) H = HyperbolicTriangleDisc(a, b, c, **options) g += H() else: g.add_primitive(HyperbolicTriangle(a, b, c, options)) g.set_aspect_ratio(1) return g
def plot_completely_periodic(self): from sage.plot.all import polygon2d, Graphics, point2d, text O = self.orbit G = [] u = self.u # direction (that we put horizontal) m = matrix(2, [u[1], -u[0], u[1], u[0]]) indices = {} xmin = xmax = ymin = ymax = 0 for comp in self.decomposition.components(): H = Graphics() x = O.V2._isomorphic_vector_space.zero() pts = [x] below = True for p in comp.perimeter(): sc = p.saddleConnection() y = x + m * O.V2._isomorphic_vector_space( O.V2(p.saddleConnection().vector())) if p.vertical(): if sc in indices: i = indices[sc] else: i = len(indices) // 2 indices[sc] = i indices[-sc] = i if below: H += text(str(i), (x + y) / 2, color='black') x = y xmin = min(xmin, x[0]) xmax = max(xmax, x[0]) ymin = min(ymin, x[1]) ymax = max(ymax, x[1]) pts.append(x) H += polygon2d(pts, color='blue', alpha=0.3) H += point2d(pts, color='red', pointsize=20) G.append(H) aspect_ratio = float(xmax - xmin) / float(ymax - ymin) for H in G: H.set_axes_range(xmin, xmax, ymin, ymax) H.axes(False) H.set_aspect_ratio(aspect_ratio) return G
def hyperbolic_triangle(a, b, c, **options): """ Return a hyperbolic triangle in the complex hyperbolic plane with points (a, b, c). Type ``?hyperbolic_triangle`` to see all options. INPUT: - ``a, b, c`` - complex numbers in the upper half complex plane OPTIONS: - ``alpha`` - default: 1 - ``fill`` - default: False - ``thickness`` - default: 1 - ``rgbcolor`` - default: 'blue' - ``linestyle`` - (default: ``'solid'``) The style of the line, which is one of ``'dashed'``, ``'dotted'``, ``'solid'``, ``'dashdot'``, or ``'--'``, ``':'``, ``'-'``, ``'-.'``, respectively. EXAMPLES: Show a hyperbolic triangle with coordinates 0, `1/2+i\sqrt{3}/2` and `-1/2+i\sqrt{3}/2`:: sage: hyperbolic_triangle(0, -1/2+I*sqrt(3)/2, 1/2+I*sqrt(3)/2) Graphics object consisting of 1 graphics primitive A hyperbolic triangle with coordinates 0, 1 and 2+i and a dashed line:: sage: hyperbolic_triangle(0, 1, 2+i, fill=true, rgbcolor='red', linestyle='--') Graphics object consisting of 1 graphics primitive """ from sage.plot.all import Graphics g = Graphics() g._set_extra_kwds(g._extract_kwds_for_show(options)) g.add_primitive(HyperbolicTriangle(a, b, c, options)) g.set_aspect_ratio(1) return g
def hyperbolic_arc(a, b, **options): """ Plot an arc from a to b in hyperbolic geometry in the complex upper half plane. INPUT: - ``a, b`` - complex numbers in the upper half complex plane connected bye the arc OPTIONS: - ``alpha`` - default: 1 - ``thickness`` - default: 1 - ``rgbcolor`` - default: 'blue' - ``linestyle`` - default: 'solid' Examples: Show a hyperbolic arc from 0 to 1:: sage: hyperbolic_arc(0, 1) Show a hyperbolic arc from 1/2 to `i` with a red thick line:: sage: hyperbolic_arc(1/2, I, color='red', thickness=2) Show a hyperbolic arc form `i` to `2 i` with dashed line:: sage: hyperbolic_arc(I, 2*I, linestyle='dashed') """ from sage.plot.all import Graphics g = Graphics() g._set_extra_kwds(g._extract_kwds_for_show(options)) g.add_primitive(HyperbolicArc(a, b, options)) g.set_aspect_ratio(1) return g
def hyperbolic_arc(a, b, **options): """ Plot an arc from a to b in hyperbolic geometry in the complex upper half plane. INPUT: - ``a, b`` - complex numbers in the upper half complex plane connected bye the arc OPTIONS: - ``alpha`` - default: 1 - ``thickness`` - default: 1 - ``rgbcolor`` - default: 'blue' - ``linestyle`` - default: 'solid' Examples: Show a hyperbolic arc from 0 to 1:: sage: hyperbolic_arc(0, 1) Show a hyperbolic arc from 1/2 to `i` with a red thick line:: sage: hyperbolic_arc(1/2, I, color='red', thickness=2) Show a hyperbolic arc form `i` to `2 i` with dashed line:: sage: hyperbolic_arc(I, 2*I, linestyle='dashed') """ from sage.plot.all import Graphics g = Graphics() g._set_extra_kwds(g._extract_kwds_for_show(options)) g.add_primitive(HyperbolicArc(a, b, options)) g.set_aspect_ratio(1) return g
def hyperbolic_triangle(a, b, c, **options): """ Return a hyperbolic triangle in the complex hyperbolic plane with points (a, b, c). Type ``?hyperbolic_triangle`` to see all options. INPUT: - ``a, b, c`` - complex numbers in the upper half complex plane OPTIONS: - ``alpha`` - default: 1 - ``fill`` - default: False - ``thickness`` - default: 1 - ``rgbcolor`` - default: 'blue' - ``linestyle`` - (default: ``'solid'``) The style of the line, which is one of ``'dashed'``, ``'dotted'``, ``'solid'``, ``'dashdot'``, or ``'--'``, ``':'``, ``'-'``, ``'-.'``, respectively. EXAMPLES: Show a hyperbolic triangle with coordinates 0, `1/2+i\sqrt{3}/2` and `-1/2+i\sqrt{3}/2`:: sage: hyperbolic_triangle(0, -1/2+I*sqrt(3)/2, 1/2+I*sqrt(3)/2) A hyperbolic triangle with coordinates 0, 1 and 2+i and a dashed line:: sage: hyperbolic_triangle(0, 1, 2+i, fill=true, rgbcolor='red', linestyle='--') """ from sage.plot.all import Graphics g = Graphics() g._set_extra_kwds(g._extract_kwds_for_show(options)) g.add_primitive(HyperbolicTriangle(a, b, c, options)) g.set_aspect_ratio(1) return g
def hyperbolic_triangle(a, b, c, **options): """ Return a hyperbolic triangle in the complex hyperbolic plane with points (a, b, c). Type ``?hyperbolic_triangle`` to see all options. INPUT: - ``a, b, c`` - complex numbers in the upper half complex plane OPTIONS: - ``alpha`` - default: 1 - ``fill`` - default: False - ``thickness`` - default: 1 - ``rgbcolor`` - default: 'blue' - ``linestyle`` - default: 'solid' EXAMPLES: Show a hyperbolic triangle with coordinates 0, `1/2+i\sqrt{3}/2` and `-1/2+i\sqrt{3}/2`:: sage: hyperbolic_triangle(0, -1/2+I*sqrt(3)/2, 1/2+I*sqrt(3)/2) A hyperbolic triangle with coordinates 0, 1 and 2+i:: sage: hyperbolic_triangle(0, 1, 2+i, fill=true, rgbcolor='red') """ from sage.plot.all import Graphics g = Graphics() g._set_extra_kwds(g._extract_kwds_for_show(options)) g.add_primitive(HyperbolicTriangle(a, b, c, options)) g.set_aspect_ratio(1) return g
def my_hyperbolic_triangle(a, b, c, **options): """ Return a hyperbolic triangle in the complex hyperbolic plane with points (a, b, c). Type ``?hyperbolic_triangle`` to see all options. INPUT: - ``a, b, c`` - complex numbers in the upper half complex plane OPTIONS: - ``alpha`` - default: 1 - ``fill`` - default: False - ``thickness`` - default: 1 - ``rgbcolor`` - default: 'blue' - ``linestyle`` - default: 'solid' EXAMPLES: Show a hyperbolic triangle with coordinates 0, `1/2+i\sqrt{3}/2` and `-1/2+i\sqrt{3}/2`:: sage: hyperbolic_triangle(0, -1/2+I*sqrt(3)/2, 1/2+I*sqrt(3)/2) A hyperbolic triangle with coordinates 0, 1 and 2+i:: sage: hyperbolic_triangle(0, 1, 2+i, fill=true, rgbcolor='red') """ from sage.plot.all import Graphics g = Graphics() g._set_extra_kwds(g._extract_kwds_for_show(options)) model = options['model'] npts = options.get('npts', 10) sides = options.pop('sides', [1, 2, 3]) ## Which of the sides we will draw. verbose = options.get('verbose', 0) options.pop('model', None) options.pop('method', None) if model == "D": #g.add_primitive(HyperbolicTriangleDisc(a, b, c, **options)) #print "options=",options options['sides'] = sides H = HyperbolicTriangleDisc(a, b, c, **options) g += H() else: options.pop('npts', None) if sides == [1, 2, 3]: if verbose > 0: print "adding HyperbolicTriangle({0}, {1}, {2},options={3})".format( a, b, c, options) options.pop('verbose', 0) ## check if We need my class or the original class g.add_primitive(HyperbolicTriangle(a, b, c, options)) else: options['sides'] = sides if verbose > 0: print "adding HyperbolicTriangle({0}, {1}, {2},options={3})".format( a, b, c, options) g.add_primitive(HyperbolicTriangle(a, b, c, options)) g.set_aspect_ratio(1) return g
def plot(self, **kwds): """ Returns a graphics object representing the (di)graph. INPUT: - pos -- an optional positioning dictionary - layout -- what kind of layout to use, takes precedence over pos - 'circular' -- plots the graph with vertices evenly distributed on a circle - 'spring' -- uses the traditional spring layout, using the graph's current positions as initial positions - 'tree' -- the (di)graph must be a tree. One can specify the root of the tree using the keyword tree_root, otherwise a root will be selected at random. Then the tree will be plotted in levels, depending on minimum distance for the root. - vertex_labels -- whether to print vertex labels edge_labels -- whether to print edge labels. By default, False, but if True, the result of str(l) is printed on the edge for each label l. Labels equal to None are not printed (to set edge labels, see set_edge_label). - vertex_size -- size of vertices displayed - vertex_shape -- the shape to draw the vertices (Not available for multiedge digraphs. - graph_border -- whether to include a box around the graph - vertex_colors -- optional dictionary to specify vertex colors: 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). - edge_colors -- a dictionary specifying edge colors: each key is a color recognized by matplotlib, and each entry is a list of edges. - partition -- a partition of the vertex set. if specified, plot will show each cell in a different color. vertex_colors takes precedence. - talk -- if true, prints large vertices with white backgrounds so that labels are legible on slides - iterations -- how many iterations of the spring layout algorithm to go through, if applicable - color_by_label -- if True, color edges by their labels - heights -- if specified, this is a dictionary from a set of floating point heights to a set of vertices - edge_style -- keyword arguments passed into the edge-drawing routine. This currently only works for directed graphs, since we pass off the undirected graph to networkx - tree_root -- 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'. - tree_orientation -- "up" or "down" (default is "down"). If "up" (resp., "down"), then the root of the tree will appear on the bottom (resp., top) and the tree will grow upwards (resp. downwards). Ignored unless layout='tree'. - save_pos -- save position computed during plotting EXAMPLES:: sage: from sage.graphs.graph_plot import graphplot_options sage: list(sorted(graphplot_options.iteritems())) [('by_component', 'Whether to do the spring layout by connected component -- a boolean.'), ('color_by_label', 'Whether or not to color the edges by their label values.'), ('dim', 'The dimension of the layout -- 2 or 3.'), ('dist', 'The distance between multiedges.'), ('edge_color', 'The default color for edges.'), ('edge_colors', 'Dictionary of edge coloring.'), ('edge_labels', 'Whether or not to draw edge labels.'), ('edge_style', 'The linestyle of the edges-- one of "solid", "dashed", "dotted", dashdot".'), ('graph_border', 'Whether or not to draw a frame around the graph.'), ('heights', 'A dictionary mapping heights to the list of vertices at this height.'), ('iterations', 'The number of times to execute the spring layout algorithm.'), ('layout', 'A layout algorithm -- one of "acyclic", "circular", "ranked", "graphviz", "planar", "spring", or "tree".'), ('loop_size', 'The radius of the smallest loop.'), ('max_dist', 'The max distance range to allow multiedges.'), ('partition', 'A partition of the vertex set. (Draws each cell of vertices in a different color).'), ('pos', 'The position dictionary of vertices'), ('prog', 'Which graphviz layout program to use -- one of "circo", "dot", "fdp", "neato", or "twopi".'), ('save_pos', 'Whether or not to save the computed position for the graph.'), ('spring', 'Use spring layout to finalize the current layout.'), ('talk', 'Whether to display the vertices in talk mode (larger and white)'), ('tree_orientation', 'The direction of tree branches -- "up" or "down".'), ('tree_root', 'A vertex designation for drawing trees.'), ('vertex_colors', 'Dictionary of vertex coloring.'), ('vertex_labels', 'Whether or not to draw vertex labels.'), ('vertex_shape', 'The shape to draw the vertices, Currently unavailable for Multi-edged DiGraphs.'), ('vertex_size', 'The size to draw the vertices.')] sage: from math import sin, cos, pi sage: P = graphs.PetersenGraph() sage: d = {'#FF0000':[0,5], '#FF9900':[1,6], '#FFFF00':[2,7], '#00FF00':[3,8], '#0000FF':[4,9]} sage: pos_dict = {} sage: for i in range(5): ... x = float(cos(pi/2 + ((2*pi)/5)*i)) ... y = float(sin(pi/2 + ((2*pi)/5)*i)) ... pos_dict[i] = [x,y] ... sage: for i in range(10)[5:]: ... x = float(0.5*cos(pi/2 + ((2*pi)/5)*i)) ... y = float(0.5*sin(pi/2 + ((2*pi)/5)*i)) ... pos_dict[i] = [x,y] ... sage: pl = P.graphplot(pos=pos_dict, vertex_colors=d) sage: pl.show() sage: C = graphs.CubeGraph(8) sage: P = C.graphplot(vertex_labels=False, vertex_size=0, graph_border=True) sage: P.show() sage: G = graphs.HeawoodGraph().copy(sparse=True) sage: for u,v,l in G.edges(): ... G.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')') sage: G.graphplot(edge_labels=True).show() sage: D = DiGraph( { 0: [1, 10, 19], 1: [8, 2], 2: [3, 6], 3: [19, 4], 4: [17, 5], 5: [6, 15], 6: [7], 7: [8, 14], 8: [9], 9: [10, 13], 10: [11], 11: [12, 18], 12: [16, 13], 13: [14], 14: [15], 15: [16], 16: [17], 17: [18], 18: [19], 19: []}, implementation='networkx' ) sage: for u,v,l in D.edges(): ... D.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')') sage: D.graphplot(edge_labels=True, layout='circular').show() sage: from sage.plot.colors import rainbow sage: C = graphs.CubeGraph(5) sage: R = rainbow(5) sage: edge_colors = {} sage: for i in range(5): ... edge_colors[R[i]] = [] sage: for u,v,l in C.edges(): ... for i in range(5): ... if u[i] != v[i]: ... edge_colors[R[i]].append((u,v,l)) sage: C.graphplot(vertex_labels=False, vertex_size=0, edge_colors=edge_colors).show() sage: D = graphs.DodecahedralGraph() sage: Pi = [[6,5,15,14,7],[16,13,8,2,4],[12,17,9,3,1],[0,19,18,10,11]] sage: D.show(partition=Pi) sage: G = graphs.PetersenGraph() sage: G.allow_loops(True) sage: G.add_edge(0,0) sage: G.show() sage: D = DiGraph({0:[0,1], 1:[2], 2:[3]}, loops=True) sage: D.show() sage: D.show(edge_colors={(0,1,0):[(0,1,None),(1,2,None)],(0,0,0):[(2,3,None)]}) sage: pos = {0:[0.0, 1.5], 1:[-0.8, 0.3], 2:[-0.6, -0.8], 3:[0.6, -0.8], 4:[0.8, 0.3]} sage: g = Graph({0:[1], 1:[2], 2:[3], 3:[4], 4:[0]}) sage: g.graphplot(pos=pos, layout='spring', iterations=0).plot() sage: G = Graph() sage: P = G.graphplot().plot() sage: P.axes() False sage: G = DiGraph() sage: P = G.graphplot().plot() sage: P.axes() False sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}).plot() sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}).plot() sage: t.set_edge_label(0,1,-7) sage: t.set_edge_label(0,5,3) sage: t.set_edge_label(0,5,99) sage: t.set_edge_label(1,2,1000) sage: t.set_edge_label(3,2,'spam') sage: t.set_edge_label(2,6,3/2) sage: t.set_edge_label(0,4,66) sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}, edge_labels=True).plot() sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(layout='tree').show() sage: t = DiGraph('JCC???@A??GO??CO??GO??') sage: t.graphplot(layout='tree', tree_root=0, tree_orientation="up").show() sage: D = DiGraph({0:[1,2,3], 2:[1,4], 3:[0]}) sage: D.graphplot().show() sage: D = DiGraph(multiedges=True, sparse=True) sage: for i in range(5): ... D.add_edge((i,i+1,'a')) ... D.add_edge((i,i-1,'b')) sage: D.graphplot(edge_labels=True,edge_colors=D._color_by_label()).plot() sage: g = Graph({}, loops=True, multiedges=True, sparse=True) sage: g.add_edges([(0,0,'a'),(0,0,'b'),(0,1,'c'),(0,1,'d'), ... (0,1,'e'),(0,1,'f'),(0,1,'f'),(2,1,'g'),(2,2,'h')]) sage: g.graphplot(edge_labels=True, color_by_label=True, edge_style='dashed').plot() """ G = Graphics() for comp in self._plot_components.values(): if not isinstance(comp, list): G += comp else: for item in comp: G += item G.set_axes_range(*(self._graph._layout_bounding_box(self._pos))) if self._options['graph_border']: xmin = G.xmin() xmax = G.xmax() ymin = G.ymin() ymax = G.ymax() dx = (xmax-xmin)/10.0 dy = (ymax-ymin)/10.0 border = (line([( xmin - dx, ymin - dy), ( xmin - dx, ymax + dy ), ( xmax + dx, ymax + dy ), ( xmax + dx, ymin - dy ), ( xmin - dx, ymin - dy )], thickness=1.3)) border.axes_range(xmin = (xmin - dx), xmax = (xmax + dx), ymin = (ymin - dy), ymax = (ymax + dy)) G += border G.set_aspect_ratio(1) G.axes(False) G._extra_kwds['axes_pad']=.05 return G
def plot(self, **kwds): """ Returns a graphics object representing the (di)graph. INPUT: The options accepted by this method are to be found in the documentation of module :mod:`sage.graphs.graph_plot`. .. NOTE:: See :mod:`the module's documentation <sage.graphs.graph_plot>` for information on default values of this method. We can specify some pretty precise plotting of familiar graphs:: sage: from math import sin, cos, pi sage: P = graphs.PetersenGraph() sage: d = {'#FF0000':[0,5], '#FF9900':[1,6], '#FFFF00':[2,7], '#00FF00':[3,8], '#0000FF':[4,9]} sage: pos_dict = {} sage: for i in range(5): ... x = float(cos(pi/2 + ((2*pi)/5)*i)) ... y = float(sin(pi/2 + ((2*pi)/5)*i)) ... pos_dict[i] = [x,y] ... sage: for i in range(10)[5:]: ... x = float(0.5*cos(pi/2 + ((2*pi)/5)*i)) ... y = float(0.5*sin(pi/2 + ((2*pi)/5)*i)) ... pos_dict[i] = [x,y] ... sage: pl = P.graphplot(pos=pos_dict, vertex_colors=d) sage: pl.show() Here are some more common graphs with typical options:: sage: C = graphs.CubeGraph(8) sage: P = C.graphplot(vertex_labels=False, vertex_size=0, graph_border=True) sage: P.show() sage: G = graphs.HeawoodGraph().copy(sparse=True) sage: for u,v,l in G.edges(): ... G.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')') sage: G.graphplot(edge_labels=True).show() The options for plotting also work with directed graphs:: sage: D = DiGraph( { 0: [1, 10, 19], 1: [8, 2], 2: [3, 6], 3: [19, 4], 4: [17, 5], 5: [6, 15], 6: [7], 7: [8, 14], 8: [9], 9: [10, 13], 10: [11], 11: [12, 18], 12: [16, 13], 13: [14], 14: [15], 15: [16], 16: [17], 17: [18], 18: [19], 19: []}, implementation='networkx' ) sage: for u,v,l in D.edges(): ... D.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')') sage: D.graphplot(edge_labels=True, layout='circular').show() This example shows off the coloring of edges:: sage: from sage.plot.colors import rainbow sage: C = graphs.CubeGraph(5) sage: R = rainbow(5) sage: edge_colors = {} sage: for i in range(5): ... edge_colors[R[i]] = [] sage: for u,v,l in C.edges(): ... for i in range(5): ... if u[i] != v[i]: ... edge_colors[R[i]].append((u,v,l)) sage: C.graphplot(vertex_labels=False, vertex_size=0, edge_colors=edge_colors).show() With the ``partition`` option, we can separate out same-color groups of vertices:: sage: D = graphs.DodecahedralGraph() sage: Pi = [[6,5,15,14,7],[16,13,8,2,4],[12,17,9,3,1],[0,19,18,10,11]] sage: D.show(partition=Pi) Loops are also plotted correctly:: sage: G = graphs.PetersenGraph() sage: G.allow_loops(True) sage: G.add_edge(0,0) sage: G.show() :: sage: D = DiGraph({0:[0,1], 1:[2], 2:[3]}, loops=True) sage: D.show() sage: D.show(edge_colors={(0,1,0):[(0,1,None),(1,2,None)],(0,0,0):[(2,3,None)]}) More options:: sage: pos = {0:[0.0, 1.5], 1:[-0.8, 0.3], 2:[-0.6, -0.8], 3:[0.6, -0.8], 4:[0.8, 0.3]} sage: g = Graph({0:[1], 1:[2], 2:[3], 3:[4], 4:[0]}) sage: g.graphplot(pos=pos, layout='spring', iterations=0).plot() sage: G = Graph() sage: P = G.graphplot().plot() sage: P.axes() False sage: G = DiGraph() sage: P = G.graphplot().plot() sage: P.axes() False We can plot multiple graphs:: sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}).plot() :: sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}).plot() sage: t.set_edge_label(0,1,-7) sage: t.set_edge_label(0,5,3) sage: t.set_edge_label(0,5,99) sage: t.set_edge_label(1,2,1000) sage: t.set_edge_label(3,2,'spam') sage: t.set_edge_label(2,6,3/2) sage: t.set_edge_label(0,4,66) sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}, edge_labels=True).plot() :: sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(layout='tree').show() The tree layout is also useful:: sage: t = DiGraph('JCC???@A??GO??CO??GO??') sage: t.graphplot(layout='tree', tree_root=0, tree_orientation="up").show() More examples:: sage: D = DiGraph({0:[1,2,3], 2:[1,4], 3:[0]}) sage: D.graphplot().show() sage: D = DiGraph(multiedges=True, sparse=True) sage: for i in range(5): ... D.add_edge((i,i+1,'a')) ... D.add_edge((i,i-1,'b')) sage: D.graphplot(edge_labels=True,edge_colors=D._color_by_label()).plot() sage: g = Graph({}, loops=True, multiedges=True, sparse=True) sage: g.add_edges([(0,0,'a'),(0,0,'b'),(0,1,'c'),(0,1,'d'), ... (0,1,'e'),(0,1,'f'),(0,1,'f'),(2,1,'g'),(2,2,'h')]) sage: g.graphplot(edge_labels=True, color_by_label=True, edge_style='dashed').plot() Wrong input (any input) :trac:`13891`:: sage: graphs.PetersenGraph().graphplot().plot(aertataert=346345345) doctest:...: DeprecationWarning: This method takes no argument ! You may want to give it as an argument to graphplot instead. See http://trac.sagemath.org/13891 for details. <BLANKLINE> """ # This method takes NO input # This has been added in early 2013. Remove it before my death, please. if kwds: from sage.misc.superseded import deprecation deprecation(13891, "This method takes no argument ! You may want " "to give it as an argument to graphplot instead.") G = Graphics() for comp in self._plot_components.values(): if not isinstance(comp, list): G += comp else: for item in comp: G += item G.set_axes_range(*(self._graph._layout_bounding_box(self._pos))) if self._options['graph_border']: xmin = G.xmin() xmax = G.xmax() ymin = G.ymin() ymax = G.ymax() dx = (xmax-xmin)/10.0 dy = (ymax-ymin)/10.0 border = (line([( xmin - dx, ymin - dy), ( xmin - dx, ymax + dy ), ( xmax + dx, ymax + dy ), ( xmax + dx, ymin - dy ), ( xmin - dx, ymin - dy )], thickness=1.3)) border.axes_range(xmin = (xmin - dx), xmax = (xmax + dx), ymin = (ymin - dy), ymax = (ymax + dy)) G += border G.set_aspect_ratio(1) G.axes(False) G._extra_kwds['axes_pad']=.05 return G
def plot(self, **kwds): """ Returns a graphics object representing the (di)graph. INPUT: The options accepted by this method are to be found in the documentation of the :mod:`sage.graphs.graph_plot` module, and the :meth:`~sage.plot.graphics.Graphics.show` method. .. NOTE:: See :mod:`the module's documentation <sage.graphs.graph_plot>` for information on default values of this method. We can specify some pretty precise plotting of familiar graphs:: sage: from math import sin, cos, pi sage: P = graphs.PetersenGraph() sage: d = {'#FF0000':[0,5], '#FF9900':[1,6], '#FFFF00':[2,7], '#00FF00':[3,8], '#0000FF':[4,9]} sage: pos_dict = {} sage: for i in range(5): ... x = float(cos(pi/2 + ((2*pi)/5)*i)) ... y = float(sin(pi/2 + ((2*pi)/5)*i)) ... pos_dict[i] = [x,y] ... sage: for i in range(10)[5:]: ... x = float(0.5*cos(pi/2 + ((2*pi)/5)*i)) ... y = float(0.5*sin(pi/2 + ((2*pi)/5)*i)) ... pos_dict[i] = [x,y] ... sage: pl = P.graphplot(pos=pos_dict, vertex_colors=d) sage: pl.show() Here are some more common graphs with typical options:: sage: C = graphs.CubeGraph(8) sage: P = C.graphplot(vertex_labels=False, vertex_size=0, graph_border=True) sage: P.show() sage: G = graphs.HeawoodGraph().copy(sparse=True) sage: for u,v,l in G.edges(): ... G.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')') sage: G.graphplot(edge_labels=True).show() The options for plotting also work with directed graphs:: sage: D = DiGraph( { 0: [1, 10, 19], 1: [8, 2], 2: [3, 6], 3: [19, 4], 4: [17, 5], 5: [6, 15], 6: [7], 7: [8, 14], 8: [9], 9: [10, 13], 10: [11], 11: [12, 18], 12: [16, 13], 13: [14], 14: [15], 15: [16], 16: [17], 17: [18], 18: [19], 19: []}) sage: for u,v,l in D.edges(): ... D.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')') sage: D.graphplot(edge_labels=True, layout='circular').show() This example shows off the coloring of edges:: sage: from sage.plot.colors import rainbow sage: C = graphs.CubeGraph(5) sage: R = rainbow(5) sage: edge_colors = {} sage: for i in range(5): ... edge_colors[R[i]] = [] sage: for u,v,l in C.edges(): ... for i in range(5): ... if u[i] != v[i]: ... edge_colors[R[i]].append((u,v,l)) sage: C.graphplot(vertex_labels=False, vertex_size=0, edge_colors=edge_colors).show() With the ``partition`` option, we can separate out same-color groups of vertices:: sage: D = graphs.DodecahedralGraph() sage: Pi = [[6,5,15,14,7],[16,13,8,2,4],[12,17,9,3,1],[0,19,18,10,11]] sage: D.show(partition=Pi) Loops are also plotted correctly:: sage: G = graphs.PetersenGraph() sage: G.allow_loops(True) sage: G.add_edge(0,0) sage: G.show() :: sage: D = DiGraph({0:[0,1], 1:[2], 2:[3]}, loops=True) sage: D.show() sage: D.show(edge_colors={(0,1,0):[(0,1,None),(1,2,None)],(0,0,0):[(2,3,None)]}) More options:: sage: pos = {0:[0.0, 1.5], 1:[-0.8, 0.3], 2:[-0.6, -0.8], 3:[0.6, -0.8], 4:[0.8, 0.3]} sage: g = Graph({0:[1], 1:[2], 2:[3], 3:[4], 4:[0]}) sage: g.graphplot(pos=pos, layout='spring', iterations=0).plot() Graphics object consisting of 11 graphics primitives sage: G = Graph() sage: P = G.graphplot().plot() sage: P.axes() False sage: G = DiGraph() sage: P = G.graphplot().plot() sage: P.axes() False We can plot multiple graphs:: sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}).plot() Graphics object consisting of 14 graphics primitives :: sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}).plot() Graphics object consisting of 14 graphics primitives sage: t.set_edge_label(0,1,-7) sage: t.set_edge_label(0,5,3) sage: t.set_edge_label(0,5,99) sage: t.set_edge_label(1,2,1000) sage: t.set_edge_label(3,2,'spam') sage: t.set_edge_label(2,6,3/2) sage: t.set_edge_label(0,4,66) sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}, edge_labels=True).plot() Graphics object consisting of 20 graphics primitives :: sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(layout='tree').show() The tree layout is also useful:: sage: t = DiGraph('JCC???@A??GO??CO??GO??') sage: t.graphplot(layout='tree', tree_root=0, tree_orientation="up").show() More examples:: sage: D = DiGraph({0:[1,2,3], 2:[1,4], 3:[0]}) sage: D.graphplot().show() sage: D = DiGraph(multiedges=True, sparse=True) sage: for i in range(5): ... D.add_edge((i,i+1,'a')) ... D.add_edge((i,i-1,'b')) sage: D.graphplot(edge_labels=True,edge_colors=D._color_by_label()).plot() Graphics object consisting of 34 graphics primitives sage: g = Graph({}, loops=True, multiedges=True, sparse=True) sage: g.add_edges([(0,0,'a'),(0,0,'b'),(0,1,'c'),(0,1,'d'), ... (0,1,'e'),(0,1,'f'),(0,1,'f'),(2,1,'g'),(2,2,'h')]) sage: g.graphplot(edge_labels=True, color_by_label=True, edge_style='dashed').plot() Graphics object consisting of 22 graphics primitives The ``edge_style`` option may be provided in the short format too:: sage: g.graphplot(edge_labels=True, color_by_label=True, edge_style='--').plot() Graphics object consisting of 22 graphics primitives TESTS: Make sure that show options work with plot also:: sage: g = Graph({}) sage: g.plot(title='empty graph', axes=True) Graphics object consisting of 0 graphics primitives Check for invalid inputs:: sage: p = graphs.PetersenGraph().plot(egabrag='garbage') Traceback (most recent call last): ... ValueError: Invalid input 'egabrag=garbage' Make sure that no graphics primitive is clipped:: sage: tadpole = Graph({0:[0,1]}).plot() sage: bbox = tadpole.get_minmax_data() sage: for part in tadpole: ....: part_bbox = part.get_minmax_data() ....: assert bbox['xmin'] <= part_bbox['xmin'] <= part_bbox['xmax'] <= bbox['xmax'] ....: assert bbox['ymin'] <= part_bbox['ymin'] <= part_bbox['ymax'] <= bbox['ymax'] """ G = Graphics() options = self._options.copy() options.update(kwds) G._set_extra_kwds(Graphics._extract_kwds_for_show(options)) # Check the arguments for o in options: if o not in graphplot_options and o not in G._extra_kwds: raise ValueError("Invalid input '{}={}'".format(o, options[o])) for comp in self._plot_components.values(): if not isinstance(comp, list): G += comp else: for item in comp: G += item if self._options['graph_border']: xmin = G.xmin() xmax = G.xmax() ymin = G.ymin() ymax = G.ymax() dx = (xmax-xmin)/10.0 dy = (ymax-ymin)/10.0 border = (line([( xmin - dx, ymin - dy), ( xmin - dx, ymax + dy ), ( xmax + dx, ymax + dy ), ( xmax + dx, ymin - dy ), ( xmin - dx, ymin - dy )], thickness=1.3)) border.axes_range(xmin = (xmin - dx), xmax = (xmax + dx), ymin = (ymin - dy), ymax = (ymax + dy)) G += border G.set_aspect_ratio(1) G.axes(False) return G
def plot(self, **kwds): """ Returns a graphics object representing the (di)graph. INPUT: - pos -- an optional positioning dictionary - layout -- what kind of layout to use, takes precedence over pos - 'circular' -- plots the graph with vertices evenly distributed on a circle - 'spring' -- uses the traditional spring layout, using the graph's current positions as initial positions - 'tree' -- the (di)graph must be a tree. One can specify the root of the tree using the keyword tree_root, otherwise a root will be selected at random. Then the tree will be plotted in levels, depending on minimum distance for the root. - vertex_labels -- whether to print vertex labels edge_labels -- whether to print edge labels. By default, False, but if True, the result of str(l) is printed on the edge for each label l. Labels equal to None are not printed (to set edge labels, see set_edge_label). - vertex_size -- size of vertices displayed - vertex_shape -- the shape to draw the vertices (Not available for multiedge digraphs. - graph_border -- whether to include a box around the graph - vertex_colors -- optional dictionary to specify vertex colors: 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). - edge_colors -- a dictionary specifying edge colors: each key is a color recognized by matplotlib, and each entry is a list of edges. - partition -- a partition of the vertex set. if specified, plot will show each cell in a different color. vertex_colors takes precedence. - talk -- if true, prints large vertices with white backgrounds so that labels are legible on slides - iterations -- how many iterations of the spring layout algorithm to go through, if applicable - color_by_label -- if True, color edges by their labels - heights -- if specified, this is a dictionary from a set of floating point heights to a set of vertices - edge_style -- keyword arguments passed into the edge-drawing routine. This currently only works for directed graphs, since we pass off the undirected graph to networkx - tree_root -- 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'. - tree_orientation -- "up" or "down" (default is "down"). If "up" (resp., "down"), then the root of the tree will appear on the bottom (resp., top) and the tree will grow upwards (resp. downwards). Ignored unless layout='tree'. - save_pos -- save position computed during plotting EXAMPLES:: sage: from sage.graphs.graph_plot import graphplot_options sage: list(sorted(graphplot_options.iteritems())) [('by_component', 'Whether to do the spring layout by connected component -- a boolean.'), ('color_by_label', 'Whether or not to color the edges by their label values.'), ('dim', 'The dimension of the layout -- 2 or 3.'), ('dist', 'The distance between multiedges.'), ('edge_color', 'The default color for edges.'), ('edge_colors', 'Dictionary of edge coloring.'), ('edge_labels', 'Whether or not to draw edge labels.'), ('edge_style', 'The linestyle of the edges-- one of "solid", "dashed", "dotted", dashdot".'), ('graph_border', 'Whether or not to draw a frame around the graph.'), ('heights', 'A dictionary mapping heights to the list of vertices at this height.'), ('iterations', 'The number of times to execute the spring layout algorithm.'), ('layout', 'A layout algorithm -- one of "acyclic", "circular", "ranked", "graphviz", "planar", "spring", or "tree".'), ('loop_size', 'The radius of the smallest loop.'), ('max_dist', 'The max distance range to allow multiedges.'), ('partition', 'A partition of the vertex set. (Draws each cell of vertices in a different color).'), ('pos', 'The position dictionary of vertices'), ('prog', 'Which graphviz layout program to use -- one of "circo", "dot", "fdp", "neato", or "twopi".'), ('save_pos', 'Whether or not to save the computed position for the graph.'), ('spring', 'Use spring layout to finalize the current layout.'), ('talk', 'Whether to display the vertices in talk mode (larger and white)'), ('tree_orientation', 'The direction of tree branches -- "up" or "down".'), ('tree_root', 'A vertex designation for drawing trees.'), ('vertex_colors', 'Dictionary of vertex coloring.'), ('vertex_labels', 'Whether or not to draw vertex labels.'), ('vertex_shape', 'The shape to draw the vertices, Currently unavailable for Multi-edged DiGraphs.'), ('vertex_size', 'The size to draw the vertices.')] sage: from math import sin, cos, pi sage: P = graphs.PetersenGraph() sage: d = {'#FF0000':[0,5], '#FF9900':[1,6], '#FFFF00':[2,7], '#00FF00':[3,8], '#0000FF':[4,9]} sage: pos_dict = {} sage: for i in range(5): ... x = float(cos(pi/2 + ((2*pi)/5)*i)) ... y = float(sin(pi/2 + ((2*pi)/5)*i)) ... pos_dict[i] = [x,y] ... sage: for i in range(10)[5:]: ... x = float(0.5*cos(pi/2 + ((2*pi)/5)*i)) ... y = float(0.5*sin(pi/2 + ((2*pi)/5)*i)) ... pos_dict[i] = [x,y] ... sage: pl = P.graphplot(pos=pos_dict, vertex_colors=d) sage: pl.show() sage: C = graphs.CubeGraph(8) sage: P = C.graphplot(vertex_labels=False, vertex_size=0, graph_border=True) sage: P.show() sage: G = graphs.HeawoodGraph().copy(sparse=True) sage: for u,v,l in G.edges(): ... G.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')') sage: G.graphplot(edge_labels=True).show() sage: D = DiGraph( { 0: [1, 10, 19], 1: [8, 2], 2: [3, 6], 3: [19, 4], 4: [17, 5], 5: [6, 15], 6: [7], 7: [8, 14], 8: [9], 9: [10, 13], 10: [11], 11: [12, 18], 12: [16, 13], 13: [14], 14: [15], 15: [16], 16: [17], 17: [18], 18: [19], 19: []}, implementation='networkx' ) sage: for u,v,l in D.edges(): ... D.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')') sage: D.graphplot(edge_labels=True, layout='circular').show() sage: from sage.plot.colors import rainbow sage: C = graphs.CubeGraph(5) sage: R = rainbow(5) sage: edge_colors = {} sage: for i in range(5): ... edge_colors[R[i]] = [] sage: for u,v,l in C.edges(): ... for i in range(5): ... if u[i] != v[i]: ... edge_colors[R[i]].append((u,v,l)) sage: C.graphplot(vertex_labels=False, vertex_size=0, edge_colors=edge_colors).show() sage: D = graphs.DodecahedralGraph() sage: Pi = [[6,5,15,14,7],[16,13,8,2,4],[12,17,9,3,1],[0,19,18,10,11]] sage: D.show(partition=Pi) sage: G = graphs.PetersenGraph() sage: G.allow_loops(True) sage: G.add_edge(0,0) sage: G.show() sage: D = DiGraph({0:[0,1], 1:[2], 2:[3]}, loops=True) sage: D.show() sage: D.show(edge_colors={(0,1,0):[(0,1,None),(1,2,None)],(0,0,0):[(2,3,None)]}) sage: pos = {0:[0.0, 1.5], 1:[-0.8, 0.3], 2:[-0.6, -0.8], 3:[0.6, -0.8], 4:[0.8, 0.3]} sage: g = Graph({0:[1], 1:[2], 2:[3], 3:[4], 4:[0]}) sage: g.graphplot(pos=pos, layout='spring', iterations=0).plot() sage: G = Graph() sage: P = G.graphplot().plot() sage: P.axes() False sage: G = DiGraph() sage: P = G.graphplot().plot() sage: P.axes() False sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}).plot() sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}).plot() sage: t.set_edge_label(0,1,-7) sage: t.set_edge_label(0,5,3) sage: t.set_edge_label(0,5,99) sage: t.set_edge_label(1,2,1000) sage: t.set_edge_label(3,2,'spam') sage: t.set_edge_label(2,6,3/2) sage: t.set_edge_label(0,4,66) sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}, edge_labels=True).plot() sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(layout='tree').show() sage: t = DiGraph('JCC???@A??GO??CO??GO??') sage: t.graphplot(layout='tree', tree_root=0, tree_orientation="up").show() sage: D = DiGraph({0:[1,2,3], 2:[1,4], 3:[0]}) sage: D.graphplot().show() sage: D = DiGraph(multiedges=True, sparse=True) sage: for i in range(5): ... D.add_edge((i,i+1,'a')) ... D.add_edge((i,i-1,'b')) sage: D.graphplot(edge_labels=True,edge_colors=D._color_by_label()).plot() sage: g = Graph({}, loops=True, multiedges=True, sparse=True) sage: g.add_edges([(0,0,'a'),(0,0,'b'),(0,1,'c'),(0,1,'d'), ... (0,1,'e'),(0,1,'f'),(0,1,'f'),(2,1,'g'),(2,2,'h')]) sage: g.graphplot(edge_labels=True, color_by_label=True, edge_style='dashed').plot() """ G = Graphics() for comp in self._plot_components.values(): if not isinstance(comp, list): G += comp else: for item in comp: G += item G.set_axes_range(*(self._graph._layout_bounding_box(self._pos))) if self._options['graph_border']: xmin = G.xmin() xmax = G.xmax() ymin = G.ymin() ymax = G.ymax() dx = (xmax - xmin) / 10.0 dy = (ymax - ymin) / 10.0 border = (line([(xmin - dx, ymin - dy), (xmin - dx, ymax + dy), (xmax + dx, ymax + dy), (xmax + dx, ymin - dy), (xmin - dx, ymin - dy)], thickness=1.3)) border.axes_range(xmin=(xmin - dx), xmax=(xmax + dx), ymin=(ymin - dy), ymax=(ymax + dy)) G += border G.set_aspect_ratio(1) G.axes(False) G._extra_kwds['axes_pad'] = .05 return G
def plot(self, **kwds): """ Returns a graphics object representing the (di)graph. INPUT: The options accepted by this method are to be found in the documentation of the :mod:`sage.graphs.graph_plot` module, and the :meth:`~sage.plot.graphics.Graphics.show` method. .. NOTE:: See :mod:`the module's documentation <sage.graphs.graph_plot>` for information on default values of this method. We can specify some pretty precise plotting of familiar graphs:: sage: from math import sin, cos, pi sage: P = graphs.PetersenGraph() sage: d = {'#FF0000':[0,5], '#FF9900':[1,6], '#FFFF00':[2,7], '#00FF00':[3,8], '#0000FF':[4,9]} sage: pos_dict = {} sage: for i in range(5): ... x = float(cos(pi/2 + ((2*pi)/5)*i)) ... y = float(sin(pi/2 + ((2*pi)/5)*i)) ... pos_dict[i] = [x,y] ... sage: for i in range(10)[5:]: ... x = float(0.5*cos(pi/2 + ((2*pi)/5)*i)) ... y = float(0.5*sin(pi/2 + ((2*pi)/5)*i)) ... pos_dict[i] = [x,y] ... sage: pl = P.graphplot(pos=pos_dict, vertex_colors=d) sage: pl.show() Here are some more common graphs with typical options:: sage: C = graphs.CubeGraph(8) sage: P = C.graphplot(vertex_labels=False, vertex_size=0, graph_border=True) sage: P.show() sage: G = graphs.HeawoodGraph().copy(sparse=True) sage: for u,v,l in G.edges(): ... G.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')') sage: G.graphplot(edge_labels=True).show() The options for plotting also work with directed graphs:: sage: D = DiGraph( { 0: [1, 10, 19], 1: [8, 2], 2: [3, 6], 3: [19, 4], 4: [17, 5], 5: [6, 15], 6: [7], 7: [8, 14], 8: [9], 9: [10, 13], 10: [11], 11: [12, 18], 12: [16, 13], 13: [14], 14: [15], 15: [16], 16: [17], 17: [18], 18: [19], 19: []}) sage: for u,v,l in D.edges(): ... D.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')') sage: D.graphplot(edge_labels=True, layout='circular').show() This example shows off the coloring of edges:: sage: from sage.plot.colors import rainbow sage: C = graphs.CubeGraph(5) sage: R = rainbow(5) sage: edge_colors = {} sage: for i in range(5): ... edge_colors[R[i]] = [] sage: for u,v,l in C.edges(): ... for i in range(5): ... if u[i] != v[i]: ... edge_colors[R[i]].append((u,v,l)) sage: C.graphplot(vertex_labels=False, vertex_size=0, edge_colors=edge_colors).show() With the ``partition`` option, we can separate out same-color groups of vertices:: sage: D = graphs.DodecahedralGraph() sage: Pi = [[6,5,15,14,7],[16,13,8,2,4],[12,17,9,3,1],[0,19,18,10,11]] sage: D.show(partition=Pi) Loops are also plotted correctly:: sage: G = graphs.PetersenGraph() sage: G.allow_loops(True) sage: G.add_edge(0,0) sage: G.show() :: sage: D = DiGraph({0:[0,1], 1:[2], 2:[3]}, loops=True) sage: D.show() sage: D.show(edge_colors={(0,1,0):[(0,1,None),(1,2,None)],(0,0,0):[(2,3,None)]}) More options:: sage: pos = {0:[0.0, 1.5], 1:[-0.8, 0.3], 2:[-0.6, -0.8], 3:[0.6, -0.8], 4:[0.8, 0.3]} sage: g = Graph({0:[1], 1:[2], 2:[3], 3:[4], 4:[0]}) sage: g.graphplot(pos=pos, layout='spring', iterations=0).plot() Graphics object consisting of 11 graphics primitives sage: G = Graph() sage: P = G.graphplot().plot() sage: P.axes() False sage: G = DiGraph() sage: P = G.graphplot().plot() sage: P.axes() False We can plot multiple graphs:: sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}).plot() Graphics object consisting of 14 graphics primitives :: sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}).plot() Graphics object consisting of 14 graphics primitives sage: t.set_edge_label(0,1,-7) sage: t.set_edge_label(0,5,3) sage: t.set_edge_label(0,5,99) sage: t.set_edge_label(1,2,1000) sage: t.set_edge_label(3,2,'spam') sage: t.set_edge_label(2,6,3/2) sage: t.set_edge_label(0,4,66) sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}, edge_labels=True).plot() Graphics object consisting of 20 graphics primitives :: sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(layout='tree').show() The tree layout is also useful:: sage: t = DiGraph('JCC???@A??GO??CO??GO??') sage: t.graphplot(layout='tree', tree_root=0, tree_orientation="up").show() More examples:: sage: D = DiGraph({0:[1,2,3], 2:[1,4], 3:[0]}) sage: D.graphplot().show() sage: D = DiGraph(multiedges=True, sparse=True) sage: for i in range(5): ... D.add_edge((i,i+1,'a')) ... D.add_edge((i,i-1,'b')) sage: D.graphplot(edge_labels=True,edge_colors=D._color_by_label()).plot() Graphics object consisting of 34 graphics primitives sage: g = Graph({}, loops=True, multiedges=True, sparse=True) sage: g.add_edges([(0,0,'a'),(0,0,'b'),(0,1,'c'),(0,1,'d'), ... (0,1,'e'),(0,1,'f'),(0,1,'f'),(2,1,'g'),(2,2,'h')]) sage: g.graphplot(edge_labels=True, color_by_label=True, edge_style='dashed').plot() Graphics object consisting of 22 graphics primitives The ``edge_style`` option may be provided in the short format too:: sage: g.graphplot(edge_labels=True, color_by_label=True, edge_style='--').plot() Graphics object consisting of 22 graphics primitives TESTS: Make sure that show options work with plot also:: sage: g = Graph({}) sage: g.plot(title='empty graph', axes=True) Graphics object consisting of 0 graphics primitives Check for invalid inputs:: sage: p = graphs.PetersenGraph().plot(egabrag='garbage') Traceback (most recent call last): ... ValueError: Invalid input 'egabrag=garbage' Make sure that no graphics primitive is clipped:: sage: tadpole = Graph({0:[0,1]}).plot() sage: bbox = tadpole.get_minmax_data() sage: for part in tadpole: ....: part_bbox = part.get_minmax_data() ....: assert bbox['xmin'] <= part_bbox['xmin'] <= part_bbox['xmax'] <= bbox['xmax'] ....: assert bbox['ymin'] <= part_bbox['ymin'] <= part_bbox['ymax'] <= bbox['ymax'] """ G = Graphics() options = self._options.copy() options.update(kwds) G._set_extra_kwds(Graphics._extract_kwds_for_show(options)) # Check the arguments for o in options: if o not in graphplot_options and o not in G._extra_kwds: raise ValueError("Invalid input '{}={}'".format(o, options[o])) for comp in self._plot_components.values(): if not isinstance(comp, list): G += comp else: for item in comp: G += item if self._options['graph_border']: xmin = G.xmin() xmax = G.xmax() ymin = G.ymin() ymax = G.ymax() dx = (xmax - xmin) / 10.0 dy = (ymax - ymin) / 10.0 border = (line([(xmin - dx, ymin - dy), (xmin - dx, ymax + dy), (xmax + dx, ymax + dy), (xmax + dx, ymin - dy), (xmin - dx, ymin - dy)], thickness=1.3)) border.axes_range(xmin=(xmin - dx), xmax=(xmax + dx), ymin=(ymin - dy), ymax=(ymax + dy)) G += border G.set_aspect_ratio(1) G.axes(False) return G
def draw_funddom_d(coset_reps, format="MP", z0=I, verbose=0): r""" Draw a fundamental domain for self in the circle model INPUT: - ''format'' -- (default 'Disp') How to present the f.d. = 'S' -- Display directly on the screen - z0 -- (default I) the upper-half plane is mapped to the disk by z-->(z-z0)/(z-z0.conjugate()) EXAMPLES:: sage: G=MySubgroup(Gamma0(3)) sage: G._draw_funddom_d() """ # The fundamental domain consists of copies of the standard fundamental domain pi = RR.pi() from sage.plot.plot import (Graphics, line) g = Graphics() bdcirc = _circ_arc(0, 2 * pi, 0, 1, 1000) g = g + bdcirc # Corners x1 = -RR(0.5) y1 = RR(sqrt(3) / 2) x2 = RR(0.5) y2 = RR(sqrt(3) / 2) z_inf = 1 l1 = _geodesic_between_two_points_d(x1, y1, x1, infinity) l2 = _geodesic_between_two_points_d(x2, y2, x2, infinity) c0 = _geodesic_between_two_points_d(x1, y1, x2, y2) tri = c0 + l1 + l2 g = g + tri for A in coset_reps: a, b, c, d = A if a == 1 and b == 0 and c == 0 and d == 1: continue if a < 0: a = -a b = -b c = -c d = -d if verbose > 0: print "a,b,c,d=", a, b, c, d if c == 0: # then this is easier l1 = _geodesic_between_two_points_d(x1 + b, y1, x1 + b, infinity) l2 = _geodesic_between_two_points_d(x2 + b, y2, x2 + b, infinity) c0 = _geodesic_between_two_points_d(x1 + b, y1, x2 + b, y2) # c0=line(L0); l1=line(L1); l2=line(L2); l3=line(L3) tri = c0 + l1 + l2 g = g + tri else: den = (c * x1 + d)**2 + c**2 * y1**2 x1_t = (a * c * (x1**2 + y1**2) + (a * d + b * c) * x1 + b * d) / den y1_t = y1 / den den = (c * x2 + d)**2 + c**2 * y2**2 x2_t = (a * c * (x2**2 + y2**2) + (a * d + b * c) * x2 + b * d) / den y2_t = y2 / den inf_t = a / c if verbose > 0: print "x1_t=", x1_t print "y1_t=", y1_t print "x2_t=", x2_t print "y2_t=", y2_t print "inf_t=", inf_t c0 = _geodesic_between_two_points_d(x1_t, y1_t, x2_t, y2_t) c1 = _geodesic_between_two_points_d(x1_t, y1_t, inf_t, 1.0) c2 = _geodesic_between_two_points_d(x2_t, y2_t, inf_t, 1.0) tri = c0 + c1 + c2 g = g + tri g.xmax(1) g.ymax(1) g.xmin(-1) g.ymin(-1) g.set_aspect_ratio(1) return g
def hyperbolic_regular_polygon(sides, i_angle, center=CC(0,1), **options): r""" Return a hyperbolic regular polygon in the upper half model of Hyperbolic plane given the number of sides, interior angle and possibly a center. Type ``?hyperbolic_regular_polygon`` to see all options. INPUT: - ``sides`` -- number of sides of the polygon - ``i_angle`` -- interior angle of the polygon - ``center`` -- (default: `i`) hyperbolic center point (complex number) of the polygon OPTIONS: - ``alpha`` -- default: 1 - ``fill`` -- default: ``False`` - ``thickness`` -- default: 1 - ``rgbcolor`` -- default: ``'blue'`` - ``linestyle`` -- (default: ``'solid'``) the style of the line, which can be one of the following: * ``'dashed'`` or ``'--'`` * ``'dotted'`` or ``':'`` * ``'solid'`` or ``'-'`` * ``'dashdot'`` or ``'-.'`` EXAMPLES: Show a hyperbolic regular polygon with 6 sides and square angles:: sage: g = hyperbolic_regular_polygon(6, pi/2) sage: g.plot() Graphics object consisting of 1 graphics primitive .. PLOT:: g = hyperbolic_regular_polygon(6, pi/2) sphinx_plot(g.plot()) With more options:: sage: g = hyperbolic_regular_polygon(6, pi/2, center=3+2*I, fill=True, color='red') sage: g.plot() Graphics object consisting of 1 graphics primitive .. PLOT:: g = hyperbolic_regular_polygon(6, pi/2, center=3+2*I, fill=True, color='red') sphinx_plot(g.plot()) The code verifies is there exists a hyperbolic regular polygon with the given data, checking .. MATH:: A(\mathcal{P}) = \pi(s-2) - s \cdot \alpha > 0, where `s` is ``sides`` and `\alpha` is ``i_angle`. This raises an error if the ``i_angle`` is less than the minimum to generate a compact polygon:: sage: hyperbolic_regular_polygon(4, pi/2) Traceback (most recent call last): ... ValueError: there exists no hyperbolic regular compact polygon, for sides=4 the interior angle must be less than 1/2*pi It is an error to give a center outside the upper half plane in this model:: sage: from sage.plot.hyperbolic_regular_polygon import hyperbolic_regular_polygon sage: hyperbolic_regular_polygon(4, pi/4, 1-I) Traceback (most recent call last): ... ValueError: center: 1.00000000000000 - 1.00000000000000*I is not a valid point in the upper half plane model of the hyperbolic plane """ g = Graphics() g._set_extra_kwds(g._extract_kwds_for_show(options)) g.add_primitive(HyperbolicRegularPolygon(sides, i_angle, center, options)) g.set_aspect_ratio(1) return g
def plot(self, size=[[0],[0]], projection='usual', simple_roots=True, fundamental_weights=True, alcovewalks=[]): r""" Return a graphics object built from a space of weight(space/lattice). There is a different technic to plot if the Cartan type is affine or not. The graphics returned is a Graphics object. This function is experimental, and is subject to short term evolutions. EXAMPLES:: By default, the plot returned has no axes and the ratio between axes is 1. sage: G = RootSystem(['C',2]).weight_lattice().plot() sage: G.axes(True) sage: G.set_aspect_ratio(2) For a non affine Cartan type, the plot method work for type with 2 generators, it will draw the hyperlane(line for this dimension) accrow the fundamentals weights. sage: G = RootSystem(['A',2]).weight_lattice().plot() sage: G = RootSystem(['B',2]).weight_lattice().plot() sage: G = RootSystem(['G',2]).weight_lattice().plot() The plot returned has a size of one fundamental polygon by default. We can ask plot to give a bigger plot by using the argument size sage: G = RootSystem(['G',2,1]).weight_space().plot(size = [[0..1],[-1..1]]) sage: G = RootSystem(['A',2,1]).weight_space().plot(size = [[-1..1],[-1..1]]) A very important argument is the projection which will draw the plot. There are some usual projections is this method. If you want to draw in the plane a very special Cartan type, Sage will ask you to specify the projection. The projection is a matrix over a ring. In practice, calcul over float is a good way to draw. sage: L = RootSystem(['A',2,1]).weight_space() sage: G = L.plot(projection=matrix(RR, [[0,0.5,-0.5],[0,0.866,0.866]])) sage: G = RootSystem(['C',2,1]).weight_space().plot() By default, the plot method draw the simple roots, this can be disabled by setting the argument simple_roots=False sage: G = RootSystem(['A',2]).weight_space().plot(simple_roots=False) By default, the plot method draw the fundamental weights,this can be disabled by setting the argument fundamental_weights=False sage: G = RootSystem(['A',2]).weight_space().plot(fundamental_weights=False, simple_roots=False) There is in a plot an argument to draw alcoves walks. The good way to do this is to use the crystals theory. the plot method contains only the drawing part... sage: L = RootSystem(['A',2,1]).weight_space() sage: G = L.plot(size=[[-1..1],[-1..1]],alcovewalks=[[0,2,0,1,2,1,2,0,2,1]]) """ from sage.plot.all import Graphics from sage.plot.line import line from cartan_type import CartanType from sage.matrix.constructor import matrix from sage.rings.all import QQ, RR from sage.plot.arrow import arrow from sage.plot.point import point # We begin with an empty plot G G = Graphics() ct = self.cartan_type() n = ct.n # Define a set of colors # TODO : Colors in option ? colors=[(0,1,0),(1,0,0),(0,0,1),(1,1,0),(0,1,1),(1,0,1)] # plot the affine types: if ct.is_affine(): # Check the projection # TODO : try to have usual_projection for main plotable types if projection == 'usual': if ct == CartanType(['A',2,1]): projection = matrix(RR, [[0,0.5,-0.5],[0,0.866,0.866]]) elif ct == CartanType(['C',2,1]): projection = matrix(QQ, [[0,1,1],[0,0,1]]) elif ct == CartanType(['G',2,1]): projection = matrix(RR, [[0,0.5,0],[0,0.866,1.732]]) else: raise 'There is no usual projection for this Cartan type, you have to give one in argument' assert(n + 1 == projection.ncols()) assert(2 == projection.nrows()) # Check the size is correct with the lattice assert(len(size) == n) # Select the center of the translated fundamental polygon to plot translation_factors = ct.translation_factors() simple_roots = self.simple_roots() translation_vectors = [translation_factors[i]*simple_roots[i] for i in ct.classical().index_set()] initial = [[]] for i in range(n): prod_list = [] for elem in size[i]: for partial_list in initial: prod_list.append( [elem]+partial_list ); initial = prod_list; part_lattice = [] for combinaison in prod_list: elem_lattice = self.zero() for i in range(n): elem_lattice = elem_lattice + combinaison[i]*translation_vectors[i] part_lattice.append(elem_lattice) # Get the vertices of the fundamental alcove fundamental_weights = self.fundamental_weights() vertices = map(lambda x: (1/x.level())*x, fundamental_weights.list()) # Recup the group which act on the fundamental polygon classical = self.weyl_group().classical() for center in part_lattice: for w in classical: # for each center of polygon and each element of classical # parabolic subgroup, we have to draw an alcove. #first, iterate over pairs of fundamental weights, drawing lines border of polygons: for i in range(1,n+1): for j in range(i+1,n+1): p1=projection*((w.action(vertices[i])).to_vector() + center.to_vector()) p2=projection*((w.action(vertices[j])).to_vector() + center.to_vector()) G+=line([p1,p2],rgbcolor=(0,0,0),thickness=2) #next, get all lines from point to a fundamental weight, that separe different #chanber in a same polygon (important: associate a color with a fundamental weight) pcenter = projection*(center.to_vector()) for i in range(1,n+1): p3=projection*((w.action(vertices[i])).to_vector() + center.to_vector()) G+=line([p3,pcenter], rgbcolor=colors[n-i+1]) #Draw alcovewalks #FIXME : The good way to draw this is to use the alcoves walks works made in Cristals #The code here just draw like example and import the good things. rho = (1/self.rho().level())*self.rho() W = self.weyl_group() for walk in alcovewalks: target = W.from_reduced_word(walk).action(rho) for i in range(len(walk)): walk.pop() origin = W.from_reduced_word(walk).action(rho) G+=arrow(projection*(origin.to_vector()),projection*(target.to_vector()), rgbcolor=(0.6,0,0.6), width=1, arrowsize=5) target = origin else: # non affine plot # Check the projection # TODO : try to have usual_projection for main plotable types if projection == 'usual': if ct == CartanType(['A',2]): projection = matrix(RR, [[0.5,-0.5],[0.866,0.866]]) elif ct == CartanType(['B',2]): projection = matrix(QQ, [[1,0],[1,1]]) elif ct == CartanType(['C',2]): projection = matrix(QQ, [[1,1],[0,1]]) elif ct == CartanType(['G',2]): projection = matrix(RR, [[0.5,0],[0.866,1.732]]) else: raise 'There is no usual projection for this Cartan type, you have to give one in argument' # Get the fundamental weights fundamental_weights = self.fundamental_weights() WeylGroup = self.weyl_group() #Draw not the alcove but the cones delimited by the hyperplanes #The size of the line depend of the fundamental weights. pcenter = projection*(self.zero().to_vector()) for w in WeylGroup: for i in range(1,n+1): p3=3*projection*((w.action(fundamental_weights[i])).to_vector()) G+=line([p3,pcenter], rgbcolor=colors[n-i+1]) #Draw the simple roots if simple_roots: SimpleRoots = self.simple_roots() if ct.is_affine(): G+=arrow((0,0), projection*(SimpleRoots[0].to_vector()), rgbcolor=(0,0,0)) for j in range(1,n+1): G+=arrow((0,0),projection*(SimpleRoots[j].to_vector()), rgbcolor=colors[j]) #Draw the fundamental weights if fundamental_weights: FundWeight = self.fundamental_weights() for j in range(1,n+1): G+=point(projection*(FundWeight[j].to_vector()), rgbcolor=colors[j], pointsize=60) G.set_aspect_ratio(1) G.axes(False) return G
def plot(self, size=[[0], [0]], projection='usual', simple_roots=True, fundamental_weights=True, alcovewalks=[]): r""" Return a graphics object built from a space of weight(space/lattice). There is a different technic to plot if the Cartan type is affine or not. The graphics returned is a Graphics object. This function is experimental, and is subject to short term evolutions. EXAMPLES:: By default, the plot returned has no axes and the ratio between axes is 1. sage: G = RootSystem(['C',2]).weight_lattice().plot() sage: G.axes(True) sage: G.set_aspect_ratio(2) For a non affine Cartan type, the plot method work for type with 2 generators, it will draw the hyperlane(line for this dimension) accrow the fundamentals weights. sage: G = RootSystem(['A',2]).weight_lattice().plot() sage: G = RootSystem(['B',2]).weight_lattice().plot() sage: G = RootSystem(['G',2]).weight_lattice().plot() The plot returned has a size of one fundamental polygon by default. We can ask plot to give a bigger plot by using the argument size sage: G = RootSystem(['G',2,1]).weight_space().plot(size = [[0..1],[-1..1]]) sage: G = RootSystem(['A',2,1]).weight_space().plot(size = [[-1..1],[-1..1]]) A very important argument is the projection which will draw the plot. There are some usual projections is this method. If you want to draw in the plane a very special Cartan type, Sage will ask you to specify the projection. The projection is a matrix over a ring. In practice, calcul over float is a good way to draw. sage: L = RootSystem(['A',2,1]).weight_space() sage: G = L.plot(projection=matrix(RR, [[0,0.5,-0.5],[0,0.866,0.866]])) sage: G = RootSystem(['C',2,1]).weight_space().plot() By default, the plot method draw the simple roots, this can be disabled by setting the argument simple_roots=False sage: G = RootSystem(['A',2]).weight_space().plot(simple_roots=False) By default, the plot method draw the fundamental weights,this can be disabled by setting the argument fundamental_weights=False sage: G = RootSystem(['A',2]).weight_space().plot(fundamental_weights=False, simple_roots=False) There is in a plot an argument to draw alcoves walks. The good way to do this is to use the crystals theory. the plot method contains only the drawing part... sage: L = RootSystem(['A',2,1]).weight_space() sage: G = L.plot(size=[[-1..1],[-1..1]],alcovewalks=[[0,2,0,1,2,1,2,0,2,1]]) """ from sage.plot.all import Graphics from sage.plot.line import line from cartan_type import CartanType from sage.matrix.constructor import matrix from sage.rings.all import QQ, RR from sage.plot.arrow import arrow from sage.plot.point import point # We begin with an empty plot G G = Graphics() ct = self.cartan_type() n = ct.n # Define a set of colors # TODO : Colors in option ? colors = [(0, 1, 0), (1, 0, 0), (0, 0, 1), (1, 1, 0), (0, 1, 1), (1, 0, 1)] # plot the affine types: if ct.is_affine(): # Check the projection # TODO : try to have usual_projection for main plotable types if projection == 'usual': if ct == CartanType(['A', 2, 1]): projection = matrix( RR, [[0, 0.5, -0.5], [0, 0.866, 0.866]]) elif ct == CartanType(['C', 2, 1]): projection = matrix(QQ, [[0, 1, 1], [0, 0, 1]]) elif ct == CartanType(['G', 2, 1]): projection = matrix(RR, [[0, 0.5, 0], [0, 0.866, 1.732]]) else: raise 'There is no usual projection for this Cartan type, you have to give one in argument' assert (n + 1 == projection.ncols()) assert (2 == projection.nrows()) # Check the size is correct with the lattice assert (len(size) == n) # Select the center of the translated fundamental polygon to plot translation_factors = ct.translation_factors() simple_roots = self.simple_roots() translation_vectors = [ translation_factors[i] * simple_roots[i] for i in ct.classical().index_set() ] initial = [[]] for i in range(n): prod_list = [] for elem in size[i]: for partial_list in initial: prod_list.append([elem] + partial_list) initial = prod_list part_lattice = [] for combinaison in prod_list: elem_lattice = self.zero() for i in range(n): elem_lattice = elem_lattice + combinaison[ i] * translation_vectors[i] part_lattice.append(elem_lattice) # Get the vertices of the fundamental alcove fundamental_weights = self.fundamental_weights() vertices = map(lambda x: (1 / x.level()) * x, fundamental_weights.list()) # Recup the group which act on the fundamental polygon classical = self.weyl_group().classical() for center in part_lattice: for w in classical: # for each center of polygon and each element of classical # parabolic subgroup, we have to draw an alcove. #first, iterate over pairs of fundamental weights, drawing lines border of polygons: for i in range(1, n + 1): for j in range(i + 1, n + 1): p1 = projection * ( (w.action(vertices[i])).to_vector() + center.to_vector()) p2 = projection * ( (w.action(vertices[j])).to_vector() + center.to_vector()) G += line([p1, p2], rgbcolor=(0, 0, 0), thickness=2) #next, get all lines from point to a fundamental weight, that separe different #chanber in a same polygon (important: associate a color with a fundamental weight) pcenter = projection * (center.to_vector()) for i in range(1, n + 1): p3 = projection * ( (w.action(vertices[i])).to_vector() + center.to_vector()) G += line([p3, pcenter], rgbcolor=colors[n - i + 1]) #Draw alcovewalks #FIXME : The good way to draw this is to use the alcoves walks works made in Cristals #The code here just draw like example and import the good things. rho = (1 / self.rho().level()) * self.rho() W = self.weyl_group() for walk in alcovewalks: target = W.from_reduced_word(walk).action(rho) for i in range(len(walk)): walk.pop() origin = W.from_reduced_word(walk).action(rho) G += arrow(projection * (origin.to_vector()), projection * (target.to_vector()), rgbcolor=(0.6, 0, 0.6), width=1, arrowsize=5) target = origin else: # non affine plot # Check the projection # TODO : try to have usual_projection for main plotable types if projection == 'usual': if ct == CartanType(['A', 2]): projection = matrix(RR, [[0.5, -0.5], [0.866, 0.866]]) elif ct == CartanType(['B', 2]): projection = matrix(QQ, [[1, 0], [1, 1]]) elif ct == CartanType(['C', 2]): projection = matrix(QQ, [[1, 1], [0, 1]]) elif ct == CartanType(['G', 2]): projection = matrix(RR, [[0.5, 0], [0.866, 1.732]]) else: raise 'There is no usual projection for this Cartan type, you have to give one in argument' # Get the fundamental weights fundamental_weights = self.fundamental_weights() WeylGroup = self.weyl_group() #Draw not the alcove but the cones delimited by the hyperplanes #The size of the line depend of the fundamental weights. pcenter = projection * (self.zero().to_vector()) for w in WeylGroup: for i in range(1, n + 1): p3 = 3 * projection * ( (w.action(fundamental_weights[i])).to_vector()) G += line([p3, pcenter], rgbcolor=colors[n - i + 1]) #Draw the simple roots if simple_roots: SimpleRoots = self.simple_roots() if ct.is_affine(): G += arrow((0, 0), projection * (SimpleRoots[0].to_vector()), rgbcolor=(0, 0, 0)) for j in range(1, n + 1): G += arrow((0, 0), projection * (SimpleRoots[j].to_vector()), rgbcolor=colors[j]) #Draw the fundamental weights if fundamental_weights: FundWeight = self.fundamental_weights() for j in range(1, n + 1): G += point(projection * (FundWeight[j].to_vector()), rgbcolor=colors[j], pointsize=60) G.set_aspect_ratio(1) G.axes(False) return G
def plot(self, **kwds): """ Returns a graphics object representing the (di)graph. INPUT: The options accepted by this method are to be found in the documentation of module :mod:`sage.graphs.graph_plot`. .. NOTE:: See :mod:`the module's documentation <sage.graphs.graph_plot>` for information on default values of this method. We can specify some pretty precise plotting of familiar graphs:: sage: from math import sin, cos, pi sage: P = graphs.PetersenGraph() sage: d = {'#FF0000':[0,5], '#FF9900':[1,6], '#FFFF00':[2,7], '#00FF00':[3,8], '#0000FF':[4,9]} sage: pos_dict = {} sage: for i in range(5): ... x = float(cos(pi/2 + ((2*pi)/5)*i)) ... y = float(sin(pi/2 + ((2*pi)/5)*i)) ... pos_dict[i] = [x,y] ... sage: for i in range(10)[5:]: ... x = float(0.5*cos(pi/2 + ((2*pi)/5)*i)) ... y = float(0.5*sin(pi/2 + ((2*pi)/5)*i)) ... pos_dict[i] = [x,y] ... sage: pl = P.graphplot(pos=pos_dict, vertex_colors=d) sage: pl.show() Here are some more common graphs with typical options:: sage: C = graphs.CubeGraph(8) sage: P = C.graphplot(vertex_labels=False, vertex_size=0, graph_border=True) sage: P.show() sage: G = graphs.HeawoodGraph().copy(sparse=True) sage: for u,v,l in G.edges(): ... G.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')') sage: G.graphplot(edge_labels=True).show() The options for plotting also work with directed graphs:: sage: D = DiGraph( { 0: [1, 10, 19], 1: [8, 2], 2: [3, 6], 3: [19, 4], 4: [17, 5], 5: [6, 15], 6: [7], 7: [8, 14], 8: [9], 9: [10, 13], 10: [11], 11: [12, 18], 12: [16, 13], 13: [14], 14: [15], 15: [16], 16: [17], 17: [18], 18: [19], 19: []}, implementation='networkx' ) sage: for u,v,l in D.edges(): ... D.set_edge_label(u,v,'(' + str(u) + ',' + str(v) + ')') sage: D.graphplot(edge_labels=True, layout='circular').show() This example shows off the coloring of edges:: sage: from sage.plot.colors import rainbow sage: C = graphs.CubeGraph(5) sage: R = rainbow(5) sage: edge_colors = {} sage: for i in range(5): ... edge_colors[R[i]] = [] sage: for u,v,l in C.edges(): ... for i in range(5): ... if u[i] != v[i]: ... edge_colors[R[i]].append((u,v,l)) sage: C.graphplot(vertex_labels=False, vertex_size=0, edge_colors=edge_colors).show() With the ``partition`` option, we can separate out same-color groups of vertices:: sage: D = graphs.DodecahedralGraph() sage: Pi = [[6,5,15,14,7],[16,13,8,2,4],[12,17,9,3,1],[0,19,18,10,11]] sage: D.show(partition=Pi) Loops are also plotted correctly:: sage: G = graphs.PetersenGraph() sage: G.allow_loops(True) sage: G.add_edge(0,0) sage: G.show() :: sage: D = DiGraph({0:[0,1], 1:[2], 2:[3]}, loops=True) sage: D.show() sage: D.show(edge_colors={(0,1,0):[(0,1,None),(1,2,None)],(0,0,0):[(2,3,None)]}) More options:: sage: pos = {0:[0.0, 1.5], 1:[-0.8, 0.3], 2:[-0.6, -0.8], 3:[0.6, -0.8], 4:[0.8, 0.3]} sage: g = Graph({0:[1], 1:[2], 2:[3], 3:[4], 4:[0]}) sage: g.graphplot(pos=pos, layout='spring', iterations=0).plot() sage: G = Graph() sage: P = G.graphplot().plot() sage: P.axes() False sage: G = DiGraph() sage: P = G.graphplot().plot() sage: P.axes() False We can plot multiple graphs:: sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}).plot() :: sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}).plot() sage: t.set_edge_label(0,1,-7) sage: t.set_edge_label(0,5,3) sage: t.set_edge_label(0,5,99) sage: t.set_edge_label(1,2,1000) sage: t.set_edge_label(3,2,'spam') sage: t.set_edge_label(2,6,3/2) sage: t.set_edge_label(0,4,66) sage: t.graphplot(heights={0:[0], 1:[4,5,1], 2:[2], 3:[3,6]}, edge_labels=True).plot() :: sage: T = list(graphs.trees(7)) sage: t = T[3] sage: t.graphplot(layout='tree').show() The tree layout is also useful:: sage: t = DiGraph('JCC???@A??GO??CO??GO??') sage: t.graphplot(layout='tree', tree_root=0, tree_orientation="up").show() More examples:: sage: D = DiGraph({0:[1,2,3], 2:[1,4], 3:[0]}) sage: D.graphplot().show() sage: D = DiGraph(multiedges=True, sparse=True) sage: for i in range(5): ... D.add_edge((i,i+1,'a')) ... D.add_edge((i,i-1,'b')) sage: D.graphplot(edge_labels=True,edge_colors=D._color_by_label()).plot() sage: g = Graph({}, loops=True, multiedges=True, sparse=True) sage: g.add_edges([(0,0,'a'),(0,0,'b'),(0,1,'c'),(0,1,'d'), ... (0,1,'e'),(0,1,'f'),(0,1,'f'),(2,1,'g'),(2,2,'h')]) sage: g.graphplot(edge_labels=True, color_by_label=True, edge_style='dashed').plot() Wrong input (any input) :trac:`13891`:: sage: graphs.PetersenGraph().graphplot().plot(aertataert=346345345) doctest:...: DeprecationWarning: This method takes no argument ! You may want to give it as an argument to graphplot instead. See http://trac.sagemath.org/13891 for details. <BLANKLINE> """ # This method takes NO input # This has been added in early 2013. Remove it before my death, please. if kwds: from sage.misc.superseded import deprecation deprecation( 13891, "This method takes no argument ! You may want " "to give it as an argument to graphplot instead.") G = Graphics() for comp in self._plot_components.values(): if not isinstance(comp, list): G += comp else: for item in comp: G += item G.set_axes_range(*(self._graph._layout_bounding_box(self._pos))) if self._options['graph_border']: xmin = G.xmin() xmax = G.xmax() ymin = G.ymin() ymax = G.ymax() dx = (xmax - xmin) / 10.0 dy = (ymax - ymin) / 10.0 border = (line([(xmin - dx, ymin - dy), (xmin - dx, ymax + dy), (xmax + dx, ymax + dy), (xmax + dx, ymin - dy), (xmin - dx, ymin - dy)], thickness=1.3)) border.axes_range(xmin=(xmin - dx), xmax=(xmax + dx), ymin=(ymin - dy), ymax=(ymax + dy)) G += border G.set_aspect_ratio(1) G.axes(False) G._extra_kwds['axes_pad'] = .05 return G