Debian Codegraph @

wxgeometrie/mathlib/graphes.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 ##--------------------------------------#######
4 # Graphes #
5 ##--------------------------------------#######
6 # WxGeometrie
7 # Dynamic geometry, graph plotter, and more for french mathematic teachers.
8 # Copyright (C) 2005-2013 Nicolas Pourcelot
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program; if not, write to the Free Software
22 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
23
24 # Lexicon
25 # http://www.apprendre-en-ligne.net/graphes/lexique/index.html
26 # http://en.wikipedia.org/wiki/Glossary_of_graph_theory
27
28 import collections, copy
29
30 from sympy import oo, Matrix
31 from ..pylib import OrderedDict, advanced_split
32
33 class GraphError(Exception):
34 pass
35
36 # http://www.chansonsdewallonie.be/PAGES/COULEURS/CouleursTeintes.htm
37 # http://www.w3.org/TR/css3-color/#svg-color (less usefull)
38
39 colors_dict = OrderedDict((
40 ('bleu', (0, 0, 255)), ('rouge', (255, 0, 0)), ('vert', (0, 128, 0)),
41 ('orange', (255, 69, 0)), ('violet', (148, 0, 211)), ('jaune', (255, 255, 0)),
42 ('marron', (210, 105, 30)), ('rose', (255, 20, 147)), ('turquoise', (64, 224, 208)),
43 ('indigo', (75, 0, 130)), ('magenta', (255, 0, 255)), ('ocre', (184, 134, 11)),
44 ('olive', (184, 134, 11)), ('pomme', (127, 255, 0)), ('gris', (128, 128, 128)),
45 ('noir', (0, 0, 0))
46 ))
47
48 def colors():
49 for color in colors_dict:
50 yield color
51 num = 0
52 while True:
53 yield 'color %s' %num
54 num += 1
55
56
57
58 class Graph(dict):
59 """A graph representation.
60
61 Graph are stored as a dictionary:
62 >>> from wxgeometrie.mathlib.graphes import Graph
63 >>> g = Graph({'A': {'B':[1],'C':[2],'D':[3]}, 'B': {'A':[4],'C':[2]}, 'C':{}, 'D':{}}, oriented=True)
64
65 For convenience, they may be entered as a string:
66 >>> h = Graph("A>(B:1,C:2,D:3), B>(A:4,C:2), C, D", oriented=True)
67 >>> g == h
68 True
69
70 If the graph is not oriented (default), the graph must be symetric:
71 >>> k = Graph("A>(B:1,C:2,D:3), B>(A:4,C:2), C>(A:2,B:2), D>(A:3)")
72 >>> k.symetric
73 True
74
75 Graph nodes may have corresponding labels. A dict should be provided for this.
76 >>> k = Graph("A>(B:1,C:2,D:3), B>(A:4,C:2), C>(A:2,B:2), D>(A:3)",
77 labels = {"A": "Bus stop", "B": "Office", "C": "Bus stop", "D": "Sweet home")
78
79 Labels are used then in some methods to display meaningful text.
80 """ #XXX: doctest fails !!!
81 # teintes = ('bleu', 'rouge', 'vert', 'jaune', 'orange', 'violet',
82 # 'marron', 'rose', 'turquoise', 'cyan', 'magenta', 'ocre',
83 # 'marine', 'indigo', 'pourpre')
84
85 def __init__(self, dictionary = (), oriented = False, labels=None):
86 # Ex: {"A": {"B":[1], "C":[2, 5]}, "B": {}, "C": {"A": [2], "C": [1]}}
87 if isinstance(dictionary, str):
88 dictionary = self._convert_input(dictionary)
89 elif not isinstance(dictionary, dict):
90 dictionary = dict.fromkeys(dictionary, {})
91 for key, val in dictionary.items():
92 if not isinstance(val, dict):
93 dictionary[key] = dict.fromkeys(val, [1])
94 elif isinstance(val, collections.defaultdict):
95 dictionary[key] = dict(val)
96 for node in dictionary[key]:
97 if node not in dictionary:
98 raise GraphError("Edge contain a unknown node: %s." %repr(node))
99 self.oriented = oriented
100 self.labels = (labels if labels is not None else {})
101 dict.__init__(self, dictionary)
102 if not oriented and not self.symetric:
103 raise GraphError("Unoriented graph must be symetric.")
104
105
106 @staticmethod
107 def _convert_input(chaine):
108 # Support nicer input format : "A>(B:1,C:2,D:3), B>(A:4, ...) ..."
109 # -> {"A":{"B":1,"C":2,"D":3},"B":{"A":4, ...} ...}
110 dic = {}
111 nodes = advanced_split(chaine, ',')
112 for node_stuff in nodes:
113 if '>' in node_stuff:
114 node, edges = node_stuff.split('>', 1)
115 else:
116 node, edges = node_stuff, '()'
117 node = node.strip()
118 edges = edges.strip()[1:-1]
119 dic[node] = {}
120 for edge in edges.split(','):
121 if edge:
122 if ':' in edge:
123 node2, distance = edge.split(':', 1)
124 else:
125 node2, distance = edge, '1'
126 node2 = node2.strip()
127 if node2 not in dic[node]:
128 dic[node][node2] = []
129 dic[node][node2].append(float(distance) if '.' in distance else int(distance))
130 #TODO: support exact calculus
131 return dic
132
133
134
135
136
137 @property
138 def order(self):
139 return len(self)
140
141 ## @property
142 ## def ordered_nodes(self):
143 ## return sorted(self)
144
145 nodes = property(dict.keys)
146
147 @property
148 def matrix(self):
149 n = self.order
150 nodes = sorted(self)
151 def f(i, j):
152 # In an unoriented graph, loops are counted twice.
153 k = (1 if self.oriented or i != j else 2)
154 return k*len(self[nodes[i]].get(nodes[j], ()))
155 return Matrix(n, n, f)
156
157 # Matrice avec coeffs=poids aretes
158 def matrix2(self, default=0):
159 n = self.order
160 nodes = sorted(self)
161 def f(i, j):
162 # In an unoriented graph, loops are counted twice.
163 k = (1 if self.oriented or i != j else 2)
164 return min(self[nodes[i]].get(nodes[j], [default]))
165 return Matrix(n, n, f)
166
167 def degree(self, node):
168 if self.oriented:
169 return sum(len(edges) for node2, edges in self[node].items() if node2)
170 else:
171 # In an unoriented graph, loops are counted twice.
172 return sum(len(edges) for node2, edges in self[node].items() if node2 != node) \
173 + 2*len(self[node].get(node, ()))
174
175
176 @property
177 def degrees(self):
178 return dict((node, self.degree(node)) for node in self.nodes)
179
180 @property
181 def to_dict(self):
182 return copy.deepcopy(dict(self))
183
184 def adjacents(self, node1, node2):
185 return node2 in self[node1] or node1 in self[node2]
186
187 @property
188 def connected(self):
189 def adjacent(node, new_nodes):
190 return any(self.adjacents(node, new) for new in new_nodes)
191 remaining_nodes = set(self)
192 new_nodes = [remaining_nodes.pop()]
193 while new_nodes:
194 new_nodes = [node for node in remaining_nodes if adjacent(node, new_nodes)]
195 remaining_nodes.difference_update(new_nodes)
196 return not remaining_nodes
197
198
199 @property
200 def symetric(self):
201 M = self.matrix
202 return M.transpose() == M
203
204 @property
205 def eulerian(self):
206 odds = sum(self.degree(node)%2 for node in self.nodes)
207 return odds in (0, 2)
208
209 def _nodes_sorted_by_degree(self, *first_nodes):
210 return list(first_nodes) \
211 + sorted(set(self).difference(first_nodes), key = self.degree, reverse = True)
212
213
214 def eulerian_trail(self, walk=None):
215 if walk is None:
216 #TODO: return an (arbitrary) eulerian trail if any, else None
217 raise NotImplementedError
218 # return trail
219
220 # Convert input string to a list of nodes.
221 for sep in ('-', ',', ';'):
222 if sep in walk:
223 walk_lst = walk.split(sep)
224 break
225 else:
226 if ' ' in walk:
227 walk_lst = walk.split()
228 else:
229 walk_lst = list(walk)
230 # if not walk_lst:
231 # raise SyntaxError, repr(walk) + " format is incorrect. Nodes should be separated by '-'."
232
233 graph = self.to_dict
234 previous = None # previous node
235
236 def remove_edge(A, B):
237 "Remove edge from graph"
238 endpoints = graph.get(A, {})
239 edges = endpoints.get(B, [])
240 if edges:
241 edges.pop()
242 else:
243 return False
244 if not edges:
245 endpoints.pop(B)
246 if not endpoints:
247 graph.pop(A)
248 return True
249
250 # We remove edges one by one from graph.
251 for node in walk_lst:
252 node = node.strip()
253 if previous is not None:
254 if not remove_edge(previous, node):
255 print("%s-%s edge does not exist, or was already used !"
256 %(previous, node))
257 return False
258 # Edge did not exist, or was already removed.
259 if not self.oriented:
260 if not remove_edge(node, previous):
261 return False
262 previous = node
263
264 if graph:
265 print("Following edges were never used:")
266 for node in graph:
267 for endpoint in graph[node]:
268 print ('%s-%s' %(node, endpoint))
269 return not graph
270
271
272
273 def coloring(self, *first_nodes):
274 """Graph colorization using Welsh & Powell algorithm.
275
276 By default, nodes are sorted according to their degrees, but you can also
277 choose manually the first nodes to be visited.
278 """
279 coloring = []
280 uncolored = self._nodes_sorted_by_degree(*first_nodes)
281 while uncolored:
282 coloring.append([])
283 for node in uncolored:
284 if not any(self.adjacents(node, s) for s in coloring[-1]):
285 coloring[-1].append(node)
286 assert coloring[-1]
287 uncolored = [s for s in uncolored if s not in coloring[-1]]
288 return coloring
289
290
291 def latex_WelshPowell(self, *first_nodes):
292 ordered_nodes = self._nodes_sorted_by_degree(*first_nodes)
293 dico = {}
294 for nodes, color in zip(self.coloring(*ordered_nodes), colors()):
295 for node in nodes:
296 dico[node] = color
297 # Génération du code LaTeX
298 nodes_line = r'Sommets '
299 degrees_line = r'Degr\'es'
300 colors_line = r'Couleurs'
301 for node in ordered_nodes:
302 nodes_line += ' & $%s$ ' %node
303 degrees_line += ' & $%s$ ' %self.degree(node)
304 colors_line += ' & %s ' %dico[node]
305 code = r'\begin{tabular}{|l||*{%s}{c|}}' % len(dico)
306 code += '\n\\hline\n'
307 code += nodes_line + '\\\\\n\\hline\n'
308 code += degrees_line + '\\\\\n\\hline\n'
309 code += colors_line + '\\\\\n\\hline\n'
310 code += '\\end{tabular}\n'
311 return code
312
313 def shortest_path(self, start, end):
314 "Implementation of Dijkstra-Moore algorithm."
315 # current node
316 current = start
317 # Nodes which have been already visited, but still not archived:
318 visited = {start: [0, [start]]}
319 # format: {node: [distance from start, [previous node, alternative previous node, ...]]}
320
321 # Nodes which will not change anymore:
322 archived = {}
323
324 while current != end and visited:
325 archived[current] = visited.pop(current)
326 # We select the node having the smallest distance
327 for neighbor in self[current]:
328 if neighbor not in archived:
329 distance = visited.get(neighbor, [oo])[0]
330 new_distance = archived[current][0] + min(self[current][neighbor])
331 if new_distance < distance:
332 visited[neighbor] = [new_distance, [current]]
333 elif new_distance == distance:
334 visited[neighbor][1].append(current)
335 current = min(visited.items(), key = lambda x:x[1][0])[0]
336 if current in visited:
337 archived[current] = visited.pop(current)
338 in_progress = set([(current,)])
339 final_paths = set()
340 while in_progress:
341 for path in set(in_progress):
342 # print path, in_progress, final_paths
343 in_progress.remove(path)
344 node1 = path[0]
345 for previous in archived[node1][1]:
346 if previous == start:
347 final_paths.add((previous,) + path)
348 else:
349 in_progress.add((previous,) + path)
350 return archived[current][0], final_paths
351 else:
352 return oo, []
353
354
355 def latex_Dijkstra(self, start, end, nodes=None):
356 if nodes is None:
357 nodes = sorted(self)
358 else:
359 if set(nodes) != set(self):
360 raise ValueError("Nodes do not match.")
361 code = "On applique l'algorithme de Moore-Dijkstra~:\n\n"
362 code += r'\begin{tabular}{|*{%s}{c|}}\hline' %len(self)
363 code += '\n' + '&'.join(('$%s$' %node) for node in nodes) + r'\\\hline\hline' + '\n'
364 # current node
365 current = start
366 # Nodes which have been already visited, but still not archived:
367 visited = {start: [0, [start]]}
368 # format: {node: [distance from start, [previous node, alternative previous node, ...]]}
369
370 # Nodes which will not change anymore (shorter path from start has been found):
371 archived = {}
372
373 while current != end and visited:
374 def str2(val):
375 # 2.0 -> "2" ; 2.3 -> "2,3"
376 val = str(val)
377 if '.' in val:
378 val = val.rstrip('0').rstrip('.').replace('.', ',')
379 return val
380
381 def format(node):
382 def _format(node):
383 previous_nodes = ','.join(str(prev) for prev in visited[node][1])
384 return str2(visited[node][0]) + ' $(%s)$' %previous_nodes
385 if node == current:
386 return r'\textbf{%s}' %_format(node)
387 elif node in archived:
388 return ''
389 elif node in visited:
390 return _format(node)
391 else:
392 return r'$+\infty$'
393 code += '&'.join(format(node) for node in nodes) + r'\\\hline' + '\n'
394 archived[current] = visited.pop(current)
395 # We select the node having the smallest distance
396 for neighbor in self[current]:
397 if neighbor not in archived:
398 # best distance found until now between neighbor and start
399 distance = visited.get(neighbor, [oo])[0]
400 # new distance found using current node:
401 # distance(start, current) + distance(current, neighbor)
402 new_distance = archived[current][0] + min(self[current][neighbor])
403 # replace with new distance only if better
404 if new_distance < distance:
405 visited[neighbor] = [new_distance, [current]]
406 elif new_distance == distance:
407 visited[neighbor][1].append(current)
408 current = min(visited.items(), key = lambda x:x[1][0])[0]
409
410 code += '&'.join(format(node) for node in nodes) + r'\\\hline' + '\n'
411 code += '\\end{tabular}\n'
412 if current in visited:
413 archived[current] = visited.pop(current)
414 in_progress = set([(current,)])
415 final_paths = set()
416 while in_progress:
417 for path in set(in_progress):
418 # print path, in_progress, final_paths
419 in_progress.remove(path)
420 node1 = path[0]
421 for previous in archived[node1][1]:
422 if previous == start:
423 final_paths.add((previous,) + path)
424 else:
425 in_progress.add((previous,) + path)
426 distance = str2(archived[current][0])
427 paths = ', '.join('$' + '-'.join(path) + '$' for path in final_paths)
428 plur1 = ('x' if len(final_paths) > 1 else '')
429 plur2 = ('s' if len(final_paths) > 1 else '')
430 code += """
431 La distance minimale entre le sommet $%(start)s$ et le sommet $%(end)s$ est de $%(distance)s$.
432 Cela correspond au%(plur1)s chemin%(plur2)s %(paths)s.
433 """ %locals()
434 return code