Sharedworksheet.sagewsOpen in CoCalc
Display E_6 associahedron skeleton
%attach graphe-dechange.sage
%attach interessant.sage
show(H,vertex_labels=false, width =1600, height=1000, charge=-40, link_distance=50,edge_partition=exp)
d3-based renderer not yet implemented
Output too long: 327364 -- MAX_OUTPUT (=150000) exceeded (type 'smc?' to learn how to raise this limit): attempting to terminate...
   File: /cocalc/lib/python2.7/site-packages/smc_sagews/
   def show(*objs, **kwds):
    Show a 2d or 3d graphics object (or objects), animation, or matplotlib figure, or show an
    expression typeset nicely using LaTeX.

       - display: (default: True); if True, use display math for expression (big and centered).

       - svg: (default: True); if True, show 2d plots using svg (otherwise use png)

       - d3: (default: True); if True, show graphs (vertices and edges) using an interactive D3 viewer
         for the many options for this viewer, type


         If false, graphs are converted to plots and displayed as usual.

       - renderer: (default: 'webgl'); for 3d graphics
           - 'webgl' (fastest) using hardware accelerated 3d;
           - 'canvas' (slower) using a 2d canvas, but may work better with transparency;
           - 'tachyon' -- a ray traced static image.

       - spin: (default: False); spins 3d plot, with number determining speed (requires mouse over plot)

       - events: if given, {'click':foo, 'mousemove':bar}; each time the user clicks,
         the function foo is called with a 2-tuple (x,y) where they clicked.  Similarly
         for mousemove.  This works for Sage 2d graphics and matplotlib figures.

       - viewer: optional string, set to "tachyon" for static ray-tracing view of 3d image

       - background: string (default: 'transparent'), specifies background color for 3d images.
         Ignored if viewer is set to 'tachyon' or if object type is Tachyon.
         May be 'transparent' or any valid CSS color string, e.g.: 'red', '#00ff00', 'rgb(0,0,255)'.

       - foreground: string, specifies frame color for 3d images. Defaults to 'gray' when
         background is 'transparent', otherwise default is computed for visibility based on canvas


       - animations are by default encoded and displayed using an efficiently web-friendly
         format (currently webm, which is **not supported** by Safari or IE).

            - ``delay`` - integer (default: 20); delay in hundredths of a
              second between frames.

            - gif=False -- if you set gif=True, instead use an animated gif,
              which is much less efficient, but works on all browsers.

         You can also use options directly to the animate command, e.g., the figsize option below:

              a = animate([plot(sin(x + a), (x, 0, 2*pi)) for a in [0, pi/4, .., 2*pi]], figsize=6)
              show(a, delay=30)


    Some examples:

        show([1, 4/5, pi^2 + e], 1+pi)
        show(x^2, display=False)
        show(e, plot(sin))

    Here's an example that illustrates creating a clickable image with events::

        def f0(fun=x*sin(x^2), mousemove='', click='(0,0)'):
            click = sage_eval(click)
            g = plot(fun, (x,0,5), zorder=0) + point(click, color='red', pointsize=100, zorder=10)
            ymax = g.ymax(); ymin = g.ymin()
            m = fun.derivative(x)(x=click[0])
            b =  fun(x=click[0]) - m*click[0]
            g += plot(m*x + b, (click[0]-1,click[0]+1), color='red', zorder=10)
            def h(p):
                f0.mousemove = p
            def c(p):
            show(g, events={'click':c, 'mousemove':h}, svg=True, gridlines='major', ymin=ymin, ymax=ymax)
    # svg=True, d3=True,
    svg = kwds.get('svg',True)
    d3 = kwds.get('d3',True)
    display = kwds.get('display', True)
    for t in ['svg', 'd3', 'display']:
        if t in kwds:
            del kwds[t]
    import graphics
    def show0(obj, combine_all=False):
        # Either show the object and return None or
        # return a string of html to represent obj.
        if isinstance(obj, (Graphics, GraphicsArray, matplotlib.figure.Figure, matplotlib.axes.Axes, matplotlib.image.AxesImage)):
            show_2d_plot_using_matplotlib(obj, svg=svg, **kwds)
        elif isinstance(obj, Animation):
            show_animation(obj, **kwds)
        elif isinstance(obj, Graphics3d):

            # _extra_kwds processing follows the example of
            # src/smc_sagews/smc_sagews/
            extra_kwds = {} if obj._extra_kwds is None else obj._extra_kwds
            for k in ['spin', 'renderer', 'viewer', 'frame', 'height', 'width', 'background', 'foreground', 'aspect_ratio']:
                if k in extra_kwds and k not in kwds:
                    kwds[k] = obj._extra_kwds[k]

            if kwds.get('viewer') == 'tachyon':
                show_3d_plot_using_tachyon(obj, **kwds)
                salvus.threed(obj, **kwds)
                # graphics.show_3d_plot_using_threejs(obj, **kwds)
        elif isinstance(obj, Tachyon):
            show_3d_plot_using_tachyon(obj, **kwds)
        elif isinstance(obj, (sage.graphs.graph.Graph, sage.graphs.digraph.DiGraph)):
            if d3:
                show_graph_using_d3(obj, **kwds)
                show(obj.plot(), **kwds)
        elif isinstance(obj, str):
            return obj
        elif isinstance(obj, (list, tuple)):
            v = []
            for a in obj:
                b = show0(a)
                if b is not None:
            if combine_all:
                return ' '.join(v)
            s = ', '.join(v)
            if isinstance(obj, list):
                return '[%s]'%s
                return '(%s)'%s
        elif is_dataframe(obj):
            html(obj.to_html(), hide=False)
            s = str(sage.misc.latex.latex(obj))
            if r'\text{\texttt' in s and 'tikzpicture' not in s:
                # In this case the mathjax latex mess is so bad, it is better to just print and give up!
            # Add anything here that Sage produces and mathjax can't handle, and
            # which people complain about... (obviously, I wish there were a way to
            # know -- e.g., if Sage had a way to tell whether latex it produces
            # will work with mathjax or not).
            if '\\begin{tikzpicture}' in s or '\\raisebox' in s:
                # special case -- mathjax has no support for tikz or \raisebox so we just immediately display it (as a png); this is
                # better than nothing.
                return ''
            elif r'\begin{tabular}' in s:
                # tabular is an environment for text, not formular.
                # Sage's `tabular` should actually use \array!
                return ''
            # default
            elif display:
                return "$\\displaystyle %s$"%s
                return "$%s$"%s
    s = show0(objs, combine_all=True)
    if s is not None:
        if len(s) > 0:
            if display:
                salvus.html("<div align='center'>%s</div>"%cgi.escape(s))
Docstring :

   File: /cocalc/lib/python2.7/site-packages/smc_sagews/
   def graph_to_d3_jsonable(G,
      vertex_labels       = True,
      edge_labels         = False,
      vertex_partition    = [],
      edge_partition      = [],
      force_spring_layout = False,
      charge              = -120,
      link_distance       = 50,
      link_strength       = 1,
      gravity             = .04,
      vertex_size         = 7,
      edge_thickness      = 2,
      width               = None,
      height              = None,
    Display a graph in CoCalc using the D3 visualization library.


    - ``G`` -- the graph

    - ``vertex_labels`` (boolean) -- Whether to display vertex labels (set to
      ``True`` by default).

    - ``edge_labels`` (boolean) -- Whether to display edge labels (set to
      ``False`` by default).

    - ``vertex_partition`` -- a list of lists representing a partition of the
      vertex set. Vertices are then colored in the graph according to the
      partition. Set to ``[]`` by default.

    - ``edge_partition`` -- same as ``vertex_partition``, with edges
      instead. Set to ``[]`` by default.

    - ``force_spring_layout`` -- whether to take sage's position into account if
      there is one (see :meth:`~sage.graphs.generic_graph.GenericGraph.` and
      :meth:`~sage.graphs.generic_graph.GenericGraph.`), or to compute a spring
      layout. Set to ``False`` by default.

    - ``vertex_size`` -- The size of a vertex' circle. Set to `7` by default.

    - ``edge_thickness`` -- Thickness of an edge. Set to ``2`` by default.

    - ``charge`` -- the vertices' charge. Defines how they repulse each
      other. See `<>`_ for more
      information. Set to ``-120`` by default.

    - ``link_distance`` -- See
      `<>`_ for more
      information. Set to ``30`` by default.

    - ``link_strength`` -- See
      `<>`_ for more
      information. Set to ``1.5`` by default.

    - ``gravity`` -- See
      `<>`_ for more
      information. Set to ``0.04`` by default.


        show(graphs.RandomTree(50), d3=True)

        show(graphs.PetersenGraph(), d3=True, vertex_partition=g.coloring())

        show(graphs.DodecahedralGraph(), d3=True, force_spring_layout=True)

        show(graphs.DodecahedralGraph(), d3=True)

        g = digraphs.DeBruijn(2,2)
        show(g, d3=True, vertex_labels=True,edge_labels=True,

    directed = G.is_directed()
    multiple_edges = G.has_multiple_edges()

    # Associated an integer to each vertex
    v_to_id = {v: i for i, v in enumerate(G.vertices())}

    # Vertex colors
    color = {i: len(vertex_partition) for i in range(G.order())}
    for i, l in enumerate(vertex_partition):
        for v in l:
            color[v_to_id[v]] = i

    # Vertex list
    nodes = []
    for v in G.vertices():
        nodes.append({"name": str(v), "group": str(color[v_to_id[v]])})

    # Edge colors.
    edge_color_default = "#aaa"
    from sage.plot.colors import rainbow
    color_list = rainbow(len(edge_partition))
    edge_color = {}
    for i, l in enumerate(edge_partition):
        for e in l:
            u, v, label = e if len(e) == 3 else e+(None,)
            edge_color[u, v, label] = color_list[i]
            if not directed:
                edge_color[v, u, label] = color_list[i]

    # Edge list
    edges = []
    seen = {}  # How many times has this edge been seen ?

    for u, v, l in G.edges():

        # Edge color
        color = edge_color.get((u, v, l), edge_color_default)

        # Computes the curve of the edge
        curve = 0

        # Loop ?
        if u == v:
            seen[u, v] = seen.get((u, v), 0)+1
            curve = seen[u, v]*10+10

        # For directed graphs, one also has to take into accounts
        # edges in the opposite direction
        elif directed:
            if G.has_edge(v, u):
                seen[u, v] = seen.get((u, v), 0)+1
                curve = seen[u, v]*15
                if multiple_edges and len(G.edge_label(u, v)) != 1:
                    # Multiple edges. The first one has curve 15, then
                    # -15, then 30, then -30, ...
                    seen[u, v] = seen.get((u, v), 0) + 1
                    curve = (1 if seen[u, v] % 2 else -1)*(seen[u, v]//2)*15

        elif not directed and multiple_edges:
            # Same formula as above for multiple edges
            if len(G.edge_label(u, v)) != 1:
                seen[u, v] = seen.get((u, v), 0) + 1
                curve = (1 if seen[u, v] % 2 else -1)*(seen[u, v]//2)*15

        # Adding the edge to the list
        edges.append({"source": v_to_id[u],
                      "target": v_to_id[v],
                      "strength": 0,
                      "color": color,
                      "curve": curve,
                      "name": str(l) if edge_labels else ""})

    loops = [e for e in edges if e["source"] == e["target"]]
    edges = [e for e in edges if e["source"] != e["target"]]

    # Defines the vertices' layout if possible
    Gpos = G.get_pos()
    pos = []
    if Gpos is not None and force_spring_layout is False:
        charge = 0
        link_strength = 0
        gravity = 0

        for v in G.vertices():
            x, y = Gpos[v]
            pos.append([json_float(x), json_float(-y)])

    return {"nodes"          : nodes,
            "links"          : edges, "loops": loops, "pos": pos,
            "directed"       : G.is_directed(),
            "charge"         : int(charge),
            "link_distance"  : int(link_distance),
            "link_strength"  : int(link_strength),
            "gravity"        : float(gravity),
            "vertex_labels"  : bool(vertex_labels),
            "edge_labels"    : bool(edge_labels),
            "vertex_size"    : int(vertex_size),
            "edge_thickness" : int(edge_thickness),
            "width"          : json_float(width),
            "height"         : json_float(height) }

Error in lines 1-1 Traceback (most recent call last): File "/cocalc/lib/python2.7/site-packages/smc_sagews/", line 986, in execute reload_attached_files_if_mod_smc() File "/cocalc/lib/python2.7/site-packages/smc_sagews/", line 71, in reload_attached_files_if_mod_smc load(filename) File "/cocalc/lib/python2.7/site-packages/smc_sagews/", line 3511, in load exec 'salvus.namespace["%s"] = sage.structure.sage_object.load(*__args, **__kwds)'%t in salvus.namespace, {'__args':other_args, '__kwds':kwds} File "<string>", line 1, in <module> File "sage/structure/sage_object.pyx", line 1075, in sage.structure.sage_object.load (/ext/sage/sage-8.0/src/build/cythonized/sage/structure/sage_object.c:12949) sage.repl.load.load(filename, globals()) File "/ext/sage/sage-8.0/local/lib/python2.7/site-packages/sage/repl/", line 247, in load exec(preparse_file(open(fpath).read()) + "\n", globals) File "<string>", line 137, in <module> NameError: name 's' is not defined
   File: /cocalc/lib/python2.7/site-packages/smc_sagews/
       def d3_graph(self, g, **kwds):
        from graphics import graph_to_d3_jsonable
        self._send_output(id=self._id, d3={"viewer":"graph", "data":graph_to_d3_jsonable(g, **kwds)})

File: /cocalc/lib/python2.7/site-packages/smc_sagews/
Docstring :
Cell execution state object and wrapper for access to special
CoCalc Server functionality.

An instance of this object is created each time you execute a cell.
It has various methods for sending different types of output
messages, links to files, etc.   Type 'help(smc)' for more details.

OUTPUT LIMITATIONS -- There is an absolute limit on the number of
messages output for a given cell, and also the size of the output
message for each cell.  You can access or change those limits
dynamically in a worksheet as follows by viewing or changing any of
the following variables:

   sage_server.MAX_STDOUT_SIZE       # max length of each stdout output message
   sage_server.MAX_STDERR_SIZE       # max length of each stderr output message
   sage_server.MAX_MD_SIZE           # max length of each md (markdown) output message
   sage_server.MAX_HTML_SIZE         # max length of each html output message
   sage_server.MAX_TEX_SIZE          # max length of tex output message
   sage_server.MAX_OUTPUT_MESSAGES   # max number of messages output for a cell.


   sage_server.MAX_OUTPUT            # max total character output for a single cell; computation
                                     # terminated/truncated if sum of above exceeds this.
150000 256