summaryrefslogtreecommitdiffstats
path: root/src/act4e_solutions/relations_representation.py
blob: a7fec7f8bdf099c3879b53f254a97b9fc907dd52 (plain)
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
from typing import TypeVar, List, Tuple

import act4e_interfaces as I
from .sets_representation import SolFiniteSetRepresentation

A = TypeVar("A")
B = TypeVar("B")

class MyFiniteRelation(I.FiniteRelation[A,B]):
    _source: I.FiniteSet[A]
    _target: I.FiniteSet[B]
    _values: List[Tuple[A,B]]

    def __init__(self, source: I.FiniteSet[A], target: I.FiniteSet[B], values: List[Tuple[A,B]]):
        self._source = source
        self._target = target
        self._values = values

    def source(self) -> I.FiniteSet[A]:
        return self._source

    def target(self) -> I.FiniteSet[B]:
        return self._target

    def holds(self, a: A, b: B) -> bool:
        for v, u in self._values:
            if self._source.equal(v, a) and self._target.equal(u, b):
                return True
        return False


class SolFiniteRelationRepresentation(I.FiniteRelationRepresentation):
    def load(self, h: I.IOHelper, data: I.FiniteRelation_desc) -> I.FiniteRelation[A, B]:
        fsr = SolFiniteSetRepresentation()
        src = fsr.load(h, data["source"])
        dst = fsr.load(h, data["target"])
        values = []
        
        for v in data["values"]:
            a, b = src.load(h, v[0]), dst.load(h, v[1])

            if not src.contains(a):
                raise I.InvalidFormat()

            if not dst.contains(b):
                raise I.InvalidFormat()

            values.append([a, b])

        return MyFiniteRelation(src, dst, values)

    def save(self, h: I.IOHelper, f: I.FiniteRelation[A, B]) -> I.FiniteRelation_desc:
        fsr = SolFiniteSetRepresentation()
        d = {
            "source": fsr.save(h, f.source()),
            "target": fsr.save(h, f.target()),
            "values": [],
        }

        for a in f.source().elements():
            for b in f.target().elements():
                if f.holds(a, b):
                    d["values"].append([
                        f.source().save(h, a),
                        f.target().save(h, b)])
        return d