Source

grrdrr / gd.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933


import cairo


class Graph(object):

    def __init__(self):
        self.nodes = []
        self.arcs = []
        self.layers = []
        self.style = None
        self.margins = None
        self.size = None

    def add_node(self):
        return Node(self)

    def add_arc(self, origin, target, weight=1.0):
        return Arc(self, origin, target, weight)

    def add_layer(self):
        return Layer(self)

    def set_style(self,
                background_color=(1.0, 1.0, 1.0),
                node_color=(0.0, 0.0, 0.0),
                arc_color=(0.0, 0.0, 0.0),
                text_color=(1.0, 1.0, 1.0),
                font_size=10):
        return GraphStyle(self, background_color=background_color,
                    node_color=node_color, arc_color=arc_color,
                    text_color=text_color, font_size=font_size)

    def set_margins(self, top, right, bottom, left):
        return GraphMargins(self, top, right, bottom, left)

    def set_size(self, width, height):
        return GraphSize(self, width, height)

    def measuring(self):
        if self.style is None:
            self.set_style()

        dummy_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1)
        dummy_context = cairo.Context(dummy_surface)
        dummy_context.set_font_size(self.style.font_size)

        extents = dummy_context.text_extents('M')
        x_bearing, y_bearing, width, height, x_advance, y_advance = extents
        m_width = int(width)*2
        m_height = int(height)*2

        if self.margins is None:
            self.set_margins(m_height, m_width, m_height, m_width)

        for node in self.nodes:
            if node.dimensions is not None:
                continue
            if node.label is not None:
                extents = dummy_context.text_extents(node.label.text)
                x_bearing, y_bearing, width, height, x_advance, y_advance = extents
                node_width = int(width*2)
                node_height = int(height*2)
            else:
                node_width = m_width*2
                node_height = m_height*2
            node.set_dimensions(node_width, node_height)

    def sorting(self):

        def get_cycle(forbidden):

            path = []
            active = {}
            used = set()

            def dfs(node):
                if node in used:
                    return None
                if node in active:
                    cycle = path[active[node]:]
                    return cycle
                active[node] = len(path)
                for arc in node.outgoing:
                    if arc in forbidden:
                        continue
                    path.append(arc)
                    cycle = dfs(arc.target)
                    if cycle is not None:
                        return cycle
                    path.pop()
                used.add(node)
                return None

            for node in self.nodes:
                cycle = dfs(node)
                if cycle is not None:
                    return cycle
            return None

        def get_node_weights(forbidden):
            weights = {}
            active = set()

            def dfs(node):
                assert node not in weights and node not in active
                active.add(node)
                total = 0.0
                for arc in node.outgoing:
                    if arc in forbidden:
                        continue
                    if arc.target not in weights:
                        weights[arc.target] = dfs(arc.target)
                    total += arc.weight + weights[arc.target]
                return total

            for node in self.nodes:
                if node not in weights:
                    weights[node] = dfs(node)
            return weights

        feedback = []
        arc_weights = dict((arc, arc.weight) for arc in self.arcs)

        cycle = get_cycle(feedback)
        while cycle is not None:
            min_weight = min(arc_weights[arc] for arc in cycle)
            for arc in cycle:
                if arc_weights[arc] == min_weight:
                    feedback.append(arc)
                arc_weights[arc] -= min_weight
            cycle = get_cycle(feedback)

        for arc in feedback[:]:
            feedback.remove(arc)
            cycle = get_cycle(feedback)
            if cycle is not None:
                feedback.append(arc)

        node_weights = get_node_weights(feedback)
        ordered_nodes = sorted(self.nodes, key=(lambda node: (node_weights[node], node.index)))
        for value, node in enumerate(ordered_nodes):
            node.set_rank(value)

    def layering(self):
        max_nodes_per_layer = int(len(self.nodes)**0.5)
        nodes = sorted(self.nodes, key=(lambda node: -node.rank.value))
        while nodes:
            candidates = []
            for node in nodes:
                is_candidate = True
                for arc in node.incoming:
                    if arc.origin.rank < node.rank and arc.origin in nodes:
                        is_candidate = False
                for arc in node.outgoing:
                    if arc.target.rank < node.rank and arc.target in nodes:
                        is_candidate = False
                if is_candidate:
                    candidates.append(node)
                if len(candidates) >= max_nodes_per_layer:
                    break
            assert candidates
            layer = self.add_layer()
            for node in candidates:
                layer.add_node_item(node)
                nodes.remove(node)

        for arc in self.arcs:
            origin_layer_index = arc.origin.layer_item.layer.index
            target_layer_index = arc.target.layer_item.layer.index
            min_index = min(origin_layer_index, target_layer_index) + 1
            max_index = max(origin_layer_index, target_layer_index)
            for index in range(min_index, max_index):
                layer = self.layers[index]
                layer.add_arc_item(arc)

    def ordering(self):

        def get_arc_orders(layer):
            arc_orders = {}
            for item in layer.items:
                if item.is_arc:
                    arc_orders[item.arc] = item_orders[item]
                else:
                    for arc in item.node.incoming+item.node.outgoing:
                        arc_orders[arc] = item_orders[item]
            return arc_orders

        def sweep(base_layer, active_layer):
            arc_orders = get_arc_orders(base_layer)

            barycenters = {}
            for item in active_layer.items:
                if item.is_arc:
                    center = 1.0*item_orders[item]
                    if item.arc in arc_orders:
                        center = 1.0*arc_orders[item.arc]
                else:
                    weight = 0.0
                    order = 0.0
                    for arc in item.node.incoming+item.node.outgoing:
                        if arc in arc_orders:
                            weight += arc.weight
                            order += arc_orders[arc]*arc.weight
                    if weight:
                        center = order/weight
                    else:
                        center = 1.0*item_orders[item]
                barycenters[item] = center

            items = sorted(active_layer.items, key=(lambda item: barycenters[item]))
            new_item_orders = {}
            for idx, item in enumerate(items):
                new_item_orders[item] = idx

            return new_item_orders

        def exchange_neighbors():
            for idx in range(len(self.layers)):
                prev_arc_orders = {}
                if idx > 0:
                    prev_arc_orders = get_arc_orders(self.layers[idx-1])
                next_arc_orders = {}
                if idx < len(self.layers)-1:
                    next_arc_orders = get_arc_orders(self.layers[idx+1])

                items = sorted(self.layers[idx].items, key=(lambda item: item_orders[item]))
                for item_idx in range(len(items)-1):
                    left_arcs = []
                    right_arcs = []
                    left_item = items[item_idx]
                    right_item = items[item_idx+1]
                    if left_item.is_arc:
                        left_arcs.append(left_item.arc)
                    else:
                        left_arcs.extend(left_item.node.incoming)
                        left_arcs.extend(left_item.node.outgoing)
                    if right_item.is_arc:
                        right_arcs.append(right_item.arc)
                    else:
                        right_arcs.extend(right_item.node.incoming)
                        right_arcs.extend(right_item.node.outgoing)
                    crossings = 0
                    non_crossings = 0
                    for left_arc in left_arcs:
                        for right_arc in right_arcs:
                            for arc_orders in [prev_arc_orders, next_arc_orders]:
                                if left_arc not in arc_orders or right_arc not in arc_orders:
                                    continue
                                if arc_orders[left_arc] < arc_orders[right_arc]:
                                    non_crossings += 1
                                if arc_orders[left_arc] > arc_orders[right_arc]:
                                    crossings += 1
                    if crossings > non_crossings:
                        new_item_orders = {}
                        new_item_orders[left_item] = item_idx+1
                        new_item_orders[right_item] = item_idx
                        return new_item_orders

            return {}

        def exchange_pairs():
            crossings = get_number_of_crossings()
            for idx in range(len(self.layers)):
                items = self.layers[idx].items
                for left_idx in range(len(items)-1):
                    left_item = items[left_idx]
                    left_order = item_orders[left_item]
                    for right_idx in range(left_idx+1, len(items)):
                        right_item = items[right_idx]
                        right_order = item_orders[right_item]
                        item_orders[left_item] = right_order
                        item_orders[right_item] = left_order
                        new_crossings = get_number_of_crossings()
                        item_orders[left_item] = left_order
                        item_orders[right_item] = right_order
                        if new_crossings < crossings:
                            new_item_orders = {}
                            new_item_orders[left_item] = right_order
                            new_item_orders[right_item] = left_order
                            return new_item_orders
            return {}

        def best_solution():
            min_crossings = None
            min_item_orders = None
            sequence = dynamic(0)
            for crossings, item_orders in sequence:
                if min_crossings is None or crossings < min_crossings:
                    min_crossings = crossings
                    min_item_orders = item_orders
            print "CROSSING WEIGHT:", min_crossings
            return min_item_orders

        def greedy_solution():
            min_crossings = None
            min_item_orders = None
            sequence = greedy_dynamic(0)
            for crossings, item_orders in sequence:
                if min_crossings is None or crossings < min_crossings:
                    min_crossings = crossings
                    min_item_orders = item_orders
            return min_item_orders

        def get_permutations(values):
            permutations = []
            if not values:
                permutations.append([])
            else:
                for idx in range(len(values)):
                    value = values[idx]
                    reduction = values[:idx]+values[idx+1:]
                    for permutation in get_permutations(reduction):
                        permutation.append(value)
                        permutations.append(permutation)
            return permutations

        def dynamic(layer_idx):
            layer = self.layers[layer_idx]
            permutations = get_permutations(range(len(layer.items)))
            sequence = []
            if layer_idx < len(self.layers)-1:
                next_sequence = dynamic(layer_idx+1)
                print "SOLVING LAYER %s; PERMUTATIONS: %s" % (layer_idx, len(permutations)*len(next_sequence))

                arc_items = {}
                node_items = {}
                for item in layer.items:
                    if item.is_arc:
                        arc_items[item.arc] = item
                    else:
                        node_items[item.node] = item
                next_item_neighbors = {}
                for item in self.layers[layer_idx+1].items:
                    neighbors = []
                    if item.is_arc:
                        item_arcs = [item.arc]
                    else:
                        item_arcs = item.node.incoming+item.node.outgoing
                    for arc in item_arcs:
                        if arc in arc_items:
                            neighbors.append((arc, arc_items[arc]))
                        if arc.origin in node_items:
                            neighbors.append((arc, node_items[arc.origin]))
                        if arc.target in node_items:
                            neighbors.append((arc, node_items[arc.target]))
                    next_item_neighbors[item] = neighbors

            for permutation in permutations:
                item_orders = {}
                for item_idx, item_order in enumerate(permutation):
                    item = layer.items[item_idx]
                    item_orders[item] = item_order
                if layer_idx < len(self.layers)-1:
                    best_item_orders = None
                    best_crossings = None

                    crossing_numbers = {}
                    for left_item in self.layers[layer_idx+1].items:
                        for right_item in self.layers[layer_idx+1].items:
                            weight = 0.0
                            if left_item is not right_item:
                                for left_arc, left_neighbor in next_item_neighbors[left_item]:
                                    for right_arc, right_neighbor in next_item_neighbors[right_item]:
                                        if item_orders[left_neighbor] > item_orders[right_neighbor]:
                                            weight += left_arc.weight + right_arc.weight
                            crossing_numbers[left_item, right_item] = weight

                    for next_crossings, next_item_orders in next_sequence:
                        crossings = next_crossings
                        next_ordered_items = sorted(self.layers[layer_idx+1].items,
                                                    key=(lambda item: next_item_orders[item]))
                        for left_idx in range(len(next_ordered_items)-1):
                            left_item = next_ordered_items[left_idx]
                            for right_idx in range(left_idx+1, len(next_ordered_items)):
                                right_item = next_ordered_items[right_idx]
                                crossings += crossing_numbers[left_item, right_item]
                        if best_crossings is None or crossings < best_crossings:
                            best_item_orders = next_item_orders
                            best_crossings = crossings
                    item_orders.update(best_item_orders)
                    crossings = best_crossings
                else:
                    crossings = 0
                sequence.append((crossings, item_orders))
            return sequence

        def greedy_dynamic(layer_idx):
            layer = self.layers[layer_idx]
            permutations = get_permutations(range(len(layer.items)))
            sequence = []
            if layer_idx < len(self.layers)-1:
                next_sequence = greedy_dynamic(layer_idx+1)
                print "SOLVING LAYER %s; PERMUTATIONS: %s" % (layer_idx, len(permutations)*len(next_sequence))

                arc_items = {}
                node_items = {}
                for item in layer.items:
                    if item.is_arc:
                        arc_items[item.arc] = item
                    else:
                        node_items[item.node] = item
                next_item_neighbors = {}
                for item in self.layers[layer_idx+1].items:
                    neighbors = []
                    if item.is_arc:
                        item_arcs = [item.arc]
                    else:
                        item_arcs = item.node.incoming+item.node.outgoing
                    for arc in item_arcs:
                        if arc in arc_items:
                            neighbors.append((arc, arc_items[arc]))
                        if arc.origin in node_items:
                            neighbors.append((arc, node_items[arc.origin]))
                        if arc.target in node_items:
                            neighbors.append((arc, node_items[arc.target]))
                    next_item_neighbors[item] = neighbors

            for permutation in permutations:
                item_orders = {}
                for item_idx, item_order in enumerate(permutation):
                    item = layer.items[item_idx]
                    item_orders[item] = item_order
                if layer_idx < len(self.layers)-1:
                    best_item_orders = None
                    best_crossings = None

                    crossing_numbers = {}
                    for left_item in self.layers[layer_idx+1].items:
                        for right_item in self.layers[layer_idx+1].items:
                            weight = 0
                            if left_item is not right_item:
                                for left_arc, left_neighbor in next_item_neighbors[left_item]:
                                    for right_arc, right_neighbor in next_item_neighbors[right_item]:
                                        if item_orders[left_neighbor] > item_orders[right_neighbor]:
                                            weight += left_arc.weight + right_arc.weight
                            crossing_numbers[left_item, right_item] = weight

                    for next_crossings, next_item_orders in next_sequence:
                        crossings = next_crossings
                        next_ordered_items = sorted(self.layers[layer_idx+1].items,
                                                    key=(lambda item: next_item_orders[item]))
                        for left_idx in range(len(next_ordered_items)-1):
                            left_item = next_ordered_items[left_idx]
                            for right_idx in range(left_idx+1, len(next_ordered_items)):
                                right_item = next_ordered_items[right_idx]
                                crossings += crossing_numbers[left_item, right_item]
                        if best_crossings is None or crossings < best_crossings:
                            best_item_orders = next_item_orders
                            best_crossings = crossings
                    item_orders.update(best_item_orders)
                    crossings = best_crossings
                else:
                    crossings = 0
                sequence.append((crossings, item_orders))
            greedy_value = min(crossings for crossings, item_orders in sequence)
            sequence = [(crossings, item_orders)
                            for crossings, item_orders in sequence
                            if crossings == greedy_value]
            return sequence

        def get_number_of_crossings():

            crossings = 0

            for idx in range(len(self.layers)-1):
                base_layer = self.layers[idx]
                active_layer = self.layers[idx+1]

                arc_orders = {}
                for item in base_layer.items:
                    if item.is_arc:
                        arc_orders[item.arc] = item_orders[item]
                    else:
                        for arc in item.node.incoming+item.node.outgoing:
                            arc_orders[arc] = item_orders[item]

                items = sorted(active_layer.items, key=(lambda item: item_orders[item]))
                for left_idx in range(len(items)-1):
                    left_arcs = []
                    left_item = items[left_idx]
                    if left_item.is_arc:
                        left_arcs.append(left_item.arc)
                    else:
                        left_arcs.extend(left_item.node.incoming)
                        left_arcs.extend(left_item.node.outgoing)
                    for right_idx in range(left_idx+1, len(items)):
                        right_arcs = []
                        right_item = items[right_idx]
                        if right_item.is_arc:
                            right_arcs.append(right_item.arc)
                        else:
                            right_arcs.extend(right_item.node.incoming)
                            right_arcs.extend(right_item.node.outgoing)
                        for left_arc in left_arcs:
                            if left_arc not in arc_orders:
                                continue
                            left_order = arc_orders[left_arc]
                            for right_arc in right_arcs:
                                if right_arc not in arc_orders:
                                    continue
                                right_order = arc_orders[right_arc]
                                if left_order > right_order:
                                    print "CROSS:", left_arc.label.text, right_arc.label.text
                                    crossings += 1

            return crossings

        item_orders = {}
        for layer in self.layers:
            for idx, item in enumerate(layer.items):
                item_orders[item] = idx

        #for idx in range(len(self.layers)-1):
        #    new_item_orders = sweep(self.layers[idx], self.layers[idx+1])
        #    item_orders.update(new_item_orders)

        #for idx in range(len(self.layers)-1, 1, -1):
        #    new_item_orders = sweep(self.layers[idx], self.layers[idx-1])
        #    item_orders.update(new_item_orders)

        #for idx in range(len(self.layers)-1):
        #    new_item_orders = sweep(self.layers[idx], self.layers[idx+1])
        #    item_orders.update(new_item_orders)

        #while True:
        #    new_item_orders = exchange_neighbors()
        #    item_orders.update(new_item_orders)
        #    if not new_item_orders:
        #        break

        #while True:
        #    new_item_orders = exchange_pairs()
        #    item_orders.update(new_item_orders)
        #    if not new_item_orders:
        #        break

        #new_item_orders = greedy_solution()
        #item_orders.update(new_item_orders)

        new_item_orders = best_solution()
        item_orders.update(new_item_orders)

        for layer in self.layers:
            for item in layer.items:
                item.set_order(item_orders[item])

        crossings = get_number_of_crossings()
        print "NUMBER OF CROSSINGS:", crossings

    def placing(self):

        bounding_width = 0
        bounding_height = 0
        is_top_line = True
        layer_dimensions = {}
        for layer in self.layers:
            if is_top_line:
                is_top_line = False
            else:
                bounding_height += max(self.margins.top, self.margins.bottom)
            width = 0
            height = 0
            is_left_column = True
            for item in layer.items:
                if is_left_column:
                    is_left_column = False
                else:
                    width += max(self.margins.left, self.margins.right)
                if item.is_node:
                    width += item.node.dimensions.width
                    height = max(height, item.node.dimensions.height)
            layer_dimensions[layer] = (width, height)
            bounding_width = max(width, bounding_width)
            bounding_height += height

        is_top_line = True
        top = self.margins.top
        for layer_idx, layer in enumerate(self.layers):
            items = sorted(layer.items, key=(lambda item: item.order.value))
            layer_width, layer_height = layer_dimensions[layer]
            extra = (bounding_width - layer_width)/(len(items) + 1)
            left = self.margins.left + extra
            if is_top_line:
                is_top_line = False
            else:
                top += max(self.margins.top, self.margins.bottom)
            is_left_column = True
            for item in items:
                if is_left_column:
                    is_left_column = False
                else:
                    left += max(self.margins.left, self.margins.right) + extra

                if item.is_node:
                    node = item.node
                    x1 = left
                    y1 = top + (layer_height - node.dimensions.height)/2
                    x2 = x1 + node.dimensions.width
                    y2 = y1 + node.dimensions.height
                    node.set_position(x1, y1, x2, y2)
                    for other_layer_idx, arc_y in [(layer_idx-1, y1+1), (layer_idx+1, y2-1)]:
                        if not (0 <= other_layer_idx < len(self.layers)):
                            continue
                        other_layer = self.layers[other_layer_idx]
                        arc_orders = {}
                        for other_item in other_layer.items:
                            if other_item.is_arc:
                                arc_orders[other_item.arc] = other_item.order.value
                            else:
                                for arc in other_item.node.incoming+other_item.node.outgoing:
                                    arc_orders[arc] = other_item.order.value
                        arcs = [arc for arc in item.node.incoming+item.node.outgoing if arc in arc_orders]
                        arcs.sort(key=(lambda arc: arc_orders[arc]))
                        if arcs:
                            distance = node.dimensions.width / (len(arcs)+1)
                            arc_x = x1
                            for arc in arcs:
                                arc_x += distance
                                arc.add_vertex(arc_x, arc_y)
                    left += node.dimensions.width
                    cx = (x1+x2)/2
                    cy = (y1+y2)/2
                    for arc in node.incoming:
                        if arc.origin is node:
                            arc.add_vertex(cx, cy)
                else:
                    arc = item.arc
                    x = left
                    y = top
                    arc.add_vertex(x, y)
                    x = left
                    y = top + layer_height
                    arc.add_vertex(x, y)

            top += layer_height

        graph_width = self.margins.left + bounding_width + self.margins.right
        graph_height = self.margins.top + bounding_height + self.margins.bottom
        self.set_size(graph_width, graph_height)

    def layout(self):
        self.measuring()
        self.sorting()
        self.layering()
        self.ordering()
        self.placing()

    def draw(self, stream):
        self.layout()

        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.size.width, self.size.height)
        context = cairo.Context(surface)
        context.set_font_size(self.style.font_size)

        context.set_source_rgb(*self.style.background_color)
        context.rectangle(0, 0, self.size.width, self.size.height)
        context.fill()

        context.set_source_rgb(*self.style.arc_color)
        for arc in self.arcs:
            context.set_line_width(2.0*abs(arc.weight))
            context.new_path()
            if len(arc.vertices) > 2:
                vertex = arc.vertices[0]
                x, y = vertex.x, vertex.y
                context.move_to(x, y)
                for idx in range(1, len(arc.vertices)-1):
                    if idx == 1:
                        vertex = arc.vertices[0]
                        s_x, s_y = vertex.x, vertex.y
                    else:
                        vertex1 = arc.vertices[idx-1]
                        vertex2 = arc.vertices[idx]
                        s_x, s_y = (vertex1.x+vertex2.x)/2, (vertex1.y+vertex2.y)/2
                    if idx == len(arc.vertices)-2:
                        vertex = arc.vertices[-1]
                        e_x, e_y = vertex.x, vertex.y
                    else:
                        vertex1 = arc.vertices[idx]
                        vertex2 = arc.vertices[idx+1]
                        e_x, e_y = (vertex1.x+vertex2.x)/2, (vertex1.y+vertex2.y)/2
                    vertex = arc.vertices[idx]
                    q_x, q_y = vertex.x, vertex.y
                    x1, y1 = 1.0/3.0*s_x+2.0/3.0*q_x, 1.0/3.0*s_y+2.0/3.0*q_y
                    x2, y2 = 1.0/3.0*e_x+2.0/3.0*q_x, 1.0/3.0*e_y+2.0/3.0*q_y
                    x3, y3 = e_x, e_y
                    context.curve_to(x1, y1, x2, y2, x3, y3)
            else:
                vertex = arc.vertices[0]
                context.move_to(vertex.x, vertex.y)
                for vertex in arc.vertices[1:]:
                    context.line_to(vertex.x, vertex.y)
            context.stroke()

        context.set_source_rgb(*self.style.node_color)
        for node in self.nodes:
            position = node.position
            context.new_path()
            x = position.x1
            y = position.y1
            w = position.x2 - position.x1 + 1
            h = position.y2 - position.y1 + 1
            context.rectangle(x, y, w, h)
            context.fill()

        context.set_source_rgb(*self.style.text_color)
        for node in self.nodes:
            if node.label is not None:
                cx = (node.position.x1 + node.position.x2)/2
                cy = (node.position.y1 + node.position.y2)/2
                text = node.label.text
                extents = context.text_extents(text)
                x_bearing, y_bearing, width, height, x_advance, y_advance = extents
                x = cx - (width/2 + x_bearing)
                y = cy - (height/2 + y_bearing)
                context.move_to(x, y)
                context.show_text(text)

        surface.write_to_png(stream)


class GraphMargins(object):

    def __init__(self, graph, top, right, bottom, left):
        self.graph = graph
        self.top = top
        self.right = right
        self.bottom = bottom
        self.left = left
        graph.margins = self


class GraphStyle(object):

    def __init__(self, graph, background_color, node_color,
                arc_color, text_color, font_size):
        self.graph = graph
        self.background_color = background_color
        self.node_color = node_color
        self.arc_color = arc_color
        self.text_color = text_color
        self.font_size = font_size
        graph.style = self


class GraphSize(object):

    def __init__(self, graph, width, height):
        self.graph = graph
        self.width = width
        self.height = height
        graph.size = self


class Node(object):

    def __init__(self, graph):
        self.graph = graph
        self.incoming = []
        self.outgoing = []
        self.label = None
        self.dimensions = None
        self.position = None
        self.rank = None
        self.order = None
        self.layer_item = None
        self.index = len(graph.nodes)
        graph.nodes.append(self)

    def set_label(self, text):
        return NodeLabel(self, text)

    def set_dimensions(self, width, height):
        return NodeDimensions(self, width, height)

    def set_position(self, x1, y1, x2, y2):
        return NodePosition(self, x1, y1, x2, y2)

    def set_rank(self, value):
        return NodeRank(self, value)


class NodeLabel(object):

    def __init__(self, node, text):
        self.node = node
        self.text = text
        node.label = self


class NodeDimensions(object):

    def __init__(self, node, width, height):
        self.node = node
        self.width = width
        self.height = height
        node.dimensions = self


class NodePosition(object):

    def __init__(self, node, x1, y1, x2, y2):
        self.node = node
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
        node.position = self


class NodeRank(object):

    def __init__(self, node, value):
        self.node = node
        self.value = value
        node.rank = self


class NodeOrder(object):

    def __init__(self, node, value):
        self.node = node
        self.value = value
        node.order = self


class Arc(object):

    def __init__(self, graph, origin, target, weight):
        self.graph = graph
        self.origin = origin
        self.target = target
        self.weight = weight
        self.label = None
        self.layer_items = []
        self.vertices = []
        self.index = len(graph.arcs)
        graph.arcs.append(self)
        origin.outgoing.append(self)
        target.incoming.append(self)

    def set_label(self, text):
        return ArcLabel(self, text)

    def set_order(self, values):
        return ArcOrder(self, values)

    def add_vertex(self, x, y):
        return ArcVertex(self, x, y)


class ArcLabel(object):

    def __init__(self, arc, text):
        self.arc = arc
        self.text = text
        arc.label = self


class ArcOrder(object):

    def __init__(self, arc, values):
        self.arc = arc
        self.values = values
        arc.order = self


class ArcVertex(object):

    def __init__(self, arc, x, y):
        self.arc = arc
        self.x = x
        self.y = y
        arc.vertices.append(self)


class Layer(object):

    def __init__(self, graph):
        self.graph = graph
        self.items = []
        self.index = len(graph.layers)
        graph.layers.append(self)

    def add_node_item(self, node):
        return LayerNodeItem(self, node)

    def add_arc_item(self, arc):
        return LayerArcItem(self, arc)


class LayerNodeItem(object):

    def __init__(self, layer, node):
        self.layer = layer
        self.node = node
        self.is_node = True
        self.is_arc = False
        self.order = None
        self.index = len(layer.items)
        layer.items.append(self)
        node.layer_item = self

    def set_order(self, value):
        return LayerItemOrder(self, value)


class LayerArcItem(object):

    def __init__(self, layer, arc):
        self.layer = layer
        self.arc = arc
        self.is_node = False
        self.is_arc = True
        self.order = None
        self.index = len(layer.items)
        layer.items.append(self)
        arc.layer_items.append(self)

    def set_order(self, value):
        return LayerItemOrder(self, value)


class LayerItemOrder(object):

    def __init__(self, layer_item, value):
        self.layer_item = layer_item
        self.value = value
        layer_item.order = self