| 243 | |
| 244 | def vertex_coloring(self,k=None,value_only=False,hex_colors=False,log=0): |
| 245 | """ |
| 246 | Computes the chromatic number of a graph, or tests its `k`-colorability |
| 247 | ( cf. http://en.wikipedia.org/wiki/Graph_coloring ) |
| 248 | |
| 249 | INPUT: |
| 250 | |
| 251 | - ``value_only`` ( boolean )-- |
| 252 | - When set to ``True``, only the chromatic number is returned |
| 253 | - When set to ``False`` (default), a partition of the vertex set into |
| 254 | independant sets is returned is possible |
| 255 | |
| 256 | - ``k`` ( an integer ) -- Tests whether the graph is `k`-colorable. |
| 257 | The function returns a partition of the vertex set in `k` |
| 258 | independent sets if possible and ``False`` otherwise. |
| 259 | |
| 260 | - ``hex_colors`` -- When set to ``True`` ( it is ``False`` by default ), |
| 261 | the partition returned is a dictionary whose keys are colors and whose |
| 262 | values are the color classes ( ideal to be plotted ) |
| 263 | |
| 264 | - ``log`` ( integer ) -- As vertex-coloring is a `NP`-complete problem, |
| 265 | its solving may take some time depending on the graph. Use ``log`` to |
| 266 | define the level of verbosity you want from the linear program solver. |
| 267 | |
| 268 | By default ``log=0``, meaning that there will be no message printed by the solver. |
| 269 | |
| 270 | OUTPUT : |
| 271 | |
| 272 | - If ``k=None`` and ``value_only=None``: |
| 273 | Returns a partition of the vertex set into the minimum possible of independent sets |
| 274 | |
| 275 | - If ``k=None`` and ``value_only=True``: |
| 276 | Returns the chromatic number |
| 277 | |
| 278 | - If ``k`` is set and ``value_only=None``: |
| 279 | Returns False if the graph is not `k`-colorable, and a partition of the |
| 280 | vertex set into `k` independent sets otherwise |
| 281 | |
| 282 | - If ``k`` is set and ``value_only=True``: |
| 283 | Test whether the graph is `k`-colorable and returns ``True`` or ``False`` accordingly |
| 284 | |
| 285 | |
| 286 | EXAMPLE:: |
| 287 | |
| 288 | sage: from sage.graphs.graph_coloring import vertex_coloring |
| 289 | sage: g=graphs.PetersenGraph() |
| 290 | sage: vertex_coloring(g, value_only=True) # optional - requires GLPK or CBC |
| 291 | 3 |
| 292 | |
| 293 | """ |
| 294 | from sage.numerical.mip import MixedIntegerLinearProgram |
| 295 | from sage.plot.colors import rainbow |
| 296 | g=self |
| 297 | |
| 298 | # If k==None, tries to find an optimal coloring |
| 299 | if k==None: |
| 300 | |
| 301 | # No need to start a linear program if the graph is an independent set or bipartite |
| 302 | # |
| 303 | # - Independent set |
| 304 | if g.size()==0: |
| 305 | if value_only: |
| 306 | return 1 |
| 307 | elif hex_colors: |
| 308 | return dict(zip(rainbow(1),g.vertices())) |
| 309 | else: |
| 310 | return g.vertices() |
| 311 | |
| 312 | # - Bipartite set |
| 313 | if g.is_bipartite(): |
| 314 | if value_only==True: |
| 315 | return 2 |
| 316 | if hex_colors: |
| 317 | return dict(zip(rainbow(2),g.bipartite_sets())) |
| 318 | else: |
| 319 | return g.bipartite_sets() |
| 320 | |
| 321 | # - No need to try any k smaller than the maximum clique in the graph |
| 322 | # - max, because the graph could be triangle-free |
| 323 | |
| 324 | k=max(3, g.clique_number() ) |
| 325 | |
| 326 | while True: |
| 327 | # tries to color the graph, increasing k each time it fails. |
| 328 | tmp=vertex_coloring(g, k=k, value_only=value_only,hex_colors=hex_colors,log=log) |
| 329 | if tmp!=False: |
| 330 | if value_only: |
| 331 | return k |
| 332 | else: |
| 333 | return tmp |
| 334 | k=k+1 |
| 335 | else: |
| 336 | # Is the graph empty ? |
| 337 | |
| 338 | # If the graph is empty, something should be returned.. |
| 339 | # This is not so stupid, as the graph could be emptied |
| 340 | # by the test of degeneracy |
| 341 | if g.order()==0: |
| 342 | if value_only==True: |
| 343 | return True |
| 344 | elif hex_colors==True: |
| 345 | return dict([(color,[]) for color in rainbow(k)]) |
| 346 | else: |
| 347 | return [[] for i in range(k)] |
| 348 | |
| 349 | # Is the graph connected ? |
| 350 | |
| 351 | # This is not so stupid, as the graph could be disconnected |
| 352 | # by the test of degeneracy ( as previously ) |
| 353 | |
| 354 | if g.is_connected()==False: |
| 355 | if value_only==True: |
| 356 | for component in g.connected_components(): |
| 357 | if vertex_coloring(g.subgraph(component),k=k,value_only=value_only,hex_colors=hex_colors,log=log)==False: |
| 358 | return False |
| 359 | return True |
| 360 | |
| 361 | colorings=[] |
| 362 | for component in g.connected_components(): |
| 363 | tmp=vertex_coloring(g.subgraph(component),k=k,value_only=value_only,hex_colors=False,log=log) |
| 364 | if tmp==False: |
| 365 | return False |
| 366 | colorings.append(tmp) |
| 367 | value=[[] for color in range(k)] |
| 368 | for color in range(k): |
| 369 | for component in colorings: |
| 370 | value[color].extend(component[color]) |
| 371 | |
| 372 | if hex_colors: |
| 373 | return dict(zip(rainbow(k),value)) |
| 374 | else: |
| 375 | return value |
| 376 | |
| 377 | # Degeneracy |
| 378 | |
| 379 | # Vertices whose degree is less than k are of no importance in the coloring |
| 380 | |
| 381 | if min(g.degree())<k: |
| 382 | vertices=set(g.vertices()) |
| 383 | deg=[] |
| 384 | tmp=[v for v in vertices if g.degree(v)<k] |
| 385 | while len(tmp)>0: |
| 386 | v=tmp.pop(0) |
| 387 | neighbors=list(set(g.neighbors(v)) & vertices) |
| 388 | if v in vertices and len(neighbors)<k: |
| 389 | vertices.remove(v) |
| 390 | tmp.extend(neighbors) |
| 391 | deg.append(v) |
| 392 | |
| 393 | if value_only==True: |
| 394 | return vertex_coloring(g.subgraph(list(vertices)),k=k,value_only=value_only,hex_colors=hex_colors,log=log) |
| 395 | |
| 396 | value=vertex_coloring(g.subgraph(list(vertices)),k=k,value_only=value_only,hex_colors=False,log=log) |
| 397 | if value==False: |
| 398 | return False |
| 399 | while len(deg)>0: |
| 400 | for classe in value: |
| 401 | if len(list(set(classe) & set(g.neighbors(deg[-1]))))==0: |
| 402 | classe.append(deg[-1]) |
| 403 | deg.pop(-1) |
| 404 | break |
| 405 | if hex_colors: |
| 406 | return dict(zip(rainbow(k),value)) |
| 407 | else: |
| 408 | return value |
| 409 | |
| 410 | |
| 411 | p=MixedIntegerLinearProgram(maximization=True) |
| 412 | color=p.new_variable(dim=2) |
| 413 | |
| 414 | # a vertex has exactly one color |
| 415 | [p.add_constraint(sum([color[v][i] for i in range(k)]),min=1,max=1) for v in g.vertices()] |
| 416 | |
| 417 | # Adjacent vertices have different colors |
| 418 | [p.add_constraint(color[u][i]+color[v][i],max=1) for (u,v) in g.edge_iterator(labels=None) for i in range(k)] |
| 419 | |
| 420 | # Anything is good as an objective value as long as it is satisfiable |
| 421 | p.add_constraint(color[g.vertex_iterator().next()][0], max=1, min=1) |
| 422 | p.set_objective(color[g.vertex_iterator().next()][0]) |
| 423 | |
| 424 | p.set_binary(color) |
| 425 | from sage.numerical.mip import MIPSolverException |
| 426 | |
| 427 | try: |
| 428 | if value_only==True: |
| 429 | p.solve(objective_only=True,log=log) |
| 430 | return True |
| 431 | else: |
| 432 | chi=p.solve(log=log) |
| 433 | except MIPSolverException: |
| 434 | return False |
| 435 | |
| 436 | color=p.get_values(color) |
| 437 | |
| 438 | # builds the color classes |
| 439 | classes=[[] for i in range(k)] |
| 440 | [classes[i].append(v) for i in range(k) for v in g.vertices() if color[v][i]==1] |
| 441 | |
| 442 | if hex_colors: |
| 443 | return dict(zip(rainbow(len(classes)),classes)) |
| 444 | else: |
| 445 | return classes |
| 446 | |
| 447 | def edge_coloring(self,value_only=False,vizing=False,hex_colors=False, log=0): |
| 448 | """ |
| 449 | Properly colors the edges of a graph. |
| 450 | ( cf. http://en.wikipedia.org/wiki/Edge_coloring ) |
| 451 | |
| 452 | INPUT: |
| 453 | |
| 454 | - ``value_only`` (boolean) -- |
| 455 | |
| 456 | - When set to ``True``, only the chromatic index is returned |
| 457 | - When set to ``False`` (default), a partition of the edge set into |
| 458 | matchings is returned is possible |
| 459 | |
| 460 | - ``vizing`` (boolean) -- |
| 461 | - When set to ``True``, tries to find a `\Delta+1`-edge-coloring ( where |
| 462 | `\Delta` is equal to the maximum degree in the graph ) |
| 463 | |
| 464 | - When set to ``False``, tries to find a `\Delta`-edge-coloring ( where |
| 465 | `\Delta` is equal to the maximum degree in the graph ). If impossible, |
| 466 | tries to find and returns a `\Delta+1`-edge-coloring |
| 467 | |
| 468 | --- Implies ``value_only = False`` --- |
| 469 | |
| 470 | - ``hex_colors`` (boolean) -- |
| 471 | |
| 472 | When set to ``True`` ( it is ``False`` by default ), the partition returned |
| 473 | is a dictionary whose keys are colors and whose values are the color classes |
| 474 | ( ideal to be plotted ) |
| 475 | |
| 476 | - ``log`` ( integer ) -- |
| 477 | As edge-coloring is a `NP`-complete problem, its solving may take some time |
| 478 | depending on the graph. Use ``log`` to define the level of verbosity you want |
| 479 | from the linear program solver. |
| 480 | |
| 481 | By default ``log=0``, meaning that there will be no message printed by the solver. |
| 482 | |
| 483 | OUTPUT : |
| 484 | |
| 485 | In the following, `\Delta` is equal to the maximum degree in the graph |
| 486 | |
| 487 | - If ``vizing=True`` and ``value_only=False``: |
| 488 | Returns a partition of the edge set into Delta+1 matchings |
| 489 | |
| 490 | - If ``vizing=False`` and ``value_only=True``: |
| 491 | Returns the chromatic index |
| 492 | |
| 493 | - If ``vizing=False`` and ``value_only=False``: |
| 494 | Returns a partition of the edge set into the minimum number of matchings |
| 495 | |
| 496 | - If ``vizing=True`` is set and ``value_only=True``: |
| 497 | Should return something, but mainly you are just trying to compute the maximum |
| 498 | degree of the graph, and this is not the easiest way ;-) |
| 499 | By Vizing's theorem, a graph has a chromatic index equal to `\Delta` |
| 500 | or to `\Delta+1` |
| 501 | |
| 502 | EXAMPLE:: |
| 503 | |
| 504 | sage: from sage.graphs.graph_coloring import edge_coloring |
| 505 | sage: g=graphs.PetersenGraph() |
| 506 | sage: edge_coloring(g, value_only=True) # optional - requires GLPK or CBC |
| 507 | 4 |
| 508 | |
| 509 | Completes graphs are colored using the linear-time Round-robin coloring :: |
| 510 | |
| 511 | sage: from sage.graphs.graph_coloring import edge_coloring |
| 512 | sage: len(edge_coloring(graphs.CompleteGraph(20))) |
| 513 | 19 |
| 514 | |
| 515 | """ |
| 516 | from sage.numerical.mip import MixedIntegerLinearProgram |
| 517 | from sage.plot.colors import rainbow |
| 518 | g=self |
| 519 | |
| 520 | |
| 521 | if g.is_clique(): |
| 522 | if value_only: |
| 523 | return g.order() if g.order() % 2 ==0 else g.order()+1 |
| 524 | vertices=g.vertices() |
| 525 | r = round_robin(g.order()) |
| 526 | classes=[[] for v in g] |
| 527 | if g.order() % 2 == 0 and vizing == False: |
| 528 | classes.pop() |
| 529 | |
| 530 | for (u,v,c) in r.edge_iterator(): |
| 531 | classes[c].append((vertices[u], vertices[v])) |
| 532 | |
| 533 | if hex_colors: |
| 534 | from sage.plot.colors import rainbow |
| 535 | return zip(rainbow(len(classes)),classes) |
| 536 | else: |
| 537 | return classes |
| 538 | |
| 539 | |
| 540 | p=MixedIntegerLinearProgram(maximization=True) |
| 541 | color=p.new_variable(dim=2) |
| 542 | obj={} |
| 543 | k=max(g.degree()) |
| 544 | |
| 545 | # reorders the edge if necessary... |
| 546 | R = lambda x : x if (x[0]<=x[1]) else (x[1],x[0],x[2]) |
| 547 | |
| 548 | # Vizing's coloring uses Delta+1 colors |
| 549 | if vizing: |
| 550 | value_only=False |
| 551 | k=k+1 |
| 552 | |
| 553 | # A vertex can not have two incident edges with |
| 554 | # the same color |
| 555 | [p.add_constraint(sum([color[R(e)][i] for e in g.edges_incident(v)]),max=1) for v in g.vertex_iterator() for i in range(k)] |
| 556 | |
| 557 | # An edge must have a color |
| 558 | [p.add_constraint(sum([color[R(e)][i] for i in range(k)]),max=1,min=1) for e in g.edge_iterator()] |
| 559 | |
| 560 | # Anything is good as an objective value as long as it is satisfiable |
| 561 | e=g.edge_iterator().next() |
| 562 | p.set_objective(color[R(e)][0]) |
| 563 | |
| 564 | p.set_binary(color) |
| 565 | try: |
| 566 | if value_only==True: |
| 567 | p.solve(objective_only=True,log=log) |
| 568 | else: |
| 569 | chi=p.solve(log=log) |
| 570 | except: |
| 571 | if value_only: |
| 572 | return k+1 |
| 573 | else: |
| 574 | # if the coloring with Delta colors fails, tries Delta+1 |
| 575 | return edge_coloring(g,vizing=True,hex_colors=hex_colors,log=log) |
| 576 | if value_only: |
| 577 | return k |
| 578 | |
| 579 | # Builds the color classes |
| 580 | color=p.get_values(color) |
| 581 | classes=[[] for i in range(k)] |
| 582 | [classes[i].append(e) for e in g.edge_iterator() for i in range(k) if color[R(e)][i]==1] |
| 583 | # if needed, builds a dictionary from the color classes adding colors |
| 584 | if hex_colors: |
| 585 | return dict(zip(rainbow(len(classes)),classes)) |
| 586 | else: |
| 587 | return classes |
| 588 | |
| 589 | def round_robin(n): |
| 590 | r""" |
| 591 | Computes a Round-robin coloring of the complete graph on `n` vertices. |
| 592 | |
| 593 | A Round-robin coloring of the complete graph `G` on |
| 594 | `2n` vertices (`V=[0,\dots,2n-1]`) is a proper coloring of its edges |
| 595 | such that the edges with color `i` are all the `(i+j,i-j)`, plus the |
| 596 | edge `(2n-1,i)`. |
| 597 | |
| 598 | If `n` is odd, one obtain a Round-robin coloring of the complete graph |
| 599 | through the Round-robin coloring of the graph with `n+1` vertices, to |
| 600 | which one is removed. |
| 601 | |
| 602 | INPUT: |
| 603 | |
| 604 | - ``n`` -- the number of vertices in the complete graph. |
| 605 | |
| 606 | OUTPUT: |
| 607 | |
| 608 | - A CompleteGraph with labelled edges, such that the label of each |
| 609 | edge is its color. |
| 610 | |
| 611 | EXAMPLES:: |
| 612 | |
| 613 | sage: from sage.graphs.graph_coloring import round_robin |
| 614 | sage: round_robin(3).edges() |
| 615 | [(0, 1, 2), (0, 2, 1), (1, 2, 0)] |
| 616 | |
| 617 | :: |
| 618 | |
| 619 | sage: round_robin(4).edges() |
| 620 | [(0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 2, 0), (1, 3, 1), (2, 3, 2)] |
| 621 | |
| 622 | |
| 623 | For higher orders, the coloring is still proper and uses the expected |
| 624 | number of colors. |
| 625 | |
| 626 | :: |
| 627 | |
| 628 | sage: g = round_robin(9) |
| 629 | sage: sum([Set([e[2] for e in g.edges_incident(v)]).cardinality() for v in g]) == 2*g.size() |
| 630 | True |
| 631 | sage: Set([e[2] for e in g.edge_iterator()]).cardinality() |
| 632 | 9 |
| 633 | |
| 634 | :: |
| 635 | |
| 636 | sage: g = round_robin(10) |
| 637 | sage: sum([Set([e[2] for e in g.edges_incident(v)]).cardinality() for v in g]) == 2*g.size() |
| 638 | True |
| 639 | sage: Set([e[2] for e in g.edge_iterator()]).cardinality() |
| 640 | 9 |
| 641 | |
| 642 | |
| 643 | """ |
| 644 | |
| 645 | if not (n>1): |
| 646 | raise ValueError, "There must be at least two vertices in the graph." |
| 647 | |
| 648 | mod = lambda x,y : x - y*(x//y) |
| 649 | |
| 650 | if n % 2 == 0: |
| 651 | g=GraphGenerators().CompleteGraph(n) |
| 652 | for i in range(n-1): |
| 653 | g.set_edge_label(n-1,i,i) |
| 654 | for j in range(1,(n-1)//2+1): |
| 655 | g.set_edge_label(mod(i-j,n-1),mod(i+j,n-1),i) |
| 656 | |
| 657 | return g |
| 658 | |
| 659 | else: |
| 660 | g=round_robin(n+1) |
| 661 | g.delete_vertex(n) |
| 662 | return g |
| 663 | |
| 664 | |