Example #1
0
def skip(s):
    p = prog(s, "skip")
    x, y = elms("x y")
    s.add(ForAll([x, y], And(p.set(x), p.pre(x), p.post(x, y) == (x == y))))
    return p
Example #2
0
def main():
  """Battleship solver example."""
  sg = grilops.SymbolGrid(LATTICE, SYM)
  sc = grilops.shapes.ShapeConstrainer(
      LATTICE,
      [
          [Vector(0, i) for i in range(4)],
          [Vector(0, i) for i in range(3)],
          [Vector(0, i) for i in range(3)],
          [Vector(0, i) for i in range(2)],
          [Vector(0, i) for i in range(2)],
          [Vector(0, i) for i in range(2)],
          [Vector(0, i) for i in range(1)],
          [Vector(0, i) for i in range(1)],
          [Vector(0, i) for i in range(1)],
      ],
      solver=sg.solver,
      allow_rotations=True
  )

  # Constrain the given ship segment counts and ship segments.
  for y, count in enumerate(GIVENS_Y):
    sg.solver.add(
        PbEq([(Not(sg.cell_is(Point(y, x), SYM.X)), 1) for x in range(WIDTH)], count)
    )
  for x, count in enumerate(GIVENS_X):
    sg.solver.add(
        PbEq([(Not(sg.cell_is(Point(y, x), SYM.X)), 1) for y in range(HEIGHT)], count)
    )
  for p, s in GIVENS.items():
    sg.solver.add(sg.cell_is(p, s))

  for p in LATTICE.points:
    shape_type = sc.shape_type_grid[p]
    shape_id = sc.shape_instance_grid[p]
    touching_types = [
        n.symbol for n in LATTICE.vertex_sharing_neighbors(sc.shape_type_grid, p)
    ]
    touching_ids = [
        n.symbol for n in LATTICE.vertex_sharing_neighbors(sc.shape_instance_grid, p)
    ]

    # Link the X symbol to the absence of a ship segment.
    sg.solver.add(
        (sc.shape_type_grid[p] == -1) == sg.cell_is(p, SYM.X))

    # Ship segments of different ships may not touch.
    and_terms = []
    for touching_id in touching_ids:
      and_terms.append(
          Implies(
              shape_id >= 0,
              Or(touching_id == shape_id, touching_id == -1)
          )
      )
    sg.solver.add(And(*and_terms))

    # Choose the correct symbol for each ship segment.
    touching_count_terms = [(c == shape_type, 1) for c in touching_types]
    sg.solver.add(
        Implies(
            And(shape_type >= 0, PbEq(touching_count_terms, 2)),
            sg.cell_is(p, SYM.B)
        )
    )
    sg.solver.add(
        Implies(
            And(shape_type >= 0, PbEq(touching_count_terms, 0)),
            sg.cell_is(p, SYM.O)
        )
    )
    for n in sg.edge_sharing_neighbors(p):
      sg.solver.add(
          Implies(
              And(
                  shape_type >= 0,
                  PbEq(touching_count_terms, 1),
                  sc.shape_type_grid[n.location] == shape_type
              ),
              sg.cell_is(p, DIR_TO_OPPOSITE_SYM[n.direction])
          )
      )

  if sg.solve():
    sg.print()
    print()
    sc.print_shape_instances()
    print()
    if sg.is_unique():
      print("Unique solution")
    else:
      print("Alternate solution")
      sg.print()
      print()
      sc.print_shape_instances()
      print()
  else:
    print("No solution")
Example #3
0
 def toZ3(self):
     var = Z3VarTable.get(self.var)
     if (isinstance(self.value, IP)):
         ips = self.value.get_range()
         return And(var >= ips[0], var <= ips[1])
     return (var == self.value.value)
Example #4
0
from z3 import Solver, Ints, And, sat
s = Solver()

# Declare three integer variables/constants of Z3Py {x, y, z} :
x, y, z = Ints('x y z')

# Assert that {x, y, z} are positive integers such that 0 < x < y < z :
s.add(And(0 < x, x < y, y < z))

# Assert that x*x + y*y = z*z, i.e. (x,y,z) is a Pythagorean triple :
s.add(x % 2 != 0)
s.add(y % 2 == 0)
s.add(y == z - 1)
s.add(x * x + y * y == z * z)

n = 1
results = []
while s.check() == sat and n <= 3:
    m = s.model()
    results.append(m)
    s.add(x != m[x])
    n = n + 1

# print len (results)

for p in range(len(results)):
    print(results[p])
def reencode_quantifiers(expr, boundvariables, quantifiers):

    z3.set_option(max_args=10000000,
                  max_lines=1000000,
                  max_depth=10000000,
                  max_visited=1000000)
    smt2string = toSMT2Benchmark(expr)

    # Have to scan the string, because other methods proved to be too slow.
    log('Detect declarations of the free variables in SMTLIB2 string')
    free_variables = re.findall(
        '\(declare-fun (\w+) \(\) (Bool)|\(declare-fun (\w+) \(\) \(\_ BitVec (\d+)\)',
        smt2string)
    free_variables += re.findall(
        '\(declare-const (\w+) (Bool)|\(declare-const (\w+) \(\_ BitVec (\d+)\)',
        smt2string)

    for fv in free_variables:
        if str(fv).startswith('?'):
            print(
                'Error: Variable starts with "?". Potential for confusion with quantified variables. This case is not handled.'
            )
            exit()

    log('  Found {} free variables'.format(len(free_variables)))

    # Turn free variables into z3 variabes and add them to the quantifier
    for idx, (a, b, x, y) in enumerate(free_variables):
        assert (a != '' or x != '')
        if a != '':
            assert (b == 'Bool')
            free_variables[idx] = Bool(a)
        else:
            free_variables[idx] = BitVec(x, int(y))

    quantifiers = [['e', free_variables]] + quantifiers

    log('Replacing de Bruijn indices by variables')
    matches = re.findall('\?(\d+)', smt2string)
    deBruijnIDXs = map(int, set(matches))
    assert (len(deBruijnIDXs) <= len(boundvariables))
    # sort de Bruijn indeces in decreasing order so that replacing smaller numbers does not accidentally match larger numbers
    deBruijnIDXs = list(deBruijnIDXs)
    deBruijnIDXs.sort()
    deBruijnIDXs.reverse()

    for idx in deBruijnIDXs:
        smt2string = smt2string.replace('?{}'.format(idx),
                                        str(boundvariables[-(1 + int(idx))]))

    log('Generating SMTLIB without quantifiers')
    # introduce quantified variables to enable re-parsing
    declarations = []
    for var in boundvariables:
        if is_bv(var):
            declarations.append('(declare-fun {} () (_ BitVec {}))'.format(
                str(var), var.size()))
        else:
            assert (is_bool(var))
            declarations.append('(declare-fun {} () Bool)'.format(str(var)))

    smt2string = '\n'.join(declarations) + '\n' + smt2string

    log('Reparsing SMTLIB without quantifiers')
    flat_constraints = parse_smt2_string(smt2string)

    # log('Extract all variables')
    # allvariables = get_vars(flat_constraints)
    #
    # log('Search for free variables')
    # freevariables = []
    # known_vars = set(map(str,boundvariables))
    # for idx, var in enumerate(allvariables):
    #     if idx+1 % 10000 == 0:
    #         log('  {} variables checked if free'.format(idx))
    #     if str(var) not in known_vars:
    #         freevariables.append(var.n) # var.n because var is only the AstRefKey object
    #
    # log('Found {} free variables'.format(len(freevariables)))
    #
    # quantifiers = [['e', freevariables]] + quantifiers

    # delete empty quantifiers
    i = 0
    while i < len(quantifiers):
        if len(quantifiers[i][1]) == 0:
            del (quantifiers[i])
        else:
            i += 1

    for i in range(len(quantifiers) - 1):
        if quantifiers[i][0] == quantifiers[i + 1][0]:
            mergedQuantifiers[-1][1] += quantifiers[i + 1][1]
        else:
            mergedQuantifiers += [quantifiers[i + 1]]

    # merge successive quantifiers of the same type
    if len(quantifiers) > 0:
        mergedQuantifiers = [quantifiers[0]]
        for i in range(len(quantifiers) - 1):
            if quantifiers[i][0] == quantifiers[i + 1][0]:
                mergedQuantifiers[-1][1] += quantifiers[i + 1][1]
            else:
                mergedQuantifiers += [quantifiers[i + 1]]

        quantifiers = mergedQuantifiers

    # print quantifiers
    return quantifiers, And(flat_constraints)
Example #6
0
def SMT_standard_model(instance):
    # --------------------------
    #         PARAMETERS
    # --------------------------

    # Define dimensions parameters
    x = 0
    y = 1

    # Define wrapping paper roll height and width
    roll_width = instance['roll_width']
    roll_height = instance['roll_height']

    # Define wrapping paper roll coordinates
    X_COORDINATES = range(roll_width)
    Y_COORDINATES = range(roll_height)

    # Define the number of pieces to cut
    n_pieces = instance['n_pieces']

    # Define pieces as a set of integers from 0 to num. of presents-1
    PIECES = range(n_pieces)

    # Define the dimensions of the piecesq to cut
    pieces_dimensions = instance['pieces_dimensions']

    # Define lower and upper bounds for the dimensions
    lower_bounds = [0, 0]
    upper_bounds = [roll_width, roll_height]

    # --------------------------
    #         VARIABLES
    # --------------------------

    # DECISION VARIABLES

    # Define bottom-left corner of the pieces of paper to cut as 2-D (width-height) array of int decision variables
    pieces_corners = [[Int("x_%s" % i), Int("y_%s" % i)] for i in PIECES]

    # --------------------------
    #        CONSTRAINTS
    # --------------------------

    # DOMAIN CONSTRAINTS: reduce the domain for the bottom-left corners of the pieces of paper

    # The cut can not be done outside the paper roll: the bottom-left corner coordinates of the pieces of paper to cut
    # must not exceed the paper roll coordinates limit, considering also the dimension of the piece of paper
    domain_bound_constraints = [
        And(And(pieces_corners[i][x] >= lower_bounds[x],
                pieces_corners[i][x] <= upper_bounds[x] - pieces_dimensions[i][x]),
            And(pieces_corners[i][y] >= lower_bounds[y],
                pieces_corners[i][y] <= upper_bounds[y] - pieces_dimensions[i][y])) for i in PIECES]

    # IMPLIED CUMULATIVE CONSTRAINTS: define the maximum number of usable paper

    # The maximum usable quantity of paper is defined by the paper roll dimensions
    cumulative_constraints = [Sum(
        [If(And(y_coord >= pieces_corners[i][y], y_coord < pieces_corners[i][y] + pieces_dimensions[i][y]),
            pieces_dimensions[i][x], 0) for i in PIECES]) == roll_width for y_coord in Y_COORDINATES] + [Sum(
        [If(And(x_coord >= pieces_corners[i][x], x_coord < pieces_corners[i][x] + pieces_dimensions[i][x]),
            pieces_dimensions[i][y], 0) for i in PIECES]) == roll_height for x_coord in X_COORDINATES]

    # NON-OVERLAPPING CONSTRAINT: define the non-overlapping property fo the pieces of paper

    # The cutted pieces of paper must not overlap: the bottom-left corner coordinates must not be equal to other
    # coordinates of the paper roll which are already occupied by other pieces of paper

    non_overlapping_constraints = [Or(pieces_corners[i][x] + pieces_dimensions[i][x] <= pieces_corners[j][x],
                                      pieces_corners[i][y] + pieces_dimensions[i][y] <= pieces_corners[j][y],
                                      pieces_corners[j][x] + pieces_dimensions[j][x] <= pieces_corners[i][x],
                                      pieces_corners[j][y] + pieces_dimensions[j][y] <= pieces_corners[i][y])
                                   for i in PIECES for j in PIECES if i < j]

    # --------------------------
    #          SOLUTION
    # --------------------------

    solver = Solver()
    solver.add(domain_bound_constraints + cumulative_constraints + non_overlapping_constraints)

    return solver, PIECES, pieces_corners
Example #7
0
from lemsynth.lemsynth_engine import solveProblem

def notInChildren(x):
    return And(Not(IsMember(x, htree(lft(x)))), Not(IsMember(x, htree(rght(x)))))

# declarations
x, y = Vars('x y', fgsort)
nil, ret = Consts('nil ret', fgsort)
k = Const('k', intsort)
key = Function('key', fgsort, intsort)
lft = Function('lft', fgsort, fgsort)
rght = Function('rght', fgsort, fgsort)
dag = RecFunction('dag', fgsort, boolsort)
tree = RecFunction('tree', fgsort, boolsort)
htree = RecFunction('htree', fgsort, fgsetsort)
AddRecDefinition(dag, x, If(x == nil, True, And(notInChildren(x),
                                                And(dag(lft(x)), dag(rght(x))))))
AddRecDefinition(tree, x, If(x == nil, True,
                             And(notInChildren(x),
                                 And(SetIntersect(htree(lft(x)), htree(rght(x)))
                                     == fgsetsort.lattice_bottom,
                                     And(tree(lft(x)), tree(rght(x)))))))
AddRecDefinition(htree, x, If(x == nil, fgsetsort.lattice_bottom,
                              SetAdd(SetUnion(htree(lft(x)), htree(rght(x))), x)))
AddAxiom((), lft(nil) == nil)
AddAxiom((), rght(nil) == nil)

# vc
pgm = If(x == nil, ret == nil, ret == lft(x))
goal = Implies(tree(x), Implies(pgm, dag(ret)))

# check validity with natural proof solver and no hardcoded lemmas
Example #8
0
# declarations
x, y = Vars('x y', fgsort)
nil = Const('nil', fgsort)
k = Const('k', intsort)
nxt = Function('nxt', fgsort, fgsort)
lst = RecFunction('lst', fgsort, boolsort)
lseg = RecFunction('lseg', fgsort, fgsort, boolsort)
key = Function('key', fgsort, intsort)
keys = RecFunction('keys', fgsort, intsetsort)
AddRecDefinition(lst, x, If(x == nil, True, lst(nxt(x))))
AddRecDefinition(lseg, (x, y) , If(x == y, True, lseg(nxt(x), y)))
AddRecDefinition(keys, x, If(x == nil, fgsetsort.lattice_bottom, SetAdd(keys(nxt(x)), key(x))))
AddAxiom((), nxt(nil) == nil)

# vc
goal = Implies(lseg(x, y), Implies(And(And(And(x != nil, y != nil), lst(x)), key(y) == k), IsMember(k, keys(x))))

# check validity with natural proof solver and no hardcoded lemmas
np_solver = NPSolver()
solution = np_solver.solve(make_pfp_formula(goal))
if not solution.if_sat:
    print('goal (no lemmas) is valid')
else:
    print('goal (no lemmas) is invalid')

# hardcoded lemma
lemma_params = (x,y)
lemma_body = Implies(lseg(x, y), Implies(And(And(y != nil, lst(x)), key(y) == k), IsMember(k, keys(x))))
lemmas = {(lemma_params, lemma_body)}

# check validity of lemmas
Example #9
0
from naturalproofs.decl_api import Const, Consts, Function, RecFunction, AddRecDefinition, AddAxiom
from naturalproofs.pfp import make_pfp_formula
from naturalproofs.prover import NPSolver
import naturalproofs.proveroptions as proveroptions

# Declarations
a, b, c, zero = Consts('a b c zero', fgsort)
suc = Function('suc', fgsort, fgsort)
pred = Function('pred', fgsort, fgsort)
AddAxiom(a, pred(suc(a)) == a)
nat = RecFunction('nat', fgsort, boolsort)
add = RecFunction('add', fgsort, fgsort, fgsort, boolsort)
AddRecDefinition(nat, a, If(a == zero, True, nat(pred(a))))
AddRecDefinition(add, (a, b, c), If(a == zero, b == c, add(pred(a), suc(b), c)))
# Problem parameters
goal = Implies(add(a, b, c), Implies(And(nat(a), nat(b)), nat(c)))
pfp_of_goal = make_pfp_formula(goal)
# Call a natural proofs solver
npsolver = NPSolver()
# Configure the solver
npsolver.options.instantiation_mode = proveroptions.manual_instantiation
npsolver.options.terms_to_instantiate = {a, b, c, zero, pred(b), suc(b)}
# Ask for proof
npsolution = npsolver.solve(pfp_of_goal)


class AddIsNatTest(unittest.TestCase):
    def test1(self):
        self.assertFalse(npsolution.if_sat)

# Run from the Unix prompt '$' at the command line by issuing:
# $ python3 pythagorean_triples.py

# Run from the Python prompt '>>>' at the command line:
# >>> execfile ('pythagorean_triples.py')           # in Python2 only
# >>> exec(open("./pythagorean_triples.py").read()) # in Python2 and Python3

from z3 import Solver, Ints, And, sat, Exists
s = Solver()

# Declare three integer variables/constants of Z3Py {x, y, z} :
x, y, z = Ints('x y z')

# Assert that {x, y, z} are positive integers such that 0 < x < y < z :
s.add(And(0 < x, x < y, y < z, x >= 4, x % 2 == 0))

# Assert that x*x + y*y = z*z, i.e. (x,y,z) is a Pythagorean triple :
s.add(x * x + y * y == z * z)
s.add(x * x == 4 * y + 4)

n = 1
results = []
while s.check() == sat and n <= 10:
    m = s.model()
    results.append(m)
    s.add(x != m[x])
    n = n + 1

print(len(results), s.check())
Example #11
0
from naturalproofs.uct import fgsort, fgsetsort, intsort, intsetsort, boolsort
from naturalproofs.decl_api import Const, Consts, Var, Vars, Function, RecFunction, AddRecDefinition, AddAxiom
from naturalproofs.prover import NPSolver
import naturalproofs.proveroptions as proveroptions

from lemsynth.lemsynth_engine import solveProblem

# Declarations
x, y = Vars('x y', fgsort)
nil = Const('nil', fgsort)
nxt = Function('nxt', fgsort, fgsort)
lseg = RecFunction('lseg', fgsort, fgsort, boolsort)
cyclic = RecFunction('cyclic', fgsort, boolsort)
AddRecDefinition(lseg, (x, y),
                 If(x == y, True, If(x == nil, False, lseg(nxt(x), y))))
AddRecDefinition(cyclic, x, And(x != nil, lseg(nxt(x), x)))
AddAxiom((), nxt(nil) == nil)

# Problem parameters
goal = Implies(cyclic(x), cyclic(nxt(x)))

# parameters representing the grammar for synth-fun and
# terms on which finite model is extracted
# TODO: extract this automatically from grammar_string
v1, v2 = Vars('v1 v2', fgsort)
lemma_grammar_args = [v1, v2, nil]
lemma_grammar_terms = {v1, v2, nxt(v1), nxt(v2), nil}

name = 'cyclic-next'
grammar_string = importlib_resources.read_text('experiments',
                                               'grammar_{}.sy'.format(name))
Example #12
0
def require(pre, b, post):
    return And(b.pre() >= pre, b.post() / pre <= post, +b)
Example #13
0
x, y = Vars('x y', fgsort)
nil, ret = Consts('nil ret', fgsort)
k = Const('k', intsort)
key = Function('key', fgsort, intsort)
lft = Function('lft', fgsort, fgsort)
rght = Function('rght', fgsort, fgsort)
tree = RecFunction('tree', fgsort, boolsort)
htree = RecFunction('htree', fgsort, fgsetsort)
reach_lr = RecFunction('reach_lr', fgsort, fgsort, boolsort)
AddRecDefinition(
    tree, x,
    If(
        x == nil, True,
        And(
            notInChildren(x),
            And(
                SetIntersect(htree(lft(x)),
                             htree(rght(x))) == fgsetsort.lattice_bottom,
                And(tree(lft(x)), tree(rght(x)))))))
AddRecDefinition(
    htree, x,
    If(x == nil, fgsetsort.lattice_bottom,
       SetAdd(SetUnion(htree(lft(x)), htree(rght(x))), x)))
AddRecDefinition(
    reach_lr, (x, y),
    If(x == y, True, Or(reach_lr(lft(x), y), reach_lr(rght(x), y))))
AddAxiom((), lft(nil) == nil)
AddAxiom((), rght(nil) == nil)

# vc
goal = Implies(reach_lr(x, y), Implies(And(key(x) != k, tree(x)), tree(y)))
Example #14
0
    CZGate._trivial_if = lambda self, x1: True
    CZGate._postconditions = lambda self, x1, y1: y1 == x1

    # SGate
    SGate._trivial_if = lambda self, x1: True
    SGate._postconditions = lambda self, x1, y1: y1 == x1
    SdgGate._trivial_if = lambda self, x1: True
    SdgGate._postconditions = lambda self, x1, y1: y1 == x1

    # TGate
    TGate._trivial_if = lambda self, x1: True
    TGate._postconditions = lambda self, x1, y1: y1 == x1
    TdgGate._trivial_if = lambda self, x1: True
    TdgGate._postconditions = lambda self, x1, y1: y1 == x1

    # RzGate = U1Gate
    RZGate._trivial_if = lambda self, x1: True
    RZGate._postconditions = lambda self, x1, y1: y1 == x1
    CRZGate._trivial_if = lambda self, x1: True
    CRZGate._postconditions = lambda self, x1, y1: y1 == x1
    U1Gate._trivial_if = lambda self, x1: True
    U1Gate._postconditions = lambda self, x1, y1: y1 == x1
    CU1Gate._trivial_if = lambda self, x1: True
    CU1Gate._postconditions = lambda self, x1, y1: y1 == x1

    # MULTI-QUBIT GATES #
    # SwapGate
    SwapGate._trivial_if = lambda self, x1, x2: x1 == x2
    SwapGate._postconditions = lambda self, x1, x2, y1, y2: And(x1 == y2, x2 == y1)
    CSwapGate._trivial_if = lambda self, x1, x2: x1 == x2
    CSwapGate._postconditions = lambda self, x1, x2, y1, y2: And(x1 == y2, x2 == y1)
Example #15
0
 def has(self, x, y):
     return And(self.s1(x), self.s2(y))
Example #16
0
x = Var('x', fgsort)
c, s, nil = Consts('c s nil', fgsort)
v1 = Function('v1', fgsort, fgsort)
v2 = Function('v2', fgsort, fgsort)
p = Function('p', fgsort, fgsort)
n = Function('n', fgsort, fgsort)

reach_pgm = RecFunction('reach_pgm', fgsort, boolsort)

# precondition
AddAxiom((), v1(s) == v2(s))

cond = v1(p(x)) != nil
assign1 = v1(x) == n(v1(p(x)))
assign2 = If(v2(p(x)) != c, v2(x) == n(v2(p(x))), v2(x) == v2(p(x)))
assign = And(assign1, assign2)
AddRecDefinition(reach_pgm, x,
                 If(x == s, True, And(reach_pgm(p(x)), And(cond, assign))))

# vc
lhs = v1(x) == nil
rhs = Or(v2(x) == nil, v2(x) == c)
goal = Implies(reach_pgm(x), Implies(lhs, rhs))

# check validity with natural proof solver and no hardcoded lemmas
np_solver = NPSolver()
solution = np_solver.solve(make_pfp_formula(goal))
if not solution.if_sat:
    print('goal (no lemmas) is valid')
else:
    print('goal (no lemmas) is invalid')
Example #17
0
def main():
    """Status Park (Loop) solver example."""
    for row in GIVENS:
        for cell in row:
            sys.stdout.write(cell)
        print()

    points = []
    for y, row in enumerate(GIVENS):
        for x, c in enumerate(row):
            if c != X:
                points.append(Point(y, x))
    lattice = RectangularLattice(points)

    sym = grilops.loops.LoopSymbolSet(lattice)
    sym.append("EMPTY", " ")

    sg = grilops.SymbolGrid(lattice, sym)
    lc = grilops.loops.LoopConstrainer(sg, single_loop=True)
    sc = grilops.shapes.ShapeConstrainer(lattice,
                                         [[Vector(y, x) for y, x in shape]
                                          for shape in SHAPES],
                                         solver=sg.solver,
                                         allow_rotations=True,
                                         allow_reflections=True,
                                         allow_copies=False)

    for p in points:
        if GIVENS[p.y][p.x] == W:
            # White circles must be part of the loop.
            sg.solver.add(lc.inside_outside_grid[p] == grilops.loops.L)
        elif GIVENS[p.y][p.x] == B:
            # Black circles must be part of a shape.
            sg.solver.add(sc.shape_type_grid[p] != -1)

        # A cell is part of the loop if and only if it is not part of
        # any shape.
        sg.solver.add((lc.inside_outside_grid[p] == grilops.loops.L) == (
            sc.shape_type_grid[p] == -1))

        # Orthogonally-adjacent cells must be part of the same shape.
        for n in sg.edge_sharing_neighbors(p):
            np = n.location
            sg.solver.add(
                Implies(
                    And(sc.shape_type_grid[p] != -1,
                        sc.shape_type_grid[np] != -1),
                    sc.shape_type_grid[p] == sc.shape_type_grid[np]))

    if sg.solve():
        sg.print()
        print()
        sc.print_shape_types()
        print()
        if sg.is_unique():
            print("Unique solution")
        else:
            print("Alternate solution")
            sg.print()
    else:
        print("No solution")
Example #18
0
                                           minr(rght(x)))))
AddRecDefinition(
    maxr, x, If(x == nil, -1, max_intsort(key(x), maxr(lft(x)),
                                          maxr(rght(x)))))
AddRecDefinition(
    bst, x,
    If(
        x == nil, True,
        And(
            0 < key(x),
            And(
                key(x) < 100,
                And(
                    bst(lft(x)),
                    And(
                        bst(rght(x)),
                        And(
                            maxr(lft(x)) <= key(x),
                            And(
                                key(x) <= minr(rght(x)),
                                And(
                                    notInChildren(x),
                                    SetIntersect(hbst(lft(x)), hbst(rght(x)))
                                    == fgsetsort.lattice_bottom)))))))))
AddRecDefinition(
    hbst, x,
    If(x == nil, fgsetsort.lattice_bottom,
       SetAdd(SetUnion(hbst(lft(x)), hbst(rght(x))), x)))
AddAxiom((), lft(nil) == nil)
AddAxiom((), rght(nil) == nil)

# vc
def all_commands_obeyed(state: EncodedState,
                        commands: Iterable[Command]) -> BoolRef:
    logging.info('final state constraint')
    return And([commands_obeyed(state, c) for c in logging_tqdm(commands)])
Example #20
0
 def has(self, x, y):
     return And(self.r1(x, y), Not(self.r2(x, y)))
Example #21
0
def notInChildren(x):
    return And(Not(IsMember(x, htree(lft(x)))), Not(IsMember(x, htree(rght(x)))))
Example #22
0
 def has(self, x, y):
     return And(self.r(x, y), self.s(y))
Example #23
0
            for mm in range(m):
                z3.add(pi[m][t] != pi[mm][t])

    for l in range(L):
        z3.add(time[l] >= 0, time[l] < T)
        if l in G_1:
            z3.add(space[l] >= 0, space[l] < N)
            for t in range(T):
                z3.add(Implies(time[l] == t, pi[g[l]][t] == space[l]))
        elif l in G_2:
            z3.add(space[l] >= 0, space[l] < K)
            for k in range(K):
                for t in range(T):
                    z3.add(
                        Implies(
                            And(time[l] == t, space[l] == k),
                            Or(
                                And(e[k][0] == pi[g[l][0]][t],
                                    e[k][1] == pi[g[l][1]][t]),
                                And(e[k][1] == pi[g[l][0]][t],
                                    e[k][0] == pi[g[l][1]][t]))))

    for d in D:
        z3.add(time[d[0]] < time[d[1]])
    """
    # just for adder.qasm on ibmqx2 experiment compared with Wille et al., 2019
    z3.add(time[3] <= time[8])
    z3.add(time[8] <= time[9])
    z3.add(time[9] <= time[10])
    z3.add(time[10] <= time[11])
    z3.add(time[11] <= time[12])
Example #24
0
 def has(self, x, y):
     a = const('a', get_sort_ran())
     return Exists(a, And(self.r(x, a), self.s(a, y)))
def writeQDIMACS(filename, constraint, quantifiers, bitmap=None):
    # filename: String
    # constraints: list of BV constraints
    # quantifiers: list of tuples (['a','e','max','count'], list of vars)

    assert_consistent_quantifiers(quantifiers)

    log('Bit blasting')
    bitmap = {}

    for q in quantifiers:
        bitvecs = filter(is_bv, q[1])
        localBitmap, localBitmapConstraints = create_bitmap(bitvecs)
        bitmap.update(localBitmap)
        constraint = And(localBitmapConstraints, constraint)
        newQuantifiedVars = filter(lambda v: not is_bv(v), q[1])
        for (_, boolvar) in localBitmap.iteritems():
            newQuantifiedVars.append(boolvar)
        q[1] = newQuantifiedVars

    g = Goal()
    g.add(constraint)
    matrix = []
    t = Then('simplify', 'bit-blast', 'tseitin-cnf')
    subgoal = t(g)
    # print(subgoal[0][0].children()[1].children()[0] == bitmap())
    assert len(subgoal) == 1

    # print('Printing quantifier')
    # print(quantifiers)
    # print('Printing goal')
    # print(g)
    # exit()

    max_var = 0
    var_mapping = {}  # maps to qdimacs variables

    textFile = open(filename, "w")

    log('Creating and writing symbol table')
    textFile.write('c Symbol table for bitvectors\n')
    symbol_table = []
    for ((bv, i), boolvar) in bitmap.iteritems():
        max_var += 1
        var_mapping[boolvar.get_id()] = max_var
        # symbol_table.append('c ' + str(boolvar) + ' --> ' + str(max_var))
        textFile.write('c ' + str(boolvar) + ' --> ' + str(max_var) + '\n')

    log('Reserving variable names for quantified variables')
    for i, q in enumerate(quantifiers):
        for var in q[1]:
            if var.get_id() not in var_mapping:
                max_var += 1
                var_mapping[var.get_id()] = max_var

    # minTseitin = max_var + 1
    Tseitin_vars = []

    log('Generating clauses ... (this may take a while)')
    clause_num = 0
    for c in subgoal[0]:
        clause_num += 1
        if clause_num % 10000 == 0:
            log('  {} clauses'.format(clause_num))
        if is_or(c):
            clause = ''
            for l in c.children():  # literals
                max_var, lit_str = encode_literal(var_mapping, Tseitin_vars,
                                                  max_var, l)
                clause += lit_str
            matrix.append(clause)
        elif is_const(c) or is_not(c):
            max_var, lit_str = encode_literal(var_mapping, Tseitin_vars,
                                              max_var, c)
            matrix.append(lit_str)
        else:
            log('Error: Unknown element ' + str(c))
            assert false
    matrix.append('')
    log('  Generated ' + str(clause_num) + ' clauses')

    log('Writing header')
    textFile.write('p cnf {} {}\n'.format(max_var, clause_num))

    # Extending quantifiers by innermost existential if necessary
    if quantifiers[-1][0] == 'a' and len(
            Tseitin_vars) > 0:  #  max_var + 1 - minTseitin > 0
        quantifiers.append(['e', []])  # empty existential

    log('Writing quantifiers')
    for i, q in enumerate(quantifiers):
        textFile.write(q[0])
        for v in q[1]:
            # try:
            v_id = v.get_id()
            textFile.write(' ' + str(var_mapping[v_id]))
            # except Exception as ex:
            #     log(' Error when writing var {} to file ({})'.format(str(v), str(ex)))
            #
            #     template = "An exception of type {0} occurred. Arguments:\n{1!r}"
            #     message = template.format(type(ex).__name__, ex.args)
            #     print message
            #
            #     exit()

        if i == len(quantifiers) - 1:
            log('Adding {} Tseitin variables'.format(len(Tseitin_vars)))
            for varID in Tseitin_vars:
                textFile.write(' ' + str(varID))

            # for varID in range(minTseitin,max_var+1):
#                 # log('Adding var {}'.format(varID))
#                 textFile.write(' '+str(varID))
#                 # quantifiers[-1][1].append(varID)
# log('  OK (added {} Tseitin vars)'.format(len(range(minTseitin,max_var+1))))

        textFile.write(' 0\n')

    log('Writing clauses')
    textFile.write('0\n'.join(matrix))
    textFile.close()

    return var_mapping
Example #26
0
 def has(self, y):
     x = const('x', get_sort_dom())
     return Exists(x, And(self.r(x, y), self.s(x)))
Example #27
0
    # a is greater
    if (x > y): #throws: z3.z3types.Z3Exception: Symbolic expressions cannot be cast to concrete Boolean values.
        return GCD(x-y, y)
    return GCD(x, y-x)

# def CoPrime(x, y):
#     return math.gcd(x, y) == 1        #x, y are 'ArithRef' not 'int' :<

def CoPrime(x, y):
    return GCD(x, y) == 1

# Declare three integer variables/constants of Z3Py {x, y, z} :
x, y, z, a, b = Ints ('x y z a b')

# Assert that {x, y, z} are positive integers such that 0 < x < y < z :
s.add (And( 0 < x , x < y , y < z ) )

# Assert that x*x + y*y = z*z, i.e. (x,y,z) is a Pythagorean triple :
s.add ( x * x + y * y == z * z )

# x = a^2 - b^2, y = 2ab, z = a^2 + b^2
s.add(And(x == (a * a) - (b * b), y == 2 * a * b, z == (a * a) + (b * b)))

# a>b>0
s.add(And(b > 0, a > b))

# a and b both not odd (idk why this works)
s.add(Or(And(Odd(a), Not(Odd(b))), And(Odd(b), Not(Odd(a)))))
s.add(Not(Odd(a) == Odd(b))) #ok apparently i needed both of these....?

#a and b coprime (GCD of both numbers == 1)
Example #28
0
 def has(self, x):
     y = const('y', get_sort_ran())
     return Exists(y, And(self.r(x, y), self.s(y)))
Example #29
0
def not_(constraint: Union[BoolRef, _NamedUIDObject]) -> BoolRef:
    """Boolean negation of the constraint."""
    return Not(And(_get_assertions(constraint)))
Example #30
0
def havoc(s):
    p = prog(s, "havoc")
    x, y = elms("x y")
    s.add(ForAll([x, y], And(p.set(x), p.pre(x), p.post(x, y))))
    return p