File size: 2,465 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
"""Standard two-copy SMT construction; the certificate checker remains separate.

Z3 API: https://z3prover.github.io/api/html/namespacez3py.html
This implements established relational reasoning, not a new SMT algorithm.
"""

import base64
import copy
import io

from .finite_program import question, render, validate_observation, validate_program


def construct(program, observed, domain, *, timeout_ms=1000):
    import z3

    validate_program(program)
    validate_observation(observed, domain)
    first = z3.IntVector("first", 4)
    second = z3.IntVector("second", 4)

    def expression(node, world):
        op = node[0]
        if op == "cell":
            return z3.ToReal(world[node[1]])
        if op == "const":
            return z3.RealVal(node[1])
        left, right = (expression(child, world) for child in node[1:])
        operations = {
            "add": lambda: left + right, "sub": lambda: left - right,
            "mul": lambda: left * right, "div": lambda: left / right,
            "min": lambda: z3.If(left <= right, left, right),
            "max": lambda: z3.If(left >= right, left, right),
            "gt": lambda: z3.If(left > right, z3.RealVal(1), z3.RealVal(0)),
            "eq": lambda: z3.If(left == right, z3.RealVal(1), z3.RealVal(0)),
        }
        return operations[op]()

    solver = z3.Solver()
    solver.set(timeout=timeout_ms, random_seed=0)
    for world in (first, second):
        for i, value in enumerate(observed):
            solver.add(world[i] >= domain[0], world[i] <= domain[1])
            if value is not None:
                solver.add(world[i] == value)
    solver.add(expression(program, first) != expression(program, second))
    status = solver.check()
    if status == z3.unsat:
        return {"status": "constant"}
    if status != z3.sat:
        return {"status": "unknown", "reason": solver.reason_unknown()}
    model = solver.model()
    worlds = [[model.eval(value, model_completion=True).as_long() for value in world]
              for world in (first, second)]
    image = io.BytesIO()
    render(observed, domain).save(image, format="PNG")
    return {"status": "ambiguous", "proof": {
        "schema": "finite_compositional_witness_v1", "domain": list(domain),
        "program": copy.deepcopy(program), "question": question(program),
        "observation": list(observed), "witnesses": worlds,
        "observed_png": base64.b64encode(image.getvalue()).decode("ascii"),
    }}