Ejemplo n.º 1
0
 def make_loc_vars(prefix):
     lInput = list(z3.Ints(id_arr(f'{prefix}_locInput', nInput), ctx))
     lPR = [(list(
         z3.Ints(id_arr(f'{prefix}_locParam_{i}', comp.arity),
                 ctx)), z3.Int(f'{prefix}_locReturn_{i}', ctx))
            for i, comp in enumerate(lib)]
     lOutput = z3.Int(f'{prefix}_locOutput', ctx)
     return lInput, lPR, lOutput
Ejemplo n.º 2
0
def calVertical(pointA, pointB, pointC):
    # t = z3.Reals("t")
    # x, y, z = calLineEqut(pointA, pointB)
    x, y, z = z3.Ints('x y z')
    formula = (pointB[0] - pointA[0]) * (x - pointC[0])
    formula += (pointB[1] - pointA[1]) * (y - pointC[1])
    formula += (pointB[2] - pointA[2]) * (z - pointC[2])
    formula = formula == 0
    cal = z3.Solver()
    cal.add(formula)
    # # cal.add(x==6)
    perhaps_list = [
        x == 0, x == factorial - 1, y == 0, y == factorial - 1, z == 0,
        z == factorial - 1
    ]
    cal.add(x >= 0, x <= (factorial - 1))
    cal.add(y >= 0, y <= (factorial - 1))
    cal.add(z >= 0, z <= (factorial - 1))
    for i in perhaps_list:
        cal.push()
        cal.add(i)
        if cal.check() != z3.sat:
            cal.pop()
            continue
        m = cal.model()
        result = [m[x].as_long(), m[y].as_long(), m[z].as_long()]
        if result == pointC:
            cal.pop()
            continue
        return result
    return False
def solve_23_part_2(nanobots: List[Nanobot]):
    print('Starting up')
    origin = (0, 0, 0)
    x, y, z, in_range = z3.Ints('x y z in_range')

    in_range = in_range * 0
    print('Vars declared')

    for bot in nanobots:
        in_range += z3.If(z3distance(bot.loc_tuple(), (x, y, z)) <= bot.radius, 1, 0)

    print('In range calc prep done')
    optimizer = z3.Optimize()

    print('Created optimizer, setting max/min functions')
    optimizer.maximize(in_range)
    optimizer.minimize(z3distance(origin, (x, y, z)))

    print('Checking optimizer')
    optimizer.check()

    print('Getting model')
    model = optimizer.model()

    print('Returning values')
    origin_loc = Point3d(0, 0, 0)
    found_loc = Point3d(model[x].as_long(), model[y].as_long(), model[z].as_long())
    distance_to_found_loc = manhattan_distance_3d(origin_loc, found_loc)
    bots_at_loc = search_point(found_loc, nanobots)

    print('Distance from {} to {}: {}. Bots in range: {}'.format(origin_loc, found_loc, distance_to_found_loc, len(bots_at_loc)))
    return distance_to_found_loc
Ejemplo n.º 4
0
def ex1a():
    # path condition leading to err1: 0 < i < 10 & i < 5 & i = 2
    myi, myj, myk = z3.Ints('i j k')
    inp = Input([myi, myj, myk], [2, 100, 1000])
    bad_pathconds = [PathCond([0 < myi, myi < 10, myi < 5, myi == 2])]

    return inp, bad_pathconds
Ejemplo n.º 5
0
def main():
    # create the variables a and b.
    a, b = z3.Ints('a b')
    # create the variables a' and b'
    a_p, b_p = z3.Ints('a_p b_p')

    # now we will check the base case for the induction

    # first create a solver object.
    S = z3.Solver()
    # create the init predicate.
    Init = z3.And(a == 0, b == 1)
    # create the property
    prop = a <= b
    # we want to check whether Init(X) ==> prop(X) is valid.
    # we do this by checking whether Not(Init(X) ==> prop(X)) is UNSAT
    S.add(z3.Not(z3.Implies(Init, prop)))
    if S.check() == z3.sat:
        print('Base case does not hold. Property is FALSE.')
        print('Counterexample: ')
        m = S.model()
        print('\ta =', m.eval(a))
        print('\tb =', m.eval(b))
    else:
        print('Base case HOLDS.')

    # now we will check the inductive step.

    # create a new solver object.
    S = z3.Solver()
    R = z3.And(a_p == b, b_p == a + b)
    prop = a <= b
    prop_p = a_p <= b_p
    # we want to check if R(X, X') && prop(X) ==>  prop(X')
    # we will do this by checking if the negation of the above is UNSAT
    S.add(z3.Not(z3.Implies(z3.And(prop, R), prop_p)))
    if S.check() == z3.sat:
        print('Inductive step does not hold. Property is UNDEF.')
        print('Counterexample to induction:')
        m = S.model()
        print('\ta =', m.eval(a))
        print('\tb =', m.eval(b))
        print('\ta_p =', m.eval(a_p))
        print('\tb_p =', m.eval(b_p))
    else:
        print('Inductive step HOLDS.')
Ejemplo n.º 6
0
    def test_variable_order(self):
        # Little more complex case, to see whether ordering of variables are
        # kept right.
        a, b, c = z3.Ints('a b c')
        formula = z3.ForAll([c, a, b], z3.And(b > a, a > c))

        self.assertEqual(z3.Not(z3.And(b > a, a > c)),
                         z3_utils.negated_body(formula))
Ejemplo n.º 7
0
 def GenerateVar(cls, name, **fields):
     if fields:
         return collections.namedtuple(
             name,
             fields.keys(),
         )(*z3.Ints(' '.join(fields.values())))
     else:
         return z3.Int(name)
Ejemplo n.º 8
0
def ex1b():
    """
    violated path conditions to err2: 0 < i < 10 & i >= 5 & i = 3
    can be fixed by changing i to #3
    """
    myi, myj, myk = z3.Ints('i j k')
    inp = Input([myi, myj, myk], [3, 100, 1000])
    bad_pathconds = [PathCond([0 < myi, myi < 10, myi < 5, myi == 3])]

    return inp, bad_pathconds
Ejemplo n.º 9
0
def ex3a():
    y0, y1, y2, y3, y4, y5 = z3.Ints('y0 y1 y2 y3 y4 y5')
    inp = Input([y0, y1, y2, y3, y4, y5], [0, 1, 2, 5, 4, 5])
    bad_pathconds = [
        PathCond([y0 == y2]),
        PathCond([y0 != y2, y1 == y3]),
        PathCond([y0 != y2, y1 != y3, y2 == y4]),
        PathCond([y0 != y2, y1 != y3, y2 != y4, y3 == y5])
    ]

    return inp, bad_pathconds
Ejemplo n.º 10
0
def hard():
    o = z3.Optimize()
    x, y, z = z3.Ints("x y z")

    for p, d in t:
        o.add_soft(
            z3.If(x > p[0], x - p[0], p[0] - x) +
            z3.If(y > p[1], y - p[1], p[1] - y) +
            z3.If(z > p[2], z - p[2], p[2] - z) <= d)
    o.check()
    m = o.model()
    print(m.eval(x + y + z))
Ejemplo n.º 11
0
def best_point(nanos):
    x, y, z, cost = z3.Ints("x y z cost")
    cost = cost * 0
    for c, r in nanos:
        cost += z3.If(z3dist((x, y, z), c) <= r, 1, 0)
    o = z3.Optimize()
    o.maximize(cost)
    o.minimize(z3dist((0, 0, 0), (x, y, z)))
    o.check()
    model = o.model()
    return distance(
        (0, 0, 0),
        (model[x].as_long(), model[y].as_long(), model[z].as_long()))
Ejemplo n.º 12
0
    def construnct_env(self, ides):
        if isinstance(ides, Token):
            ides = [ides]
        else:
            # convert ides to strings
            ides = list(map((lambda x: x.value), ides.children))

        # construct z3 symbols for all the ides
        env_str = ' '.join(ides)
        ide_symols = z3.Ints(env_str)

        # construct the environment
        for (i, ide) in enumerate(ides):
            self.env[ide] = ide_symols[i]
Ejemplo n.º 13
0
def ex1c():
    """
    violated path conditions to err1 + a fake one:
    - 0 < i < 10 & i >= 5 & i = 3
    - j >= 0
    can be fixed by changing i to !3 and j to < 0
    """
    myi, myj, myk = z3.Ints('i j k')
    inp = Input([myi, myj, myk], [3, 100, 1000])
    bad_pathconds = [
        PathCond([0 < myi, myi < 10, myi < 5, myi == 3]),
        PathCond([myj >= 0])
    ]

    return inp, bad_pathconds
Ejemplo n.º 14
0
def main():
    b, c = z3.Ints("b c")
    a = z3.Array("a", z3.IntSort(), z3.IntSort())
    f = z3.Function("f", z3.IntSort(), z3.IntSort())
    solver = z3.Solver()
    solver.add(c == b + z3.IntVal(2))
    lhs = f(z3.Store(a, b, 3)[c - 2])
    rhs = f(c - b + 1)
    solver.add(lhs != rhs)
    res = solver.check()
    if res == z3.sat:
        print("sat")
    elif res == z3.unsat:
        print("unsat")
    else:
        print("unknown")
Ejemplo n.º 15
0
def main():
    b, c = z3.Ints('b c')
    a = z3.Array('a', z3.IntSort(), z3.IntSort())
    f = z3.Function('f', z3.IntSort(), z3.IntSort())
    solver = z3.Solver()
    solver.add(c == b + z3.IntVal(2))
    lhs = f(z3.Store(a, b, 3)[c - 2])
    rhs = f(c - b + 1)
    solver.add(lhs <> rhs)
    res = solver.check()
    if res == z3.sat:
        print 'sat'
    elif res == z3.unsat:
        print 'unsat'
    else:
        print 'unknown'
Ejemplo n.º 16
0
def vc_2_z3(vc: imp_ast.Exp):
    if isinstance(vc, imp_ast.ExpNum):
        return vc.num

    if isinstance(vc, imp_ast.ExpVar):
        return z3.Int(vc.var)

    # TODO: your Exercise 5 code here, convert the generated
    # vc to z3 constraints format,
    # also do not forget to deal with ExpUni, Z3 is often
    # able to handle formulas involving quantifiers. like:
    # ForAll([x, y], f(x, y) == 0)
    if isinstance(vc, imp_ast.ExpBop):
        left = vc_2_z3(vc.left)
        right = vc_2_z3(vc.right)

        if vc.bop == imp_ast.BOp.ADD:
            return left + right
        elif vc.bop == imp_ast.BOp.MIN:
            return left - right
        elif vc.bop == imp_ast.BOp.MUL:
            return left * right
        elif vc.bop == imp_ast.BOp.DIV:
            return left / right
        elif vc.bop == imp_ast.BOp.EQ:
            return left == right
        elif vc.bop == imp_ast.BOp.NE:
            return left != right
        elif vc.bop == imp_ast.BOp.GT:
            return left > right
        elif vc.bop == imp_ast.BOp.GE:
            return left >= right
        elif vc.bop == imp_ast.BOp.LT:
            return left < right
        elif vc.bop == imp_ast.BOp.LE:
            return left <= right
        elif vc.bop == imp_ast.BOp.IM:
            return z3.Implies(left, right)
        elif vc.bop == imp_ast.BOp.AND:
            return z3.And(left, right)
        elif vc.bop == imp_ast.BOp.OR:
            return z3.Or(left, right)
    if isinstance(vc, imp_ast.ExpNeg):
        return z3.Not(vc_2_z3(vc.exp))
    if isinstance(vc, imp_ast.ExpUni):
        exp = vc_2_z3(vc.exp)
        return z3.ForAll(z3.Ints(list(vc.vars_set)), exp)
Ejemplo n.º 17
0
def getLinePonit(A, B):
    x, y, z = z3.Ints('x y z')
    cal = z3.Solver()
    formula1 = (x - A[0]) * (B[1] - A[1]) == (y - A[1]) * (B[0] - A[0])
    formula2 = (x - A[0]) * (B[2] - A[2]) == (z - A[2]) * (B[0] - A[0])
    formula3 = (z - A[2]) * (B[1] - A[1]) == (y - A[1]) * (B[2] - A[2])
    if A[0] - B[0] != 0 and A[1] - B[1] != 0 and A[2] - B[2] != 0:
        cal.add(formula1)
        cal.add(formula2)
        cal.add(formula3)
    if A[0] - B[0] == 0:
        cal.add(x == A[0])
        cal.add(formula3)
    if A[1] - B[1] == 0:
        cal.add(y == A[1])
        cal.add(formula2)
    if A[2] - B[2] == 0:
        cal.add(z == A[2])
        cal.add(formula1)
    if A[0] - B[0] != 0:
        while True:
            tmp = random.randint(10, 200)
            if tmp != A[0] and tmp != B[0]:
                break
        cal.add(x == tmp)
    elif A[1] - B[1] != 0:
        while True:
            tmp = random.randint(10, 200)
            if tmp != A[1] and tmp != B[1]:
                break
        cal.add(y == tmp)
    elif A[2] - B[2] != 0:
        while True:
            tmp = random.randint(10, 200)
            if tmp != A[2] and tmp != B[2]:
                break
        cal.add(z == tmp)
    else:
        return False
    if cal.check() != z3.sat:
        # print(cal)
        return False
    m = cal.model()
    return [m[x].as_long(), m[y].as_long(), m[z].as_long()]
Ejemplo n.º 18
0
def list_of_length(length,
                   src,
                   trg,
                   with_data=True,
                   loc_prefix='a',
                   data_prefix='d'):
    """Return expression for a sequence of `length` pointers from `src` to `trg`.

    Whether or not data allocation is included is controlled by the
    `with_data` flag (True by default).

    >>> x, y = sl.list.locs('x y'); list_of_length(2, x, y, loc_prefix = 'z_')
    sl.sepcon(sl.sepcon(sl.list.next(x, z_1),
                        sl.list.next(z_1, y)),
              sl.sepcon(sl.list.data(x, d0),
                        sl.list.data(z_1, d1)))
    >>> list_of_length(2, x, y, loc_prefix = 'z_', with_data = False)
    sl.sepcon(sl.list.next(x, z_1), sl.list.next(z_1, y))

    """
    if length == 0:
        return sl.list.eq(src, trg)

    loc_fmt = loc_prefix + '{}'
    tmp_locs = sl.list.locs(*map(loc_fmt.format, range(1, length)))
    locs = [src] + tmp_locs + [trg]
    ptr_ends = list(utils.consecutive_pairs(locs))
    assert (len(ptr_ends) == length)
    if length > 1:
        expr = sl.sepcon(*(sl.list.next(*pair) for pair in ptr_ends))
    else:
        expr = sl.list.next(*ptr_ends[0])
    if with_data:
        data_fmt = data_prefix + '{}'
        tmp_data = z3.Ints(' '.join(map(data_fmt.format, range(length))))
        assert (len(tmp_data) == len(locs) - 1)
        data_ptrs = zip(locs[:-1], tmp_data)
        if length > 1:
            data_expr = sl.sepcon(*(sl.list.data(*ptr) for ptr in data_ptrs))
        else:
            data_expr = sl.list.data(*next(data_ptrs))
        expr = sl.sepcon(expr, data_expr)
    return expr
Ejemplo n.º 19
0
def part2_z3(rules, my, others):
    ok_others = []

    for t in others:
        if not invalid_fields(rules, t):
            ok_others.append(t)

    s = z3.Solver()

    idxs = z3.Ints([f"idx_{i}" for i in range(len(rules))])

    for i in idxs:
        s.add(i >= 0, i < len(rules))

    s.add(z3.Distinct(idxs))

    cols = zip(*ok_others)

    for i, col in enumerate(cols):
        for (_, a_r, b_r), idx in zip(rules, idxs):
            c = all(x in a_r or x in b_r for x in col)
            if not c:
                s.add(idx != i)

    assert s.check() == z3.sat, "f**k"

    m = s.model()

    assignments = [(name, m[idx].as_long()) for (name, _, _), idx in zip(rules, idxs)]

    r = 1

    for name, column in assignments:
        if "departure" not in name:
            continue
        r *= my[column]

    return r
Ejemplo n.º 20
0
def euler185():
    import z3
    x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16 = z3.Ints(
        "x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16")
    #x1,x2,x3,x4,x5 = z3.Ints("x1 x2 x3 x4 x5")
    variables = [
        x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16
    ]

    #variables = [x1,x2,x3,x4,x5]

    def none_correct(arr):
        return reduce(z3.And,
                      [arr[i] != variables[i] for i in range(len(arr))])

    def one_correct(arr):
        return reduce(z3.Or, [
            reduce(z3.And, [
                arr[j] != variables[j] if i != j else arr[j] == variables[j]
                for j in range(len(arr))
            ]) for i in range(len(arr))
        ])

    def two_correct(arr):
        out = []
        for i in range(len(arr)):
            for j in range(len(arr)):
                if i < j:
                    out.append(
                        reduce(z3.And, [
                            arr[k] == variables[k] if
                            (k == i or k == j) else arr[k] != variables[k]
                            for k in range(len(arr))
                        ]))
        return reduce(z3.Or, out)

    def three_correct(arr):
        out = []
        for i in range(len(arr)):
            for j in range(len(arr)):
                for k in range(len(arr)):
                    if i < j < k:
                        out.append(
                            reduce(z3.And, [
                                arr[l] == variables[l] if
                                (l == i or l == j
                                 or l == k) else arr[l] != variables[l]
                                for l in range(len(arr))
                            ]))
        return reduce(z3.Or, out)

    s = []
    for i in variables:
        s.append(0 <= i)
        s.append(i <= 9)
    # s.append(z3.simplify(two_correct([int(i) for i in "90342"])))
    # s.append(z3.simplify(none_correct([int(i) for i in "70794"])))
    # s.append(z3.simplify(two_correct([int(i) for i in "39458"])))
    # s.append(z3.simplify(one_correct([int(i) for i in "34109"])))
    # s.append(z3.simplify(two_correct([int(i) for i in "51545"])))
    # s.append(z3.simplify(one_correct([int(i) for i in "12531"])))
    # print z3.solve(reduce(z3.And,s))
    """
    5616185650518293 ;2 correct
    3847439647293047 ;1 correct
    5855462940810587 ;3 correct
    9742855507068353 ;3 correct
    4296849643607543 ;3 correct
    3174248439465858 ;1 correct
    4513559094146117 ;2 correct
    7890971548908067 ;3 correct
    8157356344118483 ;1 correct
    2615250744386899 ;2 correct
    8690095851526254 ;3 correct
    6375711915077050 ;1 correct
    6913859173121360 ;1 correct
    6442889055042768 ;2 correct
    2321386104303845 ;0 correct
    2326509471271448 ;2 correct
    5251583379644322 ;2 correct
    1748270476758276 ;3 correct
    4895722652190306 ;1 correct
    3041631117224635 ;3 correct
    1841236454324589 ;3 correct
    2659862637316867 ;2 correct
    """

    guesses = "5616185650518293  3847439647293047  5855462940810587  9742855507068353  4296849643607543  3174248439465858  4513559094146117  7890971548908067  8157356344118483  2615250744386899  8690095851526254  6375711915077050  6913859173121360  6442889055042768  2321386104303845  2326509471271448  5251583379644322  1748270476758276  4895722652190306  3041631117224635  1841236454324589  2659862637316867".split(
        "  ")
    guesses = zip(
        guesses,
        [2, 1, 3, 3, 3, 1, 2, 3, 1, 2, 3, 1, 1, 2, 0, 2, 2, 3, 1, 3, 3, 2])
    for (i, j) in guesses:
        print i
        if j == 0:
            s.append(z3.simplify(none_correct([int(k) for k in i])))
        elif j == 1:
            s.append(z3.simplify(one_correct([int(k) for k in i])))
        elif j == 2:
            s.append(z3.simplify(two_correct([int(k) for k in i])))
        else:
            s.append(z3.simplify(three_correct([int(k) for k in i])))
    return sorted(z3.solve(reduce(z3.And, s)))
Ejemplo n.º 21
0
            bots.append(NanoBot(pos, r))
bots.sort()

# ------------------------------------------------
# part 1
# ------------------------------------------------
in_range = [bots[-1].in_range(b) for b in bots]
print(sum(in_range))
print('')

# ------------------------------------------------
# part 2
# ------------------------------------------------

zabs = lambda x: z3.If(x >= 0, x, -x)
x, y, z = z3.Ints('x y z')

o = z3.Optimize()
in_range = []
in_range_count = z3.Int('in_range_count')
for i, b in enumerate(bots):
    in_range_f = z3.If(
        zabs(b.pos[0] - x) + zabs(b.pos[1] - y) + zabs(b.pos[2] - z) <=
        b.radius, 1, 0)
    in_range_var = z3.Int('in_range_%04d' % i)
    in_range.append(in_range_var)
    o.add(in_range_var == in_range_f)
o.add(in_range_count == sum(in_range))

h1 = o.maximize(in_range_count)
h2 = o.minimize(zabs(x) + zabs(y) + zabs(z))
Ejemplo n.º 22
0
import z3
x, y, z, n = z3.Ints("x y z n")

e1 = y * z - z3.Int("18") * x - z3.Int("12") * y + z3.Int("2") * z == z3.Int(
    "6")
e2 = (z * z) - z3.Int("12") * y + z3.Int("12") == z3.Int("6") * z
e3 = z3.Int("6") * n + z3.Int("6") == z

d1 = z == z3.Int("6") * n + z3.Int("6")
d2 = y == z3.Int("3") * n * n + z3.Int("3") * n + z3.Int("1")
d3 = x == n * n * n

e123 = z3.And(e1, e2, e3)
#z3.prove(z3.Implies(e123, d1))
#z3.prove(z3.Implies(e123, d2))
#z3.prove(z3.Implies(e123, d3))
Ejemplo n.º 23
0
from collections import namedtuple
import z3

# Figure 2
SymbolicPacket = namedtuple(
    'SymbolicPacket', ['dstIp', 'srcIp', 'dstPort', 'srcPort', 'protocol'])

dstIp, srcIp, dstPort, srcPort, protocol = z3.Ints(
    'dstIp srcIp dstPort srcPort protocol')


def z3Range(exp, low, high):
    return z3.And(low <= exp, exp < high)


# (1)
symbolic_packet = SymbolicPacket(
    z3Range(dstIp, 0, 2**32),
    z3Range(srcIp, 0, 2**32),
    z3Range(dstPort, 0, 2**16),
    z3Range(srcPort, 0, 2**16),
    z3Range(protocol, 0, 2**8)
)
Ejemplo n.º 24
0
def ex2a():
    a0, a1, a2, a3, a4 = z3.Ints('a0 a1 a2 a3 a4')
    inp = Input([a0, a1, a2, a3, a4], [0, 1, 2, 3, -1])
    bad_pathconds = [PathCond([a0 != -1, a1 != -1, a2 != -1, a3 != -1])]
    return inp, bad_pathconds
Ejemplo n.º 25
0
import z3
import logging
logger = logging.getLogger('optimize.py')
logging.basicConfig()
logger.setLevel(logging.INFO)

def hook():
	#for debugging
	logger.warning("HOOKING IPYTHON")
	import IPython
	IPython.embed()

s1 = z3.Solver()
x, y = z3.Ints('x y')
s1.add(x>y)
s1.add(x==4)

s = z3.Optimize()
s.add(*s1.assertions())
m = s.maximize(y)
s.check()


logger.info("max: %s", m)

hook()
Ejemplo n.º 26
0
# feel the need to specify apparently.


def POPCNT(bits, **kwargs):
    # This is a variable-width version of the classic 0x5555/0x3333/0x0f0f/0xffff
    # etc algorithm, to sum N bits in O(log2 N) steps
    shift = 1
    while shift < bits.size():
        mask = sum(1 << x for x in range(bits.size()) if not x & shift)
        bits = (bits & mask) + ((bits >> shift) & mask)
        shift *= 2
    return bits & ((1 << shift) - 1)


# Create z3 lambdas for comparison operations
_a, _b = z3.Ints('a b')

_MM_CMPINT_EQ = z3.Lambda([_a, _b], _a == _b)  # 0
_MM_CMPINT_LT = z3.Lambda([_a, _b], _a < _b)  # 1
_MM_CMPINT_LE = z3.Lambda([_a, _b], _a <= _b)  # 2
_MM_CMPINT_FALSE = z3.Lambda([_a, _b], z3.BoolVal(False))  # 3
_MM_CMPINT_NE = z3.Lambda([_a, _b], _a != _b)  # 4
_MM_CMPINT_NLT = z3.Lambda([_a, _b], _a >= _b)  # 5
_MM_CMPINT_NLE = z3.Lambda([_a, _b], _a > _b)  # 6
_MM_CMPINT_TRUE = z3.Lambda([_a, _b], z3.BoolVal(True))  # 7

# Zero/sign extension: just mark these values as signed/unsigned, the users
# of the values will use this later when the size of the target value is known


def ZeroExtend(v, **kwargs):
Ejemplo n.º 27
0
def part_2():
    points, rs = load_input()

    # just some playing with z3
    # a = z3.Real('a')
    # b = z3.Real('b')
    # s = z3.Solver()
    # s.add(a + b == 5)
    # s.add(a - 2*b == 3)
    # s.add(a - 2*b == 3)
    # check_result = s.check()
    # m = s.model()
    # print(m[a])
    # print(m[b])

    # a = z3.Real('a')
    # b = z3.Real('b')
    # c = z3.Real('c')
    # d = z3.Real('d')
    # s = z3.Optimize()
    # s.add()
    # s.add(a <= 5)
    # s.add(b <= 10)
    # s.add(b >= c)
    # s.add(a >= d)
    # obj = s.maximize(a + b + c + d)
    # while s.check() == z3.sat:
    #     m = s.model()
    #     print(m[a])
    #     print(m[b])
    #     print(m[c])
    #     print(m[d])
    #     print(obj.value())
    # check_res = s.check()
    # m = s.model()
    # print(m[a])
    # print(m[b])
    # print(m[c])
    # print(m[d])
    # print(obj.value())

    # x, y = z3.Ints('x y')
    # opt = z3.Optimize()
    # opt.set(priority='pareto')
    # opt.add(x + y == 10, x >= 0, y >= 0)
    # mx = opt.maximize(x)
    # my = opt.maximize(y)
    # while opt.check() == z3.sat:
    #     print(mx.value(), my.value())
    # pass
    # reaches = np.zeros((np.max(points[:, 0]), np.max(points[:, 1]), np.max(points[:, 2])))
    # grid_indices = np.array(list(np.ndindex(reaches.shape)))
    # for point, r in zip(points, rs):
    #     dists = spatial.distance.cdist(point[np.newaxis, :], grid_indices, metric='cityblock')
    #     reach = np.where(dists <= r)
    #     reached_points = grid_indices[reach[1], :][:, 0], grid_indices[reach[1], :][:, 1], grid_indices[reach[1], :][:, 2]
    #     reaches[reached_points] += 1
    #
    # best_point = np.unravel_index(np.argmax(reaches), reaches.shape)
    # distance = spatial.distance.cityblock([0, 0, 0], best_point)
    # for point, r in zip(points, rs):
    #     range_set = set()
    #     for p0 in range(point[0] - r, point[0] + r + 1):
    #         remain_dist = r - abs(p0 - point[0])
    #         for p1 in range(point[1] - remain_dist, point[1] + remain_dist + 1):
    #             remain_dist = r - (abs(p0 - point[0]) + abs(p1 - point[1]))
    #             for p2 in range(point[2] - remain_dist, point[2] + remain_dist + 1):
    #                 range_set.add((p0, p1, p2))
    #     points_in_range.append(range_set)

    # dense_dists = spatial.distance.pdist(points, metric='cityblock')
    # distances = spatial.distance.squareform(dense_dists)
    # sum_ranges = rs + rs[:, np.newaxis] - np.eye(rs.shape[0]) * rs * 2
    # share_point = distances - sum_ranges
    # share_point_dense = spatial.distance.squareform(share_point)
    #
    # print('dont share any point', np.sum(share_point_dense >= 0))
    # print('share some points', np.sum(share_point_dense < 0))

    # mean for prunning estimate
    # centroid = np.mean(points, axis=0).astype(np.int32)
    # in_range = spatial.distance.cdist(centroid[np.newaxis, :], points, metric='cityblock') <= rs
    # np.sum(in_range)
    def z3abs(x):
        # z3.fpAbs is not working on integers, somehow, this works
        return z3.If(x >= 0, x, -x)

    coords = z3.Ints('x y z')
    s = z3.Optimize()
    in_ranges = z3.Ints(' '.join('p' + str(i) for i in range(len(points))))
    for i, (point, r) in enumerate(zip(points, rs)):
        # coords_diff = [z3abs(j - int(k)) for j, k in zip(coords, point)]  # casting from numpy type to pure python
        coords_diff = [z3abs(j - int(k)) for j, k in zip(coords, point)
                       ]  # casting from numpy type to pure python
        manhattan_dist = z3.Sum(coords_diff)
        s.add(z3.If(manhattan_dist <= int(r), 1, 0) == in_ranges[i])
    dist_from_zero = z3.Int('dist')
    # s.add(dist_from_zero == z3.Sum([z3abs(i) for i in coords]))
    s.add(dist_from_zero == z3.Sum([z3abs(i) for i in coords]))
    s.maximize(z3.Sum(in_ranges))
    s.minimize(dist_from_zero)
    res = s.check()
    m = s.model()
    print([m[i] for i in coords], m[dist_from_zero])
Ejemplo n.º 28
0
Archivo: data.py Proyecto: sllam/chrcp
def newInts(quantity):
	inames = " ".join( map(lambda _: get_new_var(prefix="i") ,range(0,quantity)) )
	return z3.Ints(inames)
Ejemplo n.º 29
0
import string
import numpy as np
import z3

dimension = 4
v = z3.Ints(' '.join(string.ascii_lowercase[:dimension**2]))
v = np.asarray(v).reshape(dimension, dimension)

s = z3.Solver()
for xij in v.flatten():
    s.add(z3.And(0 <= xij, xij <= 9))

answer = z3.Int("answer")
s.add(z3.And(answer >= 0, answer <= 9 * dimension**2))

for i in range(dimension):
    s.add(z3.Sum(v[i, :dimension].tolist()) == answer)
    s.add(z3.Sum(v[:dimension, i].tolist()) == answer)

s.add(z3.Sum(v.diagonal().tolist()) == answer)
s.add(z3.Sum(np.fliplr(v).diagonal().tolist()) == answer)

count = 0
while s.check() == z3.sat:
    m = s.model()
    count += 1
    s.add(z3.Or([f() != m[f] for f in m.decls() if f.arity() == 0]))

print(count)
Ejemplo n.º 30
0
    def test_forall(self):
        a, b = z3.Ints('a b')
        formula = z3.ForAll([a, b], a > b)

        self.assertEqual(z3.Not(a > b), z3_utils.negated_body(formula))