Source

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


class ModelError(Exception):
    pass


def ensure(condition, *message):
    if not condition:
        raise ModelError(*message)


class Model(object):

    class __metaclass__(type):

        def __new__(meta, name, bases, attrs):
            cls = type.__new__(meta, name, bases, attrs)
            cls.components = []
            return cls

        def __call__(cls, component):
            cls.components.append(component)
            return component

        def supports(cls, model):
            return (model is cls or any(base.supports(model)
                                        for base in cls.__bases__ if base is not object))

        @staticmethod
        def close(models):
            closure = []
            def dfs(model):
                if model in closure or model is object:
                    return
                for base in model.__bases__:
                    dfs(base)
                closure.append(model)
            for model in models:
                dfs(model)
            return closure

        @staticmethod
        def construct(models, include, exclude=[]):
            name = include[0].__name__
            bases = []
            for model in models:
                for component in model.components:
                    if (any(issubclass(component, root) for root in include)
                            and not any(issubclass(component, root) for root in exclude)):
                        bases.append(component)
            bases = tuple(reversed(bases))
            return type(name, bases, {})

        def __str__(cls):
            return "%s{%s}" % (cls.__name__, ", ".join(component.__name__
                                                       for component in cls.components))
        def __repr__(cls):
            return "<%s>" % cls


@Model
class ModelEntity(object):

    def __init__(self):
        self.all_models = [Model]
        self.frozen_models = [Model]

    @staticmethod
    def build(*models):
        closure = Model.close(models)
        entity = ModelEntity()
        for model in closure:
            if model not in entity.all_models:
                entity.initialize(model)
        return entity

    def clone(self):
        entity = ModelEntity()
        for model in self.all_models:
            if model not in entity.all_models:
                entity.initialize(model)
            entity.relocate(self, model)
            if model in self.frozen_models:
                entity.finalize(model)
        return entity

    def upgrade(self, *models):
        closure = Model.close(models)
        for model in closure:
            if model not in self.all_models:
                self.initialize(model)

    def freeze(self, *models):
        if models:
            closure = Model.close(models)
        else:
            closure = self.all_models
        for model in closure:
            if model not in self.all_models:
                self.initialize(model)
            if model not in self.frozen_models:
                self.finalize(model)

    def readable(self, *models):
        return all(model in self.all_models for model in models)

    def readonly(self, *models):
        return all(model in self.frozen_models for model in models)

    def writable(self, *models):
        return all(model in self.all_models and model not in self.frozen_models
                   for model in models)

    def initialize(self, model):
        if model not in self.all_models:
            self.all_models.append(model)
            self.__class__ = Model.construct(self.all_models, [ModelEntity])
            self.initialize(model)

    def finalize(self, model):
        self.frozen_models.append(model)

    def relocate(self, sample, model):
        pass

    def __str__(self):
        return "{%s}" % ", ".join("%s%s" % (model.__name__, "*" if model not in self.frozen_models else "")
                                  for model in self.all_models)

    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self)


class WithGraph(Model):
    pass


@WithGraph
class Graph(ModelEntity):

    def add_node(self):
        ensure(self.writable(WithGraph), "nodes are not writable", self)
        node = self.Node(self)
        for model in self.all_models:
            if model.supports(WithGraph):
                node.initialize(model)
        return node

    def add_arc(self, origin, target):
        ensure(self.writable(WithGraph), "arcs are not writable", self)
        arc = self.Arc(self, origin, target)
        for model in self.all_models:
            if model.supports(WithGraph):
                arc.initialize(model)
        return arc

    def initialize(self, model):
        if model not in self.all_models:
            return super(Graph, self).initialize(model)
        super(Graph, self).initialize(model)
        if model is WithGraph:
            self.graph = self
            self.nodes = []
            self.arcs = []
        if model.supports(WithGraph):
            self.Graph = Model.construct(self.all_models, [Graph])
            self.Node = Model.construct(self.all_models, [Node])
            self.Arc = Model.construct(self.all_models, [Arc])
            self.__class__ = self.Graph
            for node in self.nodes:
                node.__class__ = self.Node
                node.initialize(model)
            for arc in self.arcs:
                arc.__class__ = self.Arc
                arc.initialize(model)

    def finalize(self, model):
        super(Graph, self).finalize(model)
        if model.supports(WithGraph):
            for node in self.nodes:
                node.finalize(model)
            for arc in self.arcs:
                arc.finalize(model)

    def relocate(self, sample, model):
        if model is WithGraph:
            for sample_node in sample.nodes:
                self.Node(self)
            for sample_arc in sample.arcs:
                self.Arc(self, self.nodes[sample_arc.origin.idx], self.nodes[sample_arc.target.idx])
        if model.supports(WithGraph):
            for node, sample_node in zip(self.nodes, sample.nodes):
                node.initialize(model)
                node.relocate(sample_node, model)
            for arc, sample_arc in zip(self.arcs, sample.arcs):
                arc.initialize(model)
                arc.relocate(sample_arc, model)

    def __str__(self):
        return "%s:(nodes: %s, arcs: %s)" % (super(Graph, self).__str__(), len(self.nodes), len(self.arcs))

    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self)


@WithGraph
class Node(object):

    def __init__(self, graph):
        self.graph = graph
        self.idx = len(graph.nodes)
        graph.nodes.append(self)

    def initialize(self, model):
        if model is WithGraph:
            self.incoming = []
            self.outgoing = []
            self.origins = []
            self.targets = []
            self.neighbors = []

    def finalize(self, model):
        pass

    def relocate(self, sample, model):
        pass

    def __str__(self):
        return "%s" % self.idx

    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self)


@WithGraph
class Arc(object):

    def __init__(self, graph, origin, target):
        ensure(origin.graph is graph and target.graph is graph,
                "inconsistent origin and target nodes", graph, origin, target)
        self.graph = graph
        self.idx = len(graph.arcs)
        graph.arcs.append(self)
        self.origin = origin
        self.target = target

    def initialize(self, model):
        if model is WithGraph:
            self.origin.outgoing.append(self)
            self.target.incoming.append(self)
            self.origin.targets.append(self.target)
            self.target.origins.append(self.origin)
            self.origin.neighbors.append(self.target)
            self.target.neighbors.append(self.origin)

    def finalize(self, model):
        pass

    def relocate(self, sample, model):
        pass

    def __str__(self):
        return "%s:(%s->%s)" % (self.idx, self.origin, self.target)

    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self)


def inject_property(ModelClass, ComponentClass, PropertyClass, mandatory=False):
    name = PropertyClass.__name__.lower()

    def set_property(self, *args, **kwds):
        ensure(self.graph.writable(ModelClass), "%s is not writable" % name, self)
        ensure(getattr(self, name) is None, "%s is already set" % name, self)
        setattr(self, name, PropertyClass(*args, **kwds))
        return self
    set_property.__name__ = "set_%s" % name

    def initialize(self, model):
        if model not in self.graph.all_models:
            return super(ComponentClass, self).initialize(model)
        super(ComponentClass, self).initialize(model)
        if model is ModelClass:
            setattr(self, name, None)

    def finalize(self, model):
        super(ComponentClass, self).finalize(model)
        if model is ModelClass:
            if mandatory:
                ensure(getattr(self, name) is not None, "%s is not set" % name, self)
            else:
                if getattr(self, name) is None:
                    setattr(self, name, PropertyClass())

    def relocate(self, sample, model):
        super(ComponentClass, self).relocate(sample, model)
        if model is ModelClass:
            setattr(self, name, getattr(sample, name))

    setattr(ComponentClass, set_property.__name__, set_property)
    ComponentClass.initialize = initialize
    ComponentClass.finalize = finalize
    ComponentClass.relocate = relocate


class Label(object):

    def __init__(self, text=None):
        if text is None:
            text = ""
        self.text = text


class WithGraphLabel(WithGraph):
    pass


@WithGraphLabel
class GraphWithLabel(Graph):

    def __str__(self):
        return "%s:%s" % (super(GraphWithLabel, self).__str__(),
                            repr(self.label.text) if self.label is not None else "")


inject_property(WithGraphLabel, GraphWithLabel, Label)


class WithNodeLabel(WithGraph):
    pass


@WithNodeLabel
class NodeWithLabel(Node):

    def __str__(self):
        return "%s:%s" % (super(NodeWithLabel, self).__str__(),
                            repr(self.label.text) if self.label is not None else "")


inject_property(WithNodeLabel, NodeWithLabel, Label)


class WithArcLabel(WithGraph):
    pass


@WithArcLabel
class ArcWithLabel(Arc):

    def __str__(self):
        return "%s:%s" % (super(ArcWithLabel, self).__str__(),
                            repr(self.label.text) if self.label is not None else "")


inject_property(WithArcLabel, ArcWithLabel, Label)


class Weight(object):

    def __init__(self, value=None):
        if value is None:
            value = 0.0
        self.value = value


class WithArcWeight(WithGraph):
    pass


@WithArcWeight
class ArcWithWeight(Arc):
    pass


inject_property(WithArcWeight, ArcWithWeight, Weight)


class Polarity(object):

    def __init__(self, value=None):
        if value is None:
            value = 0
        self.value = value


class WithArcPolarity(WithGraph):
    pass


@WithArcPolarity
class ArcWithPolarity(Arc):
    pass


inject_property(WithArcPolarity, ArcWithPolarity, Polarity)


class Style(object):

    def __init__(self, background_color=None, node_color=None, border_color=None, arc_color=None, text_color=None,
                 font_size=None, border_width=None, arc_width=None):
        if background_color is None:
            background_color = (1.0, 1.0, 1.0)
        if node_color is None:
            node_color = (1.0, 1.0, 1.0)
        if border_color is None:
            border_color = (0.0, 0.0, 0.0)
        if arc_color is None:
            arc_color = (0.0, 0.0, 0.0)
        if text_color is None:
            text_color = (0.0, 0.0, 0.0)
        if font_size is None:
            font_size = 12.0
        if border_width is None:
            border_width = 1.0
        if arc_width is None:
            arc_width = 1.0
        self.background_color = background_color
        self.node_color = node_color
        self.border_color = border_color
        self.arc_color = arc_color
        self.text_color = text_color
        self.font_size = font_size
        self.border_width = border_width
        self.arc_width = arc_width


class WithGraphStyle(WithGraph):
    pass


@WithGraphStyle
class GraphWithStyle(Graph):
    pass


inject_property(WithGraphStyle, GraphWithStyle, Style)


class Dimensions(object):

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


class WithNodeDimensions(WithGraph):
    pass


@WithNodeDimensions
class NodeWithDimensions(Node):
    pass


inject_property(WithNodeDimensions, NodeWithDimensions, Dimensions, True)


class Rank(object):

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


class WithNodeRank(WithGraph):
    pass


@WithNodeRank
class GraphWithNodeRank(Graph):

    @property
    def nodes_by_rank(self):
        return sorted(self.nodes, key=(lambda node: node.rank.value if node.rank is not None else -1))


@WithNodeRank
class NodeWithRank(Node):
    pass


inject_property(WithNodeRank, NodeWithRank, Rank, True)


class WithLayers(WithGraph):
    pass


@WithLayers
class GraphWithLayers(Graph):

    def add_layer(self):
        ensure(self.writable(WithLayers), "layers are not writable", self)
        layer = self.Layer(self)
        for model in self.all_models:
            if model.supports(WithLayers):
                layer.initialize(model)
        return layer

    def initialize(self, model):
        if model not in self.all_models:
            return super(GraphWithLayers, self).initialize(model)
        super(GraphWithLayers, self).initialize(model)
        if model is WithLayers:
            self.layers = []
            self.beads = []
        if model.supports(WithLayers):
            self.Layer = Model.construct(self.all_models, [Layer])
            self.NodeBead = Model.construct(self.all_models, [NodeBead, Bead], [ArcBead])
            self.ArcBead = Model.construct(self.all_models, [ArcBead, Bead], [NodeBead])
            for layer in self.layers:
                layer.__class__ = self.Layer
                layer.initialize(model)
            for bead in self.beads:
                if bead.is_node:
                    bead.__class__ = self.NodeBead
                if bead.is_arc:
                    bead.__class__ = self.ArcBead
                bead.initialize(model)

    def finalize(self, model):
        super(GraphWithLayers, self).finalize(model)
        if model.supports(WithLayers):
            for layer in self.layers:
                layer.finalize(model)
            for bead in self.beads:
                bead.finalize(model)

    def relocate(self, sample, model):
        super(GraphWithLayers, self).relocate(sample, model)
        if model is WithLayers:
            for sample_layer in sample.layers:
                self.Layer(self)
            for sample_bead in sample.beads:
                if sample_bead.is_node:
                    self.NodeBead(self, self.layers[sample_bead.layer.idx], self.nodes[sample_bead.node.idx])
                if sample_bead.is_arc:
                    self.ArcBead(self, self.layers[sample_bead.layer.idx], self.arcs[sample_bead.arc.idx])
        if model.supports(WithLayers):
            for layer, sample_layer in zip(self.layers, sample.layers):
                layer.initialize(model)
                layer.relocate(sample_layer, model)
            for bead, sample_bead in zip(self.beads, sample.beads):
                bead.initialize(model)
                bead.relocate(sample_bead, model)


@WithLayers
class NodeWithLayers(Node):

    def initialize(self, model):
        super(NodeWithLayers, self).initialize(model)
        if model is WithLayers:
            self.bead = None
            self.layer = None

    def finalize(self, model):
        super(NodeWithLayers, self).finalize(model)
        if model is WithLayers:
            ensure(self.bead is not None, "node bead is not set", self)


@WithLayers
class ArcWithLayers(Arc):

    def initialize(self, model):
        super(ArcWithLayers, self).initialize(model)
        if model is WithLayers:
            self.beads = []
            self.layers = []

    def finalize(self, model):
        super(ArcWithLayers, self).finalize(model)
        if model is WithLayers:
            ensure(self.origin.layer != self.target.layer or self.origin == self.target, "flat arc", self)
            head = min(self.origin.layer.idx, self.target.layer.idx)+1
            tail = max(self.origin.layer.idx, self.target.layer.idx)
            ensure(self.layers == [self.graph.layers[idx] for idx in range(head, tail)], "arc beads are not set", self)


@WithLayers
class Layer(object):

    def __init__(self, graph):
        self.graph = graph
        self.idx = len(graph.layers)
        graph.layers.append(self)

    def add_node_bead(self, node):
        ensure(self.graph.writable(WithLayers), "layers are not writable", self)
        ensure(node.bead is None, "node bead is already added", node)
        bead = self.graph.NodeBead(self.graph, self, node)
        for model in self.graph.all_models:
            if model.supports(WithLayers):
                bead.initialize(model)
        for neighbor in bead.neighbors:
            neighbor.neighbors.append(bead)
        return bead

    def add_arc_bead(self, arc):
        ensure(self.graph.writable(WithLayers), "layers are not writable", self)
        ensure(self not in arc.layers, "arc bead is already added", arc)
        bead = self.graph.ArcBead(self.graph, self, arc)
        for model in self.graph.all_models:
            if model.supports(WithLayers):
                bead.initialize(model)
        for neighbor in bead.neighbors:
            neighbor.neighbors.append(bead)
        return bead

    def initialize(self, model):
        if model is WithLayers:
            self.beads = []

    def finalize(self, model):
        if model is WithLayers:
            ensure(self.beads, "layer is empty", self)

    def relocate(self, sample, model):
        pass

    def __str__(self):
        return "%s" % self.idx

    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self)


@WithLayers
class Bead(object):

    is_node = False
    is_arc = False

    def __init__(self, graph):
        self.graph = graph
        self.idx = len(graph.beads)
        graph.beads.append(self)

    def initialize(self, model):
        pass

    def finalize(self, model):
        pass

    def relocate(self, sample, model):
        pass

    def __str__(self):
        return "%s" % self.idx

    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, self)


@WithLayers
class NodeBead(Bead):

    is_node = True

    def __init__(self, graph, layer, node):
        ensure(graph is layer.graph and graph is node.graph, "inconsistent layer and node", graph, layer, node)
        super(NodeBead, self).__init__(graph)
        self.layer = layer
        self.node = node

    def initialize(self, model):
        super(NodeBead, self).initialize(model)
        if model is WithLayers:
            self.layer.beads.append(self)
            self.node.bead = self
            self.node.layer = self.layer
            self.neighbors = []
            for bead in self.graph.beads:
                if bead.layer.idx in [self.layer.idx+1, self.layer.idx-1]:
                    if bead.is_node and bead.node in self.node.neighbors:
                        self.neighbors.append(bead)
                    if bead.is_arc and bead.arc in self.node.incoming+self.node.outgoing:
                        self.neighbors.append(bead)

    def __str__(self):
        return "%s:<%s>:[%s]" % (super(NodeBead, self).__str__(), self.layer, self.node)


@WithLayers
class ArcBead(Bead):

    is_arc = True

    def __init__(self, graph, layer, arc):
        ensure(graph is layer.graph and graph is arc.graph, "inconsistent layer and arc", graph, layer, arc)
        super(ArcBead, self).__init__(graph)
        self.layer = layer
        self.arc = arc

    def initialize(self, model):
        super(ArcBead, self).initialize(model)
        if model is WithLayers:
            self.layer.beads.append(self)
            self.arc.beads.append(self)
            self.arc.layers.append(self.layer)
            self.neighbors = []
            for bead in self.graph.beads:
                if bead.layer.idx in [self.layer.idx+1, self.layer.idx-1]:
                    if bead.is_node and bead.node in [self.arc.origin, self.arc.target]:
                        self.neighbors.append(bead)
                    if bead.is_arc and bead.arc is self.arc:
                        self.neighbors.append(bead)

    def __str__(self):
        return "%s:<%s>:[%s]" % (super(ArcBead, self).__str__(), self.layer, self.arc)


class Order(object):

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


class WithBeadOrder(WithLayers):
    pass


@WithBeadOrder
class LayerWithBeadOrder(Layer):

    @property
    def beads_by_order(self):
        return sorted(self.beads, key=(lambda bead: bead.order.value if bead.order is not None else -1))


@WithBeadOrder
class BeadWithOrder(Bead):
    pass


inject_property(WithBeadOrder, BeadWithOrder, Order, True)


class Size(object):

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


class WithGraphSize(WithGraph):
    pass


@WithGraphSize
class GraphWithSize(Graph):
    pass


inject_property(WithGraphSize, GraphWithSize, Size, True)


class Margins(object):

    def __init__(self, horizontal, vertical):
        self.horizontal = horizontal
        self.vertical = vertical


class WithGraphMargins(WithGraph):
    pass


@WithGraphMargins
class GraphWithMargins(Graph):
    pass


inject_property(WithGraphMargins, GraphWithMargins, Margins, True)


class Position(object):

    def __init__(self, x, y, w, h):
        self.x = x
        self.y = y
        self.w = w
        self.h = h


class WithNodePosition(WithGraph):
    pass


@WithNodePosition
class NodeWithPosition(Node):
    pass


inject_property(WithNodePosition, NodeWithPosition, Position, True)


class Vertex(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y


class WithArcVertices(WithGraph):
    pass


@WithArcVertices
class ArcWithVertices(Arc):

    def add_vertex(self, x, y):
        ensure(self.graph.writable(WithArcVertices), "vertices are not writable", self)
        self.vertices.append(Vertex(x, y))
        return self

    def initialize(self, model):
        super(ArcWithVertices, self).initialize(model)
        if model is WithArcVertices:
            self.vertices = []

    def finalize(self, model):
        super(ArcWithVertices, self).finalize(model)
        if model is WithArcVertices:
            ensure(len(self.vertices) >= 2, "vertices are not set", self)

    def relocate(self, sample, model):
        super(ArcWithVertices, self).relocate(sample, model)
        if model is WithArcVertices:
            self.vertices.extend(sample.vertices)


def build(*models):
    return ModelEntity.build(WithGraph, *models)