Source

grrdrr / algorithm.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


from model import (ensure, WithArcWeight, WithNodeRank, WithLayers, WithBeadOrder,
                   WithGraphSize, WithNodeDimensions, WithGraphMargins,
                   WithNodePosition, WithArcVertices)
import itertools


def rank(graph):
    ensure(graph.readonly(WithArcWeight), "without arc weights", graph)
    ensure(not graph.readable(WithNodeRank), "already with node ranks", graph)

    graph.upgrade(WithNodeRank)

    def get_cycle(forbidden):

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

        def dfs(node):
            if node in visited:
                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()
            visited.add(node)
            return None

        for node in graph.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.value + weights[arc.target]
            return total

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

    feedback = []
    arc_weights = dict((arc, arc.weight.value) for arc in graph.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(graph.nodes, key=(lambda node: node_weights[node]))
    for value, node in enumerate(ordered_nodes):
        node.set_rank(value)

    graph.freeze(WithNodeRank)

    return graph


def layer(graph):
    return layer_respecting_rank(graph)


def layer_neatly(graph):
    ensure(graph.readonly(WithNodeRank), "without node ranks", graph)
    ensure(not graph.readable(WithLayers), "already with layers", graph)

    graph.upgrade(WithLayers)

    max_nodes_per_layer = int(len(graph.nodes)**0.5)+1
    nodes = graph.nodes_by_rank[:]
    while nodes:
        candidates = []
        for node in nodes:
            for neighbor in node.neighbors:
                if neighbor in candidates:
                    break
            else:
                candidates.append(node)
                if len(candidates) > max_nodes_per_layer:
                    break
        layer = graph.add_layer()
        for node in candidates:
            layer.add_node_bead(node)
            nodes.remove(node)

    for arc in graph.arcs:
        head = min(arc.origin.layer.idx, arc.target.layer.idx) + 1
        tail = max(arc.origin.layer.idx, arc.target.layer.idx)
        for idx in range(head, tail):
            graph.layers[idx].add_arc_bead(arc)

    graph.freeze(WithLayers)

    return graph


def layer_respecting_rank(graph):
    ensure(graph.readonly(WithNodeRank), "without node ranks", graph)
    ensure(not graph.readable(WithLayers), "already with layers", graph)

    graph.upgrade(WithLayers)

    max_nodes_per_layer = int(len(graph.nodes)**0.5)+1
    nodes = graph.nodes_by_rank[:]
    while nodes:
        candidates = []
        for node in nodes:
            for neighbor in node.neighbors:
                if neighbor.rank.value < node.rank.value and neighbor.layer is None:
                    break
            else:
                candidates.append(node)
                if len(candidates) > max_nodes_per_layer:
                    break
        layer = graph.add_layer()
        for node in candidates:
            layer.add_node_bead(node)
            nodes.remove(node)

    for arc in graph.arcs:
        head = min(arc.origin.layer.idx, arc.target.layer.idx) + 1
        tail = max(arc.origin.layer.idx, arc.target.layer.idx)
        for idx in range(head, tail):
            graph.layers[idx].add_arc_bead(arc)

    graph.freeze(WithLayers)

    return graph


def order(graph):
    return order_median(graph)


def order_by_default(graph):
    ensure(graph.readonly(WithArcWeight), "without arc weights", graph)
    ensure(graph.readonly(WithLayers), "without layers", graph)
    ensure(not graph.readable(WithBeadOrder), "already with bead orders", graph)

    graph.upgrade(WithBeadOrder)

    for layer in graph.layers:
        for order, bead in enumerate(layer.beads):
            bead.set_order(order)

    graph.freeze(WithBeadOrder)

    return graph


def order_optimally(graph):
    ensure(graph.readonly(WithArcWeight), "without arc weights", graph)
    ensure(graph.readonly(WithLayers), "without layers", graph)
    ensure(not graph.readable(WithBeadOrder), "already with bead orders", graph)

    graph.upgrade(WithBeadOrder)

    layer = graph.layers[0]
    indexes = range(len(layer.beads))
    shuffles = list(itertools.permutations(indexes))
    crosses = {}
    solutions = {}
    for shuffle in shuffles:
        crosses[shuffle] = 0.0
        solutions[shuffle] = [shuffle]

    for next_layer in graph.layers[1:]:
        next_indexes = range(len(next_layer.beads))
        next_shuffles = list(itertools.permutations(next_indexes))
        next_crosses = {}
        next_solutions = {}

        weights = {}
        for idx, bead in enumerate(layer.beads):
            for next_idx, next_bead in enumerate(next_layer.beads):
                arcs = []
                if bead.is_node:
                    for arc in bead.node.incoming+bead.node.outgoing:
                        if next_bead.is_node and next_bead.node in [arc.origin, arc.target]:
                            arcs.append(arc)
                        elif next_bead.is_arc and next_bead.arc is arc:
                            arcs.append(arc)
                else:
                    if next_bead.is_node and bead.arc in next_bead.node.incoming+next_bead.node.outgoing:
                        arcs.append(bead.arc)
                    elif next_bead.is_arc and bead.arc is next_bead.arc:
                        arcs.append(bead.arc)
                weight = 0.0
                for arc in arcs:
                    weight += arc.weight.value
                weights[idx, next_idx] = weight

        for next_shuffle in next_shuffles:

            crossings = {}
            for left_idx in indexes:
                for right_idx in indexes:
                    crossing = 0.0
                    if left_idx != right_idx:
                        for next_left_idx in next_indexes:
                            left_weight = weights[left_idx, next_left_idx]
                            for next_right_idx in next_indexes:
                                right_weight = weights[right_idx, next_right_idx]
                                if next_shuffle[next_left_idx] > next_shuffle[next_right_idx]:
                                    crossing += left_weight*right_weight
                    crossings[left_idx, right_idx] = crossing

            min_cross = None
            min_solution = None

            for shuffle in shuffles:
                cross = crosses[shuffle]
                for left_idx in indexes:
                    for right_idx in indexes:
                        if shuffle[left_idx] < shuffle[right_idx]:
                            cross += crossings[left_idx, right_idx]
                if min_cross is None or cross < min_cross:
                    min_cross = cross
                    min_solution = solutions[shuffle]

            next_crosses[next_shuffle] = min_cross
            next_solutions[next_shuffle] = min_solution+[next_shuffle]

        layer = next_layer
        indexes = next_indexes
        shuffles = next_shuffles
        crosses = next_crosses
        solutions = next_solutions

    min_cross = None
    min_solution = None
    for shuffle in shuffles:
        cross = crosses[shuffle]
        if min_cross is None or cross < min_cross:
            min_cross = cross
            min_solution = solutions[shuffle]

    for layer, shuffle in zip(graph.layers, min_solution):
        for bead, value in zip(layer.beads, shuffle):
            bead.set_order(value)

    graph.freeze(WithBeadOrder)

    return graph


def order_dfs(graph):
    ensure(graph.readonly(WithLayers), "without layers", graph)
    ensure(not graph.readable(WithBeadOrder), "already with bead orders", graph)

    graph.upgrade(WithBeadOrder)

    next_order_by_layer = {}
    for layer in graph.layers:
        next_order_by_layer[layer] = 0

    stack = []
    stack.extend(reversed(graph.beads))
    while stack:
        bead = stack.pop()
        if bead.order is not None:
            continue
        value = next_order_by_layer[bead.layer]
        bead.set_order(value)
        next_order_by_layer[bead.layer] = value+1
        stack.extend(bead.neighbors)

    graph.freeze(WithBeadOrder)

    return graph


def order_transpose(graph):
    ensure(graph.readonly(WithLayers), "without layers", graph)
    ensure(not graph.readable(WithBeadOrder), "already with bead orders", graph)

    graph.upgrade(WithBeadOrder)

    weights = {}
    layer = graph.layers[0]
    for next_layer in graph.layers[1:]:
        for bead in layer.beads:
            for next_bead in next_layer.beads:
                arcs = []
                if bead.is_node:
                    for arc in bead.node.incoming+bead.node.outgoing:
                        if next_bead.is_node and next_bead.node in [arc.origin, arc.target]:
                            arcs.append(arc)
                        elif next_bead.is_arc and next_bead.arc is arc:
                            arcs.append(arc)
                else:
                    if next_bead.is_node and bead.arc in next_bead.node.incoming+next_bead.node.outgoing:
                        arcs.append(bead.arc)
                    elif next_bead.is_arc and bead.arc is next_bead.arc:
                        arcs.append(bead.arc)
                weight = 0.0
                for arc in arcs:
                    weight += arc.weight.value
                weights[bead, next_bead] = weight
        layer = next_layer

    order_by_bead = {}
    next_order_by_layer = {}
    for layer in graph.layers:
        next_order_by_layer[layer] = 0
    stack = []
    stack.extend(reversed(graph.beads))
    while stack:
        bead = stack.pop()
        if bead in order_by_bead:
            continue
        value = next_order_by_layer[bead.layer]
        order_by_bead[bead] = value
        next_order_by_layer[bead.layer] = value+1
        stack.extend(bead.neighbors)

    improved = True
    while improved:
        improved = False
        for prev_layer, layer, next_layer in zip([None]+graph.layers[:-1], graph.layers, graph.layers[1:]+[None]):
            prev_beads = None
            if prev_layer is not None:
                prev_beads = sorted(prev_layer.beads, key=(lambda bead: order_by_bead[bead]))
            beads = sorted(layer.beads, key=(lambda bead: order_by_bead[bead]))
            next_beads = None
            if next_layer is not None:
                next_beads = sorted(next_layer.beads, key=(lambda bead: order_by_bead[bead]))
            for idx in range(len(beads)-1):
                left = beads[idx]
                right = beads[idx+1]
                direct = 0.0
                reverse = 0.0
                if prev_beads is not None:
                    for left_neighbor in prev_beads:
                        left_weight = weights[left_neighbor, left]
                        for right_neighbor in prev_beads:
                            right_weight = weights[right_neighbor, right]
                            if order_by_bead[left_neighbor] > order_by_bead[right_neighbor]:
                                direct += left_weight*right_weight
                            if order_by_bead[left_neighbor] < order_by_bead[right_neighbor]:
                                reverse += left_weight*right_weight
                if next_beads is not None:
                    for left_neighbor in next_beads:
                        left_weight = weights[left, left_neighbor]
                        for right_neighbor in next_beads:
                            right_weight = weights[right, right_neighbor]
                            if order_by_bead[left_neighbor] > order_by_bead[right_neighbor]:
                                direct += left_weight*right_weight
                            if order_by_bead[left_neighbor] < order_by_bead[right_neighbor]:
                                reverse += left_weight*right_weight
                if reverse < direct or (reverse == direct and left.idx < right.idx):
                    beads[idx] = right
                    beads[idx+1] = left
                    order_by_bead[left] = idx+1
                    order_by_bead[right] = idx
                    improved = True

    for bead in graph.beads:
        value = order_by_bead[bead]
        bead.set_order(value)

    graph.freeze(WithBeadOrder)

    return graph


def order_median(graph):
    ensure(graph.readonly(WithLayers), "without layers", graph)
    ensure(not graph.readable(WithBeadOrder), "already with bead orders", graph)

    graph.upgrade(WithBeadOrder)

    weights = {}
    layer = graph.layers[0]
    for next_layer in graph.layers[1:]:
        for bead in layer.beads:
            for next_bead in next_layer.beads:
                arcs = []
                if bead.is_node:
                    for arc in bead.node.incoming+bead.node.outgoing:
                        if next_bead.is_node and next_bead.node in [arc.origin, arc.target]:
                            arcs.append(arc)
                        elif next_bead.is_arc and next_bead.arc is arc:
                            arcs.append(arc)
                else:
                    if next_bead.is_node and bead.arc in next_bead.node.incoming+next_bead.node.outgoing:
                        arcs.append(bead.arc)
                    elif next_bead.is_arc and bead.arc is next_bead.arc:
                        arcs.append(bead.arc)
                weight = 0.0
                for arc in arcs:
                    weight += arc.weight.value
                weights[bead, next_bead] = weight
                weights[next_bead, bead] = weight
        layer = next_layer

    order_by_bead = {}
    next_order_by_layer = {}
    for layer in graph.layers:
        next_order_by_layer[layer] = 0
    stack = []
    stack.extend(reversed(graph.beads))
    while stack:
        bead = stack.pop()
        if bead in order_by_bead:
            continue
        value = next_order_by_layer[bead.layer]
        order_by_bead[bead] = value
        next_order_by_layer[bead.layer] = value+1
        stack.extend(bead.neighbors)

    next_layouts = zip(graph.layers[1:], graph.layers[:-1])
    current_layouts = zip(graph.layers[:-1][::-1], graph.layers[1:][::-1])
    for count in range(len(graph.beads)):
        current_layouts, next_layouts = next_layouts, current_layouts

        for layer, opposite_layer in current_layouts:
            beads = sorted(layer.beads, key=(lambda bead: order_by_bead[bead]))
            medians = {}
            for bead in beads:
                neighbors = sorted(order_by_bead[neighbor]
                                  for neighbor in opposite_layer.beads if weights[bead,neighbor] > 0.0)
                if not neighbors:
                    value = order_by_bead[bead]
                else:
                    length = len(neighbors)
                    if length % 2 == 1:
                        value = neighbors[length/2]
                    elif length == 2:
                        value = 0.5*sum(neighbors)
                    else:
                        l = neighbors[length/2-1] - neighbors[0]
                        r = neighbors[-1] - neighbors[length/2]
                        value = 1.0*(l*neighbors[length/2-1]+r*neighbors[length/2])/(l+r)
                medians[bead] = value
            beads = sorted(beads, key=(lambda bead: medians[bead]))
            for idx, bead in enumerate(beads):
                order_by_bead[bead] = idx

        improved = True
        while improved:
            improved = False
            for prev_layer, layer, next_layer in zip([None]+graph.layers[:-1],
                                                     graph.layers,
                                                     graph.layers[1:]+[None])[::-1]:
                beads = sorted(layer.beads, key=(lambda bead: order_by_bead[bead]))
                for idx in range(len(beads)-1):
                    left = beads[idx]
                    right = beads[idx+1]
                    direct = 0.0
                    reverse = 0.0
                    for opposite_layer in [prev_layer, next_layer]:
                        if opposite_layer is None:
                            continue
                        for left_neighbor in opposite_layer.beads:
                            left_weight = weights[left_neighbor, left]
                            for right_neighbor in opposite_layer.beads:
                                right_weight = weights[right_neighbor, right]
                                if order_by_bead[left_neighbor] > order_by_bead[right_neighbor]:
                                    direct += left_weight*right_weight
                                if order_by_bead[left_neighbor] < order_by_bead[right_neighbor]:
                                    reverse += left_weight*right_weight
                    if reverse < direct:
                        beads[idx] = right
                        beads[idx+1] = left
                        order_by_bead[left] = idx+1
                        order_by_bead[right] = idx
                        improved = True

    for bead in graph.beads:
        value = order_by_bead[bead]
        bead.set_order(value)

    graph.freeze(WithBeadOrder)

    return graph


def place(graph):
    return place_simplex(graph)


def place_uniform(graph):
    ensure(graph.readonly(WithLayers), "without layers", graph)
    ensure(graph.readonly(WithBeadOrder), "without bead orders", graph)
    ensure(graph.readonly(WithNodeDimensions), "without node dimensions", graph)
    ensure(graph.readonly(WithGraphMargins), "without graph margins", graph)
    ensure(not graph.readable(WithGraphSize), "already with graph size", graph)
    ensure(not graph.readable(WithNodePosition), "already with node positions", graph)
    ensure(not graph.readable(WithArcVertices), "already with arc vertices", graph)

    graph.upgrade(WithGraphSize)
    graph.upgrade(WithNodePosition)
    graph.upgrade(WithArcVertices)

    width = graph.margins.horizontal
    height = graph.margins.vertical
    for layer in graph.layers:
        layer_width = (len(layer.beads)+1)*graph.margins.horizontal
        layer_height = 0
        for bead in layer.beads:
            if bead.is_node:
                layer_width += bead.node.dimensions.width
        for bead in layer.beads:
            if bead.is_node:
                layer_height = max(layer_height, bead.node.dimensions.height)
        width = max(width, layer_width)
        height += layer_height+graph.margins.vertical
    graph.set_size(width, height)

    top = graph.margins.vertical
    for layer in graph.layers:
        left = graph.margins.horizontal
        height = 0
        density = 0
        for bead in layer.beads:
            if bead.is_node:
                height = max(height, bead.node.dimensions.height)
                density += bead.node.dimensions.width
        spread = 0
        if len(layer.beads) > 1:
            spread = (graph.size.width-2*graph.margins.horizontal-density) / (len(layer.beads)-1)
        else:
            left += (graph.size.width-2*graph.margins.horizontal-density) / 2
        for bead in layer.beads_by_order:
            if bead.is_node:
                w = bead.node.dimensions.width
                h = bead.node.dimensions.height
                x = left
                y = top + (height-h)/2
                cx = x+w/2
                cy = y+h/2
                bead.node.set_position(x, y, w, h)
                for arc in bead.node.incoming+bead.node.outgoing:
                    arc.add_vertex(cx, cy)
                left += w+spread
            if bead.is_arc:
                x = left
                y = top + height/2
                bead.arc.add_vertex(x, y)
                left += spread
        top += height+graph.margins.vertical

    graph.freeze(WithGraphSize)
    graph.freeze(WithNodePosition)
    graph.freeze(WithArcVertices)

    return graph


def debug_simplex(A, B, C):
    M = len(B)
    N = len(C)
    print
    print "A:"
    for i in range(M):
        for j in range(N):
            print A[i,j],
        print
    print "B:"
    for i in range(M):
        print B[i],
    print
    print "C:"
    for j in range(N):
        print C[j],
    print

def simplex(A, B, C):
    M = len(B)
    N = len(C)
    A = dict((key, float(A[key])) for key in A)
    B = [float(b) for b in B]
    C = [float(-c) for c in C]
    X = [i for i in range(M)]
    Y = [None for j in range(N)]
    #debug_simplex(A, B, C)

    eps = 1e-5
    assert all(b >= -eps for b in B)
    while not all(c >= -eps for c in C):
        i0 = None
        j0 = None
        for j in range(N):
            if C[j] < -eps:
                j0 = j
                break
        for i in range(M):
            if A[i,j0] > eps:
                if i0 is None or B[i]/A[i,j0] < B[i0]/A[i0,j0]:
                    i0 = i
        assert i0 is not None
        AA = {}
        BB = [None]*M
        CC = [None]*N
        for i in range(M):
            for j in range(N):
                if i == i0 and j == j0:
                    AA[i,j] = 1/A[i0,j0]
                elif i == i0:
                    AA[i,j] = A[i,j]/A[i0,j0]
                elif j == j0:
                    AA[i,j] = -A[i,j]/A[i0,j0]
                else:
                    AA[i,j] = A[i,j]-A[i0,j]*A[i,j0]/A[i0,j0]
        for i in range(M):
            if i == i0:
                BB[i] = B[i]/A[i0,j0]
            else:
                BB[i] = B[i]-B[i0]*A[i,j0]/A[i0,j0]
        for j in range(N):
            if j == j0:
                CC[j] = -C[j]/A[i0,j0]
            else:
                CC[j] = C[j]-A[i0,j]*C[j0]/A[i0,j0]
        A, B, C = AA, BB, CC
        X[i0], Y[j0] = Y[j0], X[i0]
        #print
        #print "pivot:", (i0, j0)
        #debug_simplex(A, B, C)

    #debug_simplex(A, B, C)
    solution = [0]*M
    for y, c in zip(Y, C):
        if y is not None:
            solution[y] = int(c)
    #print "solution:", solution
    return solution


def place_simplex(graph):
    ensure(graph.readonly(WithLayers), "without layers", graph)
    ensure(graph.readonly(WithBeadOrder), "without bead orders", graph)
    ensure(graph.readonly(WithNodeDimensions), "without node dimensions", graph)
    ensure(graph.readonly(WithGraphMargins), "without graph margins", graph)
    ensure(not graph.readable(WithGraphSize), "already with graph size", graph)
    ensure(not graph.readable(WithNodePosition), "already with node positions", graph)
    ensure(not graph.readable(WithArcVertices), "already with arc vertices", graph)

    graph.upgrade(WithGraphSize)
    graph.upgrade(WithNodePosition)
    graph.upgrade(WithArcVertices)

    A = {}
    B = []
    C = []
    delta = graph.margins.horizontal
    for layer in graph.layers:
        beads = layer.beads_by_order
        bead = beads[0]
        for next_bead in beads[1:]:
            c = delta
            if bead.is_node:
                c += bead.node.dimensions.width/2
            if next_bead.is_node:
                c += next_bead.node.dimensions.width/2
            i1 = bead.idx
            i2 = next_bead.idx
            j = len(C)
            A[i1,j] = -1
            A[i2,j] = +1
            C.append(c)
            bead = next_bead
    B += [0]*len(graph.beads)
    layer = graph.layers[0]
    for next_layer in graph.layers[1:]:
        for bead in layer.beads:
            for next_bead in next_layer.beads:
                arcs = []
                if bead.is_node:
                    for arc in bead.node.incoming+bead.node.outgoing:
                        if next_bead.is_node and next_bead.node in [arc.origin, arc.target]:
                            arcs.append(arc)
                        elif next_bead.is_arc and next_bead.arc is arc:
                            arcs.append(arc)
                else:
                    if next_bead.is_node and bead.arc in next_bead.node.incoming+next_bead.node.outgoing:
                        arcs.append(bead.arc)
                    elif next_bead.is_arc and bead.arc is next_bead.arc:
                        arcs.append(bead.arc)
                b = 0.0
                for arc in arcs:
                    b += arc.weight.value
                if bead.is_arc and next_bead.is_arc:
                    b *= 8
                elif bead.is_arc or next_bead.is_arc:
                    b *= 4
                if b:
                    i1 = bead.idx
                    i2 = next_bead.idx
                    i3 = len(B)
                    j1 = len(C)
                    j2 = len(C)+1
                    A[i1,j1] = -1
                    A[i2,j1] = +1
                    A[i3,j1] = +1
                    A[i1,j2] = +1
                    A[i2,j2] = -1
                    A[i3,j2] = +1
                    B.append(b)
                    C.append(0)
                    C.append(0)
        layer = next_layer
    for i in range(len(B)):
        for j in range(len(C)):
            if (i,j) not in A:
                A[i,j] = 0

    centers = simplex(A, B, C)
    left = None
    right = None
    for bead in graph.beads:
        l = r = centers[bead.idx]
        if bead.is_node:
            l -= bead.node.dimensions.width/2
            r += bead.node.dimensions.width/2
        if left is None or l < left:
            left = l
        if right is None or r > right:
            right = r
    width = graph.margins.horizontal*2 + (right-left)
    height = graph.margins.vertical
    for layer in graph.layers:
        layer_height = 0
        for bead in layer.beads:
            if bead.is_node:
                layer_height = max(layer_height, bead.node.dimensions.height)
        height += layer_height+graph.margins.vertical
    graph.set_size(width, height)
    shift = graph.margins.horizontal-left

    top = graph.margins.vertical
    for layer in graph.layers:
        height = 0
        for bead in layer.beads:
            if bead.is_node:
                height = max(height, bead.node.dimensions.height)
        for bead in layer.beads_by_order:
            if bead.is_node:
                w = bead.node.dimensions.width
                h = bead.node.dimensions.height
                x = shift+centers[bead.idx]-w/2
                y = top + (height-h)/2
                cx = x+w/2
                cy = y+h/2
                bead.node.set_position(x, y, w, h)
                for arc in bead.node.incoming+bead.node.outgoing:
                    arc.add_vertex(cx, cy)
            if bead.is_arc:
                x = shift+centers[bead.idx]
                y = top + height/2
                bead.arc.add_vertex(x, y)
        top += height+graph.margins.vertical

    graph.freeze(WithGraphSize)
    graph.freeze(WithNodePosition)
    graph.freeze(WithArcVertices)

    return graph