Example #1
0
from z3 import Optimize, Real, If

x = Real('x')
y = Real('y')
z = Real('z')


def z3abs(obj):
    return If(x > 0, x, -x)

optimizer = Optimize()
# optimizer.add(x>0.0)
# optimizer.add(y>0.0)
optimizer.add(x*x+y*y==1.0)
optimizer.add_soft(z == x+y)
optimizer.maximize(z)
result = optimizer.check()

print(optimizer.model())
Example #2
0
def run_inference(file_name=None, base_folder=None):
    if not file_name:
        if len(sys.argv) >= 2 and sys.argv[1] != '--help':
            file_name = sys.argv[1]
            if len(sys.argv) >= 3:
                base_folder = sys.argv[2]
        else:
            print_help()
            return
    start_time = time.time()
    class_type_params, func_type_params = configure_inference([flag for flag in sys.argv[2:] if flag.startswith("--")])

    if not base_folder:
        base_folder = ''

    if file_name.endswith('.py'):
        file_name = file_name[:-3]

    t = ImportHandler.get_module_ast(file_name, base_folder)

    solver = z3_types.TypesSolver(t, base_folder=base_folder, type_params=func_type_params,
                                  class_type_params=class_type_params)

    context = Context(t, t.body, solver)
    context.type_params = solver.config.type_params
    context.class_type_params = solver.config.class_type_params
    solver.infer_stubs(context, infer)

    for stmt in t.body:
        infer(stmt, context, solver)

    solver.push()
    end_time = time.time()
    print("Constraints collection took  {}s".format(end_time - start_time))

    start_time = time.time()
    if config.config['enable_soft_constraints']:
        check = solver.optimize.check()
    else:
        check = solver.check(solver.assertions_vars)
    end_time = time.time()
    print("Constraints solving took  {}s".format(end_time - start_time))

    write_path = "inference_output/" + base_folder
    if not os.path.exists(write_path):
        os.makedirs(write_path)

    if write_path.endswith('/'):
        write_path = write_path[:-1]

    file = open(write_path + '/{}_constraints_log.txt'.format(file_name.replace('/', '.')), 'w')
    file.write(print_solver(solver))
    file.close()

    if check == z3_types.unsat:
        print("Check: unsat")
        if config.config["print_unsat_core"]:
            print("Writing unsat core to {}".format(write_path))
            if config.config['enable_soft_constraints']:
                solver.check(solver.assertions_vars)
                core = solver.unsat_core()
            else:
                core = solver.unsat_core()
            core_string = '\n'.join(solver.assertions_errors[c] for c in core)
            file = open(write_path + '/{}_unsat_core.txt'.format(file_name), 'w')
            file.write(core_string)
            file.close()
            model = None
            
            opt = Optimize(solver.ctx)
            for av in solver.assertions_vars:
                opt.add_soft(av)
            for a in solver.all_assertions:
                opt.add(a)
            for a in solver.z3_types.subtyping:
                opt.add(a)
            for a in solver.z3_types.subst_axioms:
                opt.add(a)
            for a in solver.forced:
                opt.add(a)
            start_time = time.time()
            opt.check()
            model = opt.model()
            end_time = time.time()
            print("Solving relaxed model took  {}s".format(end_time - start_time))
            for av in solver.assertions_vars:
                if not model[av]:
                    print("Unsat:")
                    print(solver.assertions_errors[av])
        else:
            opt = Optimize(solver.ctx)
            for av in solver.assertions_vars:
                opt.add_soft(av)
            for a in solver.all_assertions:
                opt.add(a)
            for a in solver.z3_types.subtyping:
                opt.add(a)
            for a in solver.z3_types.subst_axioms:
                opt.add(a)
            for a in solver.forced:
                opt.add(a)
            start_time = time.time()
            opt.check()
            model = opt.model()
            end_time = time.time()
            print("Solving relaxed model took  {}s".format(end_time - start_time))
            for av in solver.assertions_vars:
                if not model[av]:
                    print("Unsat:")
                    print(solver.assertions_errors[av])
    else:
        if config.config['enable_soft_constraints']:
            model = solver.optimize.model()
        else:
            model = solver.model()

    if model is not None:
        print("Writing output to {}".format(write_path))
        context.generate_typed_ast(model, solver)
        ImportHandler.add_required_imports(file_name, t, context)

        write_path += '/' + file_name + '.py'

        if not os.path.exists(os.path.dirname(write_path)):
            os.makedirs(os.path.dirname(write_path))
        file = open(write_path, 'w')
        file.write(astunparse.unparse(t))
        file.close()

        ImportHandler.write_to_files(model, solver)
Example #3
0
def main(args):
    # print(args)
    seed = int(args[0])
    random.seed(seed)

    # X is a three dimensional grid containing (t, x, y)
    X = [[[Bool("x_%s_%s_%s" % (k, i, j)) for j in range(GRID_SZ)]
          for i in range(GRID_SZ)] for k in range(HOPS + 1)]

    s = Optimize()

    # Initial Constraints
    s.add(X[0][0][0])
    s.add([Not(cell) for row in X[0] for cell in row][1:])

    # Final constraints
    s.add(X[HOPS][GRID_SZ - 1][GRID_SZ - 1])
    s.add([Not(cell) for row in X[HOPS] for cell in row][:-1])

    #Sanity Constraints
    for grid in X:
        for i in range(len(grid)):
            for j in range(len(grid)):
                for p in range(len(grid)):
                    for q in range(len(grid)):
                        if not (i == p and j == q):
                            s.add(Not(And(grid[i][j], grid[p][q])))

    #Motion primitives
    for t in range(HOPS):
        for x in range(GRID_SZ):
            for y in range(GRID_SZ):
                temp = Or(X[t][x][y])
                if (x + 1 < GRID_SZ):
                    temp = Or(temp, X[t][x + 1][y])
                if (y + 1 < GRID_SZ):
                    temp = Or(temp, X[t][x][y + 1])
                if (x - 1 >= 0):
                    temp = Or(temp, X[t][x - 1][y])
                if (y - 1 >= 0):
                    temp = Or(temp, X[t][x][y - 1])
                s.add(simplify(Implies(X[t + 1][x][y], temp)))

    # Cost constraints
    for t in range(HOPS):
        for x in range(GRID_SZ):
            for y in range(GRID_SZ):
                s.add_soft(Not(X[t][x][y]),
                           distance(x, y, GRID_SZ - 1, GRID_SZ - 1))

    hop = 0
    if s.check() == sat:
        m = s.model()
    else:
        print("No.of hops too low...")
        exit(1)
    obs1 = Obstacle(0, 3, GRID_SZ)

    robot_plan = []
    obs_plan = []
    # for a in s.assertions():
    #     print(a)
    while (hop < HOPS):

        robot_pos = (0, 0) if hop == 0 else get_robot_pos(m, hop)
        obs_pos = obs1.next_move()

        s.add(X[hop][robot_pos[0]][robot_pos[1]])
        # print("hop is ", hop)
        # print("robot at ", robot_pos)
        # print("obs at ", obs_pos)

        if robot_pos == obs_pos:
            print("COLLISION!!!")
            print(robot_plan)
            print(obs_plan)
            exit()

        robot_plan.append(robot_pos)
        obs_plan.append(obs_pos)
        #next position of the robot
        next_robot_pos = get_robot_pos(m, hop + 1)
        s.push()
        # print("intersection points")
        # print(intersection_points(robot_pos, obs_pos))
        # count = 0
        next_overlap = next_intersection_points(next_robot_pos, obs_pos)
        for (x, y) in next_overlap:
            # consider only the intersection with the next step in the plan
            s.add(Not(X[hop + 1][x][y]))

        if len(next_overlap) > 0:  # we need to find a new path
            if (s.check() == unsat):
                print("stay there")
            else:
                m = s.model()
                # print("Plan for hop = " + str(hop+1))
                # print(get_plan(m))
                hop += 1
        else:
            # we don't need to worry about the path
            hop += 1

        s.pop()

    robot_pos = get_robot_pos(m, hop)
    obs_pos = obs1.next_move()
    # print("hop is ", hop)
    # print("robot at ", robot_pos)
    # print("obs at ", obs_pos)
    robot_plan.append(robot_pos)
    obs_plan.append(obs_pos)

    if path_valid(robot_plan, obs_plan):
        print("PATH IS VALID!!!")
    else:
        print("PATH IS INVALID!!!")
    print("ROBOT MOVEMENT:")
    print(robot_plan)
    print("OBSTACLE MOVEMENT:")
    print(obs_plan)
Example #4
0
def main(args):
    # print(args)
    seed = int(args[0])
    random.seed(seed)
    GRID_SZ = int(args[1])
    HOPS = int(args[2])


    print("WORKSPACE SIZE (%s x %s)" % (GRID_SZ, GRID_SZ))
    print("HOPS ALLOWED = %s" % (HOPS))


    
    # X is a three dimensional grid containing (t, x, y)
    X =  [ [ [ Bool("x_%s_%s_%s" % (k, i, j)) for j in range(GRID_SZ) ]
        for i in range(GRID_SZ) ] 
        for k in range(HOPS+1)]

    s = Optimize()

    # Initial Constraints
    s.add(X[0][0][0])
    s.add([Not(cell) for row in X[0] for cell in row][1:])

    # Final constraints
    s.add(X[HOPS][GRID_SZ-1][GRID_SZ-1])
    s.add([Not(cell) for row in X[HOPS] for cell in row][:-1])

    #Sanity Constraints
    for grid in X:
        for i in range(len(grid)):
            for j in range(len(grid)):
                for p in range(len(grid)):
                    for q in range(len(grid)):
                        if not (i==p and j==q):
                            s.add(Not(And(grid[i][j], grid[p][q])))
    
    #Motion primitives
    for t in range(HOPS):
        for x in range(GRID_SZ):
                for y in range(GRID_SZ):
                    temp = Or(X[t][x][y])
                    if (x+1 < GRID_SZ):
                        temp = Or(temp, X[t][x+1][y])
                    if (y+1 < GRID_SZ):
                        temp = Or(temp, X[t][x][y+1])
                    if (x-1 >= 0):
                        temp = Or(temp, X[t][x-1][y])
                    if (y-1 >= 0):
                        temp = Or(temp, X[t][x][y-1])
                    s.add(simplify(Implies(X[t+1][x][y], temp)))


    # Cost constraints
    for t in range(HOPS):
        for x in range(GRID_SZ):
            for y in range(GRID_SZ):
                s.add_soft(Not(X[t][x][y]), distance(x, y, GRID_SZ-1, GRID_SZ-1))


    if s.check() == sat:
        m = s.model()
    else:
        print("No.of hops too low...")
        exit(1)
    # obs1 = Obstacle(0, 3, GRID_SZ)

    obs = [Obstacle(3, 3, GRID_SZ), Obstacle(4, 5, GRID_SZ), Obstacle(6, 7, GRID_SZ), Obstacle(8, 9, GRID_SZ), Obstacle(9, 3, GRID_SZ), Obstacle(1, 8, GRID_SZ), Obstacle(7, 7, GRID_SZ)]
    # obs = [Obstacle(3, 3, GRID_SZ)]


    ## 

    # obs = []
    # for i in range(0, GRID_SZ-1):
    #     for j in range(0, GRID_SZ-1):
    #         if (i+j)%3 != 0:
    #             print(i, j)
    #             obs.append(Obstacle(i, j, GRID_SZ))
    # print("-----")




    robot_plan = []
    hop = 0
    stay_count = 0
    # obs_plan = []
    # for a in s.assertions():
    #     print(a)
    while (hop < HOPS):
        # print("hops = ", hop)
        if stay_count > 0:
            robot_pos = [robot_plan[-stay_count][0], robot_plan[-stay_count][1]]
            next_robot_pos = get_robot_pos(m,hop-stay_count)
        else:
            robot_pos = get_robot_pos(m,hop)
            next_robot_pos = get_robot_pos(m,hop+1)
        # print("robot_pos = ", robot_pos)

        # for obstacle in obs:
        #     print("Obstacle at ", (obstacle.x, obstacle.y))

        # print('-----------')
        s.add(X[hop][robot_pos[0]][robot_pos[1]])

        robot_plan.append(robot_pos)
        # obs_plan.append(obs_pos)
        #next position of the robot
        # if (stay:
        
        # s.push() 
        # print("intersection points")
        # print(intersection_points(robot_pos, obs_pos))
        # count = 0
        # print("blah!!!")
        next_overlap = []
        for obstacle in obs:
            next_overlap = next_overlap + next_intersection_points(robot_pos, (obstacle.x, obstacle.y))
       
        # print("Lenght = ", len(next_overlap))
        for (x, y) in next_overlap:
            # consider only the intersection with the next step in the plan
            if ((0 <= x < GRID_SZ) and (0 <= y < GRID_SZ)):
                s.add(Not(X[hop+1][x][y]))

        # print("ceeeee!!", next_robot_pos in set(next_overlap))
        
        if next_robot_pos in set(next_overlap): # we need to find a new path
            # print("just before check")
            if (s.check() == unsat):
                print("stay there")
                print(robot_pos)
                stay_count += 1
                # hop -= 1
                hop += 1
            else:
                stay_count = 0
                m = s.model()
                hop += 1
            # print("just after check")
        else:
            # we don't need to worry about the path
            hop += 1
        # print('dssdfdsfds')
        # s.pop() 
        for obstacle in obs:
            # print("12")
            obstacle.next_move()

    if (stay_count > 0):
        return 1    
    
    robot_pos = get_robot_pos(m,hop)
    for obstacle in obs:
        obstacle.next_move()
    # print("hop is ", hop)
    # print("robot at ", robot_pos)
    # print("obs at ", obs_pos)
    robot_plan.append(robot_pos)
    # obs_plan.append(obs_pos)

    for obstacle in obs:
        if not path_valid(robot_plan, obstacle.path):
            print("PATH IS INVALID!!!")


    print("ROBOT MOVEMENT:")
    print(robot_plan)
    print("OBSTACLE MOVEMENT:")
    for obstacle in obs:
        print(obstacle.path)