Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/graphs/graph_editor.py
4036 views
1
#*****************************************************************************
2
# Copyright (C) 2009 Radoslav Kirov
3
#
4
# Distributed under the terms of the GNU General Public License (GPL)
5
#
6
# This code is distributed in the hope that it will be useful,
7
# but WITHOUT ANY WARRANTY; without even the implied warranty of
8
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9
# General Public License for more details.
10
#
11
# The full text of the GPL is available at:
12
#
13
# http://www.gnu.org/licenses/
14
#*****************************************************************************
15
import sys
16
17
from graph_generators import graphs
18
from sage.misc.html import html
19
20
import sagenb.notebook.interact
21
from sagenb.misc.support import EMBEDDED_MODE
22
23
24
def graph_to_js(g):
25
"""
26
Returns a string representation of a :class:`Graph` instance
27
usable by the :func:`graph_editor`. The encoded information is
28
the number of vertices, their 2D positions, and a list of edges.
29
30
INPUT:
31
32
- ``g`` - a :class:`Graph` instance
33
34
OUTPUT:
35
36
- a string
37
38
EXAMPLES::
39
40
sage: from sage.graphs.graph_editor import graph_to_js
41
sage: G = graphs.CompleteGraph(4)
42
sage: graph_to_js(G)
43
'num_vertices=4;edges=[[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]];pos=[[0.5,0.0],[0.0,0.4999999999999999],[0.4999999999999999,1.0],[1.0,0.5000000000000001]];'
44
sage: graph_to_js(graphs.StarGraph(2))
45
'num_vertices=3;edges=[[0,1],[0,2]];pos=[[0.75,0.5],[1.0,0.0],[0.0,1.0]];'
46
"""
47
string = ''
48
vertex_list = g.get_vertices().keys()
49
string += 'num_vertices=' + str(len(vertex_list)) + ';'
50
string += 'edges=['
51
for i, e in enumerate(g.edges()):
52
if(i != 0):
53
string += ','
54
string += '[' + str(vertex_list.index(e[0])) + ',' + str(vertex_list.index(e[1])) + ']'
55
string += '];'
56
string += 'pos=['
57
pos = g.get_pos()
58
max_x = max([i[0] for i in pos.values()])
59
max_y = max([i[1] for i in pos.values()])
60
min_x = min([i[0] for i in pos.values()])
61
min_y = min([i[1] for i in pos.values()])
62
if max_x == 0:
63
max_x = 1
64
if max_y == 0:
65
max_y = 1
66
for i, v in enumerate(vertex_list):
67
if(i != 0):
68
string += ','
69
new_pos = [float(pos[v][0] - min_x) / (max_x - min_x),
70
1.0 - float(pos[v][1] - min_y) / (max_y - min_y)]
71
string += str(new_pos)
72
string += '];'
73
string = string.replace(' ', '')
74
return string
75
76
def graph_editor(graph=None, graph_name=None,
77
replace_input=True, **layout_options):
78
"""
79
Opens a graph editor in the Sage notebook.
80
81
INPUT:
82
83
- ``graph`` - a :class:`Graph` instance (default:
84
graphs.CompleteGraph(2)); the graph to edit
85
86
- ``graph_name`` - a string (default: None); the variable name to
87
use for the updated instance; by default, this function attempts
88
to determine the name automatically
89
90
- ``replace_input`` - a boolean (default: True); whether to
91
replace the text in the input cell with the updated graph data
92
when "Save" is clicked; if this is False, the data is **still**
93
evaluated as if it had been entered in the cell
94
95
EXAMPLES::
96
97
sage: g = graphs.CompleteGraph(3)
98
sage: graph_editor(g) # not tested
99
sage: graph_editor(graphs.HouseGraph()) # not tested
100
sage: graph_editor(graph_name='my_graph') # not tested
101
sage: h = graphs.StarGraph(6)
102
sage: graph_editor(h, replace_input=False) # not tested
103
"""
104
if graph is None:
105
graph = graphs.CompleteGraph(2)
106
107
if not EMBEDDED_MODE:
108
return "This graph editor only runs in the Sage notebook."
109
110
graph.layout(save_pos = True, **layout_options)
111
112
if graph_name is None:
113
graph_name = ''
114
locs = sys._getframe(1).f_locals
115
for var in locs:
116
if id(locs[var]) == id(graph):
117
graph_name = var
118
119
cell_id = sagenb.notebook.interact.SAGE_CELL_ID
120
121
# TODO: Put reasonable checks for large graphs, before disaster
122
# occurs (i.e., breaks browser).
123
124
close_button = r"""<button onclick="cell_delete_output(%(cell_id)s);">Close</button>""" % locals()
125
126
if replace_input:
127
eval_strategy = r"""
128
f += ' graph_editor(' + g[2] + ');'
129
\$('#cell_input_%(cell_id)s').val(f);
130
cell_input_resize(%(cell_id)s);
131
evaluate_cell(%(cell_id)s, false);
132
""" % locals()
133
else:
134
eval_strategy = r"""
135
saved_input = \$('#cell_input_%(cell_id)s').val();
136
\$('#cell_input_%(cell_id)s').val(f);
137
evaluate_cell(%(cell_id)s, false);
138
\$('#cell_input_%(cell_id)s').val(saved_input);
139
send_cell_input(%(cell_id)s);
140
cell_input_resize(%(cell_id)s);
141
""" % locals()
142
143
update_button = r"""<button onclick="
144
var f, g, saved_input;
145
g = \$('#iframe_graph_editor_%(cell_id)s')[0].contentWindow.update_sage();
146
147
if (g[2] === '') {
148
alert('You need to give a Sage variable name to the graph, before saving it.');
149
return;
150
}
151
f = g[2] + ' = Graph(' + g[0] + '); ' + g[2] + '.set_pos(' + g[1] + '); '
152
%(eval_strategy)s
153
">Save</button>""" % locals()
154
155
graph_js = graph_to_js(graph)
156
data_fields = """<input type="hidden" id="graph_data_%(cell_id)s" value="%(graph_js)s"><input type="hidden" id="graph_name_%(cell_id)s" value="%(graph_name)s">""" % locals()
157
158
return html(r"""<div id="graph_editor_%(cell_id)s"><table><tbody>
159
<tr><td><iframe style="width: 800px; height: 400px; border: 0;" id="iframe_graph_editor_%(cell_id)s" src="/javascript/graph_editor/graph_editor.html?cell_id=%(cell_id)s"></iframe>%(data_fields)s</td></tr>
160
<tr><td>%(update_button)s%(close_button)s</td></tr>
161
</tbody></table></div>""" % locals())
162
163
# This is commented out because the mouse_out call raises an error in
164
# Firebug's console when the event fires but the function itself has
165
# not yet been loaded.
166
167
# <tr><td><iframe style="width: 800px; height: 400px; border: 0;" id="iframe_graph_editor_%(cell_id)s" src="/javascript/graph_editor/graph_editor.html?cell_id=%(cell_id)s" onmouseout="\$('#iframe_graph_editor_%(cell_id)s')[0].contentWindow.mouse_out();"></iframe>%(data_fields)s</td></tr>
168
169