Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/graphs/graph_list.py
4045 views
1
r"""
2
Lists of graphs
3
4
AUTHORS:
5
6
- Robert L. Miller (2007-02-10): initial version
7
8
- Emily A. Kirkman (2007-02-13): added show functions
9
(to_graphics_array and show_graphs)
10
"""
11
12
#*****************************************************************************
13
# Copyright (C) 2007 Robert L. Miller <[email protected]>
14
# and Emily A. Kirkman
15
#
16
# Distributed under the terms of the GNU General Public License (GPL)
17
# http://www.gnu.org/licenses/
18
#*****************************************************************************
19
20
def from_whatever(data):
21
"""
22
Returns a list of Sage Graphs, given a list of whatever kind of
23
data.
24
25
INPUT:
26
27
28
- ``data`` - can be a string, a list of strings, or a
29
file stream, or whatever.
30
31
32
EXAMPLE::
33
34
sage: l = ['N@@?N@UGAGG?gGlKCMO',':P_`cBaC_ACd`C_@BC`ABDHaEH_@BF_@CHIK_@BCEHKL_BIKM_BFGHI']
35
sage: graphs_list.from_whatever(l)
36
[Graph on 15 vertices, Looped multi-graph on 17 vertices]
37
"""
38
from sage.graphs.graph import Graph
39
if isinstance(data, file):
40
if data.name[data.name.rindex('.'):] == '.g6':
41
return from_graph6(data)
42
elif data.name[data.name.rindex('.'):] == '.s6':
43
return from_sparse6(data)
44
else: # convert to list of lines, do each separately
45
L = data.readlines()
46
return from_whatever(L)
47
if isinstance(data, list):
48
l = []
49
for d in data:
50
if isinstance(d, str):
51
nn = d.rfind('\n')
52
if nn == -1:
53
sparse = bool(d[0] == ':')
54
l.append(Graph(d, sparse=sparse))
55
elif len(d) == nn + 1:
56
sparse = bool(d[0] == ':')
57
l.append(Graph(d[:nn], sparse=sparse))
58
else:
59
l.append(from_whatever(d))
60
else:
61
l.append(from_whatever(d))
62
return l
63
if isinstance(data, str):
64
data = data.split('\n')
65
l = []
66
for d in data:
67
if not d == '':
68
sparse = bool(d[0] == ':')
69
l.append(Graph(d, sparse=sparse))
70
return l
71
72
def from_graph6(data):
73
"""
74
Returns a list of Sage Graphs, given a list of graph6 data.
75
76
INPUT:
77
78
79
- ``data`` - can be a string, a list of strings, or a
80
file stream.
81
82
83
EXAMPLE::
84
85
sage: l = ['N@@?N@UGAGG?gGlKCMO','XsGGWOW?CC?C@HQKHqOjYKC_uHWGX?P?~TqIKA`OA@SAOEcEA??']
86
sage: graphs_list.from_graph6(l)
87
[Graph on 15 vertices, Graph on 25 vertices]
88
"""
89
from sage.graphs.graph import Graph
90
if isinstance(data,str):
91
data = data.split('\n')
92
l = []
93
for d in data:
94
if not d == '':
95
l.append(Graph(d, format = 'graph6'))
96
return l
97
elif isinstance(data,list):
98
l = []
99
for d in data:
100
if isinstance(d, str):
101
nn = d.rfind('\n')
102
if nn == -1:
103
l.append(Graph(d,format='graph6'))
104
elif len(d) == nn + 1:
105
l.append(Graph(d[:nn], format='graph6'))
106
else:
107
l.append(from_graph6(d))
108
else:
109
l.append(from_graph6(d))
110
return l
111
elif isinstance(data,file):
112
strlist = data.readlines()
113
l = []
114
for s in strlist:
115
l.append(Graph(s[:s.rfind('\n')], format='graph6'))
116
return l
117
118
def from_sparse6(data):
119
"""
120
Returns a list of Sage Graphs, given a list of sparse6 data.
121
122
INPUT:
123
124
125
- ``data`` - can be a string, a list of strings, or a
126
file stream.
127
128
129
EXAMPLE::
130
131
sage: l = [':P_`cBaC_ACd`C_@BC`ABDHaEH_@BF_@CHIK_@BCEHKL_BIKM_BFGHI',':f`??KO?B_OOSCGE_?OWONDBO?GOJBDO?_SSJdApcOIG`?og_UKEbg?_SKFq@[CCBA`p?oYMFp@gw]Qaa@xEMHDb@hMCBCbQ@ECHEcAKKQKFPOwo[PIDQ{KIHEcQPOkVKEW_WMNKqPWwcRKOOWSKIGCqhWt??___WMJFCahWzEBa`xOu[MpPPKqYNoOOOKHHDBPs|??__gWMKEcAHKgTLErqA?A@a@G{kVLErs?GDBA@XCs\\NggWSOJIDbHh@?A@aF']
132
sage: graphs_list.from_sparse6(l)
133
[Looped multi-graph on 17 vertices, Looped multi-graph on 39 vertices]
134
"""
135
from sage.graphs.graph import Graph
136
if isinstance(data,str):
137
data = data.split('\n')
138
l = []
139
for d in data:
140
if not d == '':
141
l.append(Graph(d, format = 'sparse6', sparse=True))
142
return l
143
elif isinstance(data,list):
144
l = []
145
for d in data:
146
if isinstance(d, str):
147
nn = d.rfind('\n')
148
if nn == -1:
149
l.append(Graph(d, format='sparse6', sparse=True))
150
elif len(d) == nn + 1:
151
l.append(Graph(d[:nn], format='sparse6', sparse=True))
152
else:
153
l.append(from_sparse6(d))
154
else:
155
l.append(from_sparse6(d))
156
return l
157
elif isinstance(data,file):
158
strlist = data.readlines()
159
l = []
160
for s in strlist:
161
l.append(Graph(s[:s.rfind('\n')], format='sparse6', sparse=True))
162
return l
163
164
def to_graph6(list, file = None, output_list=False):
165
r"""
166
Converts a list of Sage graphs to a single string of graph6 graphs.
167
If file is specified, then the string will be written quietly to
168
the file. If output_list is True, then a list of strings will be
169
returned, one string per graph.
170
171
INPUT:
172
173
174
- ``list`` - a Python list of Sage Graphs
175
176
- ``file`` - (optional) a file stream to write to
177
(must be in 'w' mode)
178
179
- ``output_list`` - False - output is a string True -
180
output is a list of strings (ignored if file gets specified)
181
182
183
EXAMPLE::
184
185
sage: l = [graphs.DodecahedralGraph(), graphs.PetersenGraph()]
186
sage: graphs_list.to_graph6(l)
187
'ShCHGD@?K?_@?@?C_GGG@??cG?G?GK_?C\nIheA@GUAo\n'
188
"""
189
l = ''
190
for G in list:
191
l += G.graph6_string() + '\n'
192
if file is None:
193
if output_list:
194
a = l.split('\n')
195
a = a[:len(a)-1]
196
return a
197
else:
198
return l
199
else:
200
file.write(l)
201
file.flush()
202
203
def to_sparse6(list, file = None, output_list=False):
204
r"""
205
Converts a list of Sage graphs to a single string of sparse6
206
graphs. If file is specified, then the string will be written
207
quietly to the file. If output_list is True, then a list of
208
strings will be returned, one string per graph.
209
210
INPUT:
211
212
213
- ``list`` - a Python list of Sage Graphs
214
215
- ``file`` - (optional) a file stream to write to
216
(must be in 'w' mode)
217
218
- ``output_list`` - False - output is a string True -
219
output is a list of strings (ignored if file gets specified)
220
221
222
EXAMPLE::
223
224
sage: l = [graphs.DodecahedralGraph(), graphs.PetersenGraph()]
225
sage: graphs_list.to_sparse6(l)
226
':S_`abcaDe`Fg_HijhKfLdMkNcOjP_BQ\n:I`ES@obGkqegW~\n'
227
"""
228
l = ''
229
for G in list:
230
l += G.sparse6_string() + '\n'
231
if file is None:
232
if output_list:
233
a = l.split('\n')
234
a = a[:len(a)-1]
235
return a
236
else:
237
return l
238
else:
239
file.write(l)
240
file.flush()
241
242
def to_graphics_arrays(list, **kwds):
243
"""
244
Returns a list of Sage graphics arrays containing the graphs in
245
list. The maximum number of graphs per array is 20 (5 rows of 4).
246
Use this function if there are too many graphs for the show_graphs
247
function. The graphics arrays will contain 20 graphs each except
248
potentially the last graphics array in the list.
249
250
INPUT:
251
252
253
- ``list`` - a list of Sage graphs
254
255
256
GRAPH PLOTTING: Defaults to circular layout for graphs. This allows
257
for a nicer display in a small area and takes much less time to
258
compute than the spring- layout algorithm for many graphs.
259
260
EXAMPLES::
261
262
sage: glist = []
263
sage: for i in range(999):
264
... glist.append(graphs.RandomGNP(6,.45))
265
...
266
sage: garray = graphs_list.to_graphics_arrays(glist)
267
268
Display the first graphics array in the list.
269
270
::
271
272
sage: garray[0].show()
273
274
Display the last graphics array in the list.
275
276
::
277
278
sage: garray[len(garray)-1].show()
279
280
See the .plot() or .show() documentation for an individual graph
281
for options, all of which are available from to_graphics_arrays
282
283
::
284
285
sage: glist = []
286
sage: for _ in range(10):
287
... glist.append(graphs.RandomLobster(41, .3, .4))
288
sage: w = graphs_list.to_graphics_arrays(glist, layout='spring', vertex_size=20)
289
sage: len(w)
290
1
291
sage: w[0]
292
"""
293
from sage.plot.plot import graphics_array
294
from sage.graphs import graph
295
plist = []
296
g_arrays = []
297
for i in range (len(list)):
298
if ( isinstance( list[i], graph.GenericGraph ) ):
299
pos = list[i].get_pos()
300
if ( pos is None ):
301
if not kwds.has_key('layout'):
302
kwds['layout'] = 'circular'
303
if not kwds.has_key('vertex_size'):
304
kwds['vertex_size'] = 50
305
if not kwds.has_key('vertex_labels'):
306
kwds['vertex_labels'] = False
307
kwds['graph_border'] = True
308
plist.append(list[i].plot(**kwds))
309
else: plist.append(list[i].plot(pos=pos, vertex_size=50, vertex_labels=False, graph_border=True))
310
else: raise TypeError, 'Param list must be a list of Sage (di)graphs.'
311
312
num_arrays = len(plist)/20
313
if ( len(plist)%20 > 0 ): num_arrays += 1
314
rows = 5
315
cols = 4
316
317
for i in range (num_arrays-1):
318
glist = []
319
for j in range (rows*cols):
320
glist.append(plist[ i*rows*cols + j ])
321
ga = graphics_array(glist, rows, cols)
322
ga.__set_figsize__([8,10])
323
g_arrays.append(ga)
324
325
last = len(plist)%20
326
if ( last == 0 and len(plist) != 0 ): last = 20
327
index = (num_arrays-1)*rows*cols
328
last_rows = last/cols
329
if ( last%cols > 0 ): last_rows += 1
330
331
glist = []
332
for i in range (last):
333
glist.append(plist[ i + index])
334
ga = graphics_array(glist, last_rows, cols)
335
ga.__set_figsize__([8, 2*last_rows])
336
g_arrays.append(ga)
337
338
return g_arrays
339
340
def show_graphs(list, **kwds):
341
"""
342
Shows a maximum of 20 graphs from list in a sage graphics array. If
343
more than 20 graphs are given in the list argument, then it will
344
display one graphics array after another with each containing at
345
most 20 graphs.
346
347
Note that if to save the image output from the notebook, you must
348
save each graphics array individually. (There will be a small space
349
between graphics arrays).
350
351
INPUT:
352
353
354
- ``list`` - a list of Sage graphs
355
356
357
GRAPH PLOTTING: Defaults to circular layout for graphs. This allows
358
for a nicer display in a small area and takes much less time to
359
compute than the spring- layout algorithm for many graphs.
360
361
EXAMPLES: Create a list of graphs::
362
363
sage: glist = []
364
sage: glist.append(graphs.CompleteGraph(6))
365
sage: glist.append(graphs.CompleteBipartiteGraph(4,5))
366
sage: glist.append(graphs.BarbellGraph(7,4))
367
sage: glist.append(graphs.CycleGraph(15))
368
sage: glist.append(graphs.DiamondGraph())
369
sage: glist.append(graphs.HouseGraph())
370
sage: glist.append(graphs.HouseXGraph())
371
sage: glist.append(graphs.KrackhardtKiteGraph())
372
sage: glist.append(graphs.LadderGraph(5))
373
sage: glist.append(graphs.LollipopGraph(5,6))
374
sage: glist.append(graphs.PathGraph(15))
375
sage: glist.append(graphs.PetersenGraph())
376
sage: glist.append(graphs.StarGraph(17))
377
sage: glist.append(graphs.WheelGraph(9))
378
379
Check that length is = 20::
380
381
sage: len(glist)
382
14
383
384
Show the graphs in a graphics array::
385
386
sage: graphs_list.show_graphs(glist)
387
388
Here's an example where more than one graphics array is used::
389
390
sage: gq = GraphQuery(display_cols=['graph6'],num_vertices=5)
391
sage: g = gq.get_graphs_list()
392
sage: len(g)
393
34
394
sage: graphs_list.show_graphs(g)
395
396
See the .plot() or .show() documentation for an individual graph
397
for options, all of which are available from to_graphics_arrays
398
399
::
400
401
sage: glist = []
402
sage: for _ in range(10):
403
... glist.append(graphs.RandomLobster(41, .3, .4))
404
sage: graphs_list.show_graphs(glist, layout='spring', vertex_size=20)
405
"""
406
ga_list = to_graphics_arrays(list, **kwds)
407
408
for i in range (len(ga_list)):
409
(ga_list[i]).show()
410
411
return
412
413
414
415