File size: 8,965 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Complete finite-world witness synthesis for compositional numeric programs.

Worlds contain four labelled integer cells in a declared inclusive domain.
The renderer redacts complete cells before drawing. The finite-domain
restriction is explicit: this is not a certificate for arbitrary real worlds.
"""

import base64
import copy
import io
import itertools
from fractions import Fraction

OPS = {"add", "sub", "mul", "div", "min", "max", "gt", "eq"}
LABELS = ("A", "B", "C", "D")


def evaluate(program, world):
    """Recursive exact-rational executor used by the synthesizer."""
    op = program[0]
    if op == "cell":
        return Fraction(world[program[1]])
    if op == "const":
        return Fraction(program[1])
    a, b = (evaluate(p, world) for p in program[1:])
    if op == "add":
        return a + b
    if op == "sub":
        return a - b
    if op == "mul":
        return a * b
    if op == "div":
        return a / b
    if op == "min":
        return min(a, b)
    if op == "max":
        return max(a, b)
    if op == "gt":
        return int(a > b)
    if op == "eq":
        return int(a == b)
    raise ValueError("unsupported operator")


def reference_evaluate(program, world):
    """Separate postfix stack executor; it does not call evaluate."""
    todo, code = [(program, False)], []
    while todo:
        node, visited = todo.pop()
        if node[0] in ("cell", "const") or visited:
            code.append(node[:2] if node[0] in ("cell", "const") else [node[0]])
        else:
            todo.extend([(node, True), (node[2], False), (node[1], False)])
    stack = []
    for instruction in code:
        op = instruction[0]
        if op == "cell":
            stack.append(Fraction(world[instruction[1]]))
        elif op == "const":
            stack.append(Fraction(instruction[1]))
        else:
            right, left = stack.pop(), stack.pop()
            operations = {
                "add": lambda: left + right, "sub": lambda: left - right,
                "mul": lambda: left * right, "div": lambda: left / right,
                "min": lambda: left if left <= right else right,
                "max": lambda: right if left <= right else left,
                "gt": lambda: Fraction(int(left > right)),
                "eq": lambda: Fraction(int(left == right)),
            }
            stack.append(operations[op]())
    if len(stack) != 1:
        raise ValueError("invalid postfix program")
    return stack[0]


def validate_program(program, depth=0):
    if depth > 12 or not isinstance(program, list) or not program:
        raise ValueError("invalid program")
    op = program[0]
    if op in ("cell", "const"):
        if len(program) != 2:
            raise ValueError("invalid leaf")
        if op == "cell" and (type(program[1]) is not int or program[1] not in range(4)):
            raise ValueError("unknown cell")
        if op == "const" and (type(program[1]) is not int or abs(program[1]) > 100):
            raise ValueError("invalid constant")
    else:
        if op not in OPS or len(program) != 3:
            raise ValueError("unknown operation")
        for child in program[1:]:
            validate_program(child, depth + 1)
        if op == "div" and not (program[2][0] == "const" and program[2][1] != 0):
            raise ValueError("division requires a nonzero constant denominator")


def question(program):
    op = program[0]
    if op == "cell":
        return LABELS[program[1]]
    if op == "const":
        return str(program[1])
    symbols = {"add": "+", "sub": "-", "mul": "*", "div": "/", "gt": ">", "eq": "="}
    a, b = map(question, program[1:])
    return f"{op}({a}, {b})" if op in ("min", "max") else f"({a} {symbols[op]} {b})"


def observation(world, hidden):
    return [None if i in hidden else value for i, value in enumerate(world)]


def render(observed, domain):
    """Byte-exact RGB observation, with a fixed public axis and value labels."""
    from PIL import Image, ImageDraw

    image = Image.new("RGB", (400, 260), "white")
    draw = ImageDraw.Draw(image)
    draw.text((12, 8), f"Integer values: {domain[0]} to {domain[1]}", fill="black")
    for i, value in enumerate(observed):
        left = 18 + 95 * i
        draw.rectangle((left, 40, left + 70, 230), outline="black")
        draw.text((left + 29, 238), LABELS[i], fill="black")
        if value is None:
            draw.rectangle((left + 1, 41, left + 69, 229), fill=(210, 210, 210))
            draw.text((left + 9, 125), "HIDDEN", fill="black")
        else:
            y = 225 - round(155 * (value - domain[0]) / (domain[1] - domain[0]))
            draw.rectangle((left + 12, y, left + 58, 225), fill=(45, 102, 164))
            draw.text((left + 24, 46), str(value), fill="black")
    return image


def completions(observed, domain):
    hidden = [i for i, value in enumerate(observed) if value is None]
    for values in itertools.product(range(domain[0], domain[1] + 1), repeat=len(hidden)):
        world = list(observed)
        for i, value in zip(hidden, values, strict=True):
            world[i] = value
        yield world


def validate_observation(observed, domain):
    if (not isinstance(domain, list) or len(domain) != 2
            or any(type(x) is not int for x in domain) or not 0 < domain[1] - domain[0] <= 20):
        raise ValueError("unsupported finite domain")
    if not isinstance(observed, list) or len(observed) != 4:
        raise ValueError("expected four cells")
    if sum(x is None for x in observed) > 3:
        raise ValueError("at most three hidden cells")
    if any(x is not None and (type(x) is not int or not domain[0] <= x <= domain[1])
           for x in observed):
        raise ValueError("observed value outside domain")


def synthesize(program, observed, domain):
    """Exhaustively find a separating pair, or report a constant finite answer."""
    validate_program(program)
    validate_observation(observed, domain)
    first, first_answer, inspected = None, None, 0
    for world in completions(observed, domain):
        answer = evaluate(program, world)
        inspected += 1
        if first is None:
            first, first_answer = world, answer
        elif answer != first_answer:
            buf = io.BytesIO()
            render(observed, domain).save(buf, format="PNG")
            return {
                "status": "ambiguous", "worlds_inspected": inspected,
                "proof": {
                    "schema": "finite_compositional_witness_v1",
                    "domain": domain, "program": copy.deepcopy(program),
                    "question": question(program), "observation": observed,
                    "witnesses": [first, world],
                    "observed_png": base64.b64encode(buf.getvalue()).decode("ascii"),
                },
            }
    return {"status": "constant", "worlds_inspected": inspected, "answer": str(first_answer)}


def verify(proof):
    """Check complete-world membership, both executors, question and pixels."""
    from PIL import Image

    try:
        if proof["schema"] != "finite_compositional_witness_v1":
            raise ValueError("schema")
        program, observed, domain = proof["program"], proof["observation"], proof["domain"]
        validate_program(program)
        validate_observation(observed, domain)
        if proof["question"] != question(program):
            raise ValueError("question/program mismatch")
        hidden = [i for i, v in enumerate(observed) if v is None]
        png = base64.b64decode(proof["observed_png"], validate=True)
        image = Image.open(io.BytesIO(png)).convert("RGB")
        expected = render(observed, domain)
        if image.size != expected.size or image.tobytes() != expected.tobytes():
            raise ValueError("observed pixels mismatch")
        answers = []
        if len(proof["witnesses"]) != 2:
            raise ValueError("two worlds required")
        for world in proof["witnesses"]:
            if (len(world) != 4 or any(type(v) is not int or not domain[0] <= v <= domain[1]
                                       for v in world)):
                raise ValueError("inadmissible complete world")
            if observation(world, hidden) != observed:
                raise ValueError("visible value mismatch")
            rendered = render(observation(world, hidden), domain)
            if rendered.tobytes() != image.tobytes():
                raise ValueError("witness pixels mismatch")
            answer = reference_evaluate(program, world)
            if answer != evaluate(program, world):
                raise ValueError("executor disagreement")
            answers.append(str(answer))
        if answers[0] == answers[1]:
            raise ValueError("answers are identical")
        return {"ok": True, "answers": answers}
    except (ValueError, KeyError, TypeError, IndexError, ZeroDivisionError, OSError) as exc:
        return {"ok": False, "error": str(exc)}