Ejemplo n.º 1
0
def main():
    connect(use_gui=True)
    print(get_json_filenames())

    #problem_filenames = sorted(os.listdir(openrave_directory))
    #problem_filenames = ['{}.json'.format(name) for name in FFROB]
    #problem_filenames = ['sink_stove_4_30.json'] # 'dinner.json' | 'simple.json'
    problem_filenames = ['simple.json'] # 'dinner.json' | 'simple.json'

    # Mac width/height
    #width = 2560
    #height = 1600
    #
    #640, 480
    screenshot = False

    for problem_filename in problem_filenames:
        load_json_problem(problem_filename)
        if screenshot:
            problem_name = problem_filename.split('.')[0]
            image_filename = "{}.png".format(problem_name)
            image_path = os.path.join(SCREENSHOT_DIR, image_filename)
            wait_for_interrupt(max_time=0.5)
            os.system("screencapture -R {},{},{},{} {}".format(
                225, 200, 600, 500, image_path))
        else:
            wait_if_gui()
    disconnect()
Ejemplo n.º 2
0
def main():
    connect(use_gui=True)
    add_data_path()

    plane = p.loadURDF("plane.urdf")
    with HideOutput():
        with LockRenderer():
            robot = load_model(FRANKA_URDF, fixed_base=True)
    dump_body(robot)
    print('Start?')
    wait_for_user()

    tool_link = link_from_name(robot, 'panda_hand')
    joints = get_movable_joints(robot)
    print('Joints', [get_joint_name(robot, joint) for joint in joints])
    sample_fn = get_sample_fn(robot, joints)
    for i in range(10):
        print('Iteration:', i)
        conf = sample_fn()
        set_joint_positions(robot, joints, conf)
        wait_for_user()
        test_retraction(robot,
                        PANDA_INFO,
                        tool_link,
                        max_distance=0.01,
                        max_time=0.05)
    disconnect()
Ejemplo n.º 3
0
def main():
    # The URDF loader seems robust to package:// and slightly wrong relative paths?
    connect(use_gui=True)
    add_data_path()

    plane = p.loadURDF("plane.urdf")
    #with HideOutput():
    with LockRenderer():
        robot = load_model(MOVO_URDF, fixed_base=True)
    dump_body(robot)
    print('Start?')
    wait_for_user()

    #joint_names = HEAD_JOINTS
    #joints = joints_from_names(robot, joint_names)
    joints = get_movable_joints(robot)
    print('Joints', [get_joint_name(robot, joint) for joint in joints])
    sample_fn = get_sample_fn(robot, joints)
    for i in range(10):
        print('Iteration:', i)
        conf = sample_fn()
        set_joint_positions(robot, joints, conf)
        wait_for_user()

    disconnect()
Ejemplo n.º 4
0
def main():
    connect(use_gui=True)
    disable_real_time()
    set_default_camera()

    problem = pick_problem(arm='left', grasp_type='side')
    grasp_gen = get_grasp_gen(problem, collisions=False)
    ik_ir_fn = get_ik_ir_gen(problem, max_attempts=100, teleport=False)
    pose = Pose(problem.movable[0], support=problem.surfaces[0])
    base_conf = Conf(problem.robot, get_group_joints(problem.robot, 'base'))
    ik_fn = get_ik_fn(problem)
    found = False
    saved_world = WorldSaver()
    for grasp, in grasp_gen(problem.movable[0]):
        print(grasp.value)
        # confs_cmds = ik_ir_fn(problem.arms[0], problem.movable[0], pose, grasp)
        # for conf, cmds in confs_cmds:
        #     found = True
        cmds = ik_fn(problem.arms[0], problem.movable[0], pose, grasp,
                     base_conf)
        if cmds is not None:
            cmds = cmds[0]
            found = True
        if found:
            break
    if not found:
        raise Exception('No grasp found')
    saved_world.restore()
    for cmd in cmds.commands:
        print(cmd)
    control_commands(cmds.commands)
    print('Quit?')

    wait_for_user()
    disconnect()
Ejemplo n.º 5
0
def main():
    world = connect(use_gui=True)

    #model = 'oil'
    model = 'soup'

    point_path = os.path.join(DATA_DIRECTORY, 'clouds', CLOUDS[model])
    mesh_path = os.path.join(DATA_DIRECTORY, 'meshes',
                             MESHES[model])  # off | ply | wrl
    #ycb_path = os.path.join(DATA_DIRECTORY, 'ycb', 'plastic_wine_cup', 'meshes', 'tsdf.stl') # stl | ply
    ycb_path = os.path.join(DATA_DIRECTORY, 'ycb', 'plastic_wine_cup',
                            'textured_meshes',
                            'optimized_tsdf_texture_mapped_mesh.obj')  # ply

    print(point_path)
    print(mesh_path)
    print(ycb_path)

    #mesh = read_mesh_off(mesh_path, scale=0.001)
    #print(mesh)
    points = read_pcd_file(point_path)
    #print(points)
    #print(convex_hull(points))
    mesh = mesh_from_points(points)
    #print(mesh)

    body = create_mesh(mesh, color=(1, 0, 0, 1))
    #print(get_num_links(body))
    #print(mesh_from_body(body))

    #set_point(body, (1, 1, 1))
    wait_for_interrupt()
    disconnect()
Ejemplo n.º 6
0
def main():
    parser = argparse.ArgumentParser()  # Automatically includes help
    parser.add_argument('-arm', required=True)
    parser.add_argument('-grasp', required=True)
    parser.add_argument('-viewer', action='store_true', help='enable viewer.')
    args = parser.parse_args()

    arm = args.arm
    other_arm = get_other_arm(arm)
    grasp_type = args.grasp

    connect(use_gui=args.viewer)
    add_data_path()

    with HideOutput():
        robot = load_pybullet(DRAKE_PR2_URDF)
    set_group_conf(robot, 'torso', [0.2])
    set_arm_conf(robot, arm, get_carry_conf(arm, grasp_type))
    set_arm_conf(robot, other_arm, arm_conf(other_arm, REST_LEFT_ARM))

    #plane = p.loadURDF("plane.urdf")
    #table = p.loadURDF("table/table.urdf", 0, 0, 0, 0, 0, 0.707107, 0.707107)
    table = create_table()
    box = create_box(.07, .07, .14)

    #create_inverse_reachability(robot, box, table, arm=arm, grasp_type=grasp_type)
    create_inverse_reachability2(robot,
                                 box,
                                 table,
                                 arm=arm,
                                 grasp_type=grasp_type)
    disconnect()
Ejemplo n.º 7
0
def main(display='control'):  # control | execute | step
    connect(use_gui=True)
    disable_real_time()
    # KUKA_IIWA_URDF | DRAKE_IIWA_URDF
    robot = load_model(DRAKE_IIWA_URDF, fixed_base=True)
    # floor = load_model('models/short_floor.urdf')
    floor = p.loadURDF("plane.urdf")
    block = load_model(
        "models/drake/objects/block_for_pick_and_place_heavy.urdf", fixed_base=False)
    set_pose(block, Pose(Point(y=0.5, z=stable_z(block, floor))))
    set_default_camera()
    dump_world()

    saved_world = WorldSaver()
    command = plan(robot, block, fixed=[floor], teleport=False)
    if (command is None) or (display is None):
        print('Unable to find a plan!')
        return

    saved_world.restore()
    update_state()
    user_input('{}?'.format(display))
    if display == 'control':
        enable_gravity()
        command.control(real_time=False, dt=0)
    elif display == 'execute':
        command.refine(num_steps=10).execute(time_step=0.005)
    elif display == 'step':
        command.step()
    else:
        raise ValueError(display)

    print('Quit?')
    wait_for_user()
    disconnect()
Ejemplo n.º 8
0
def main(display='execute'):  # control | execute | step
    connect(use_gui=True)
    disable_real_time()
    draw_global_system()
    with HideOutput():
        robot = load_model(DRAKE_IIWA_URDF)  # KUKA_IIWA_URDF | DRAKE_IIWA_URDF
        floor = load_model('models/short_floor.urdf')
    block = load_model(BLOCK_URDF, fixed_base=False)
    set_pose(block, Pose(Point(y=0.5, z=stable_z(block, floor))))
    set_default_camera(distance=2)
    dump_world()

    saved_world = WorldSaver()
    command = plan(robot, block, fixed=[floor], teleport=False)
    if (command is None) or (display is None):
        print('Unable to find a plan!')
        return

    saved_world.restore()
    update_state()
    wait_if_gui('{}?'.format(display))
    if display == 'control':
        enable_gravity()
        command.control(real_time=False, dt=0)
    elif display == 'execute':
        command.refine(num_steps=10).execute(time_step=0.005)
    elif display == 'step':
        command.step()
    else:
        raise ValueError(display)

    print('Quit?')
    wait_if_gui()
    disconnect()
Ejemplo n.º 9
0
def main():
    # TODO: move to pybullet-planning for now
    parser = argparse.ArgumentParser()
    parser.add_argument('-viewer',
                        action='store_true',
                        help='enable the viewer while planning')
    args = parser.parse_args()
    print(args)

    connect(use_gui=True)
    with LockRenderer():
        draw_pose(unit_pose(), length=1)
        floor = create_floor()
        with HideOutput():
            robot = load_pybullet(get_model_path(ROOMBA_URDF),
                                  fixed_base=True,
                                  scale=2.0)
            for link in get_all_links(robot):
                set_color(robot, link=link, color=ORANGE)
            robot_z = stable_z(robot, floor)
            set_point(robot, Point(z=robot_z))
        #set_base_conf(robot, rover_confs[i])

        data_path = add_data_path()
        shelf, = load_model(os.path.join(data_path, KIVA_SHELF_SDF),
                            fixed_base=True)  # TODO: returns a tuple
        dump_body(shelf)
        #draw_aabb(get_aabb(shelf))

    wait_for_user()
    disconnect()
Ejemplo n.º 10
0
def main():
    # The URDF loader seems robust to package:// and slightly wrong relative paths?
    connect(use_gui=True)
    add_data_path()
    plane = p.loadURDF("plane.urdf")
    with LockRenderer():
        with HideOutput():
            robot = load_model(MOVO_URDF, fixed_base=True)
        for link in get_links(robot):
            set_color(robot,
                      color=apply_alpha(0.25 * np.ones(3), 1),
                      link=link)
        base_joints = joints_from_names(robot, BASE_JOINTS)
        draw_base_limits((get_min_limits(
            robot, base_joints), get_max_limits(robot, base_joints)),
                         z=1e-2)
    dump_body(robot)
    wait_for_user('Start?')

    #for arm in ARMS:
    #    test_close_gripper(robot, arm)

    arm = 'right'
    tool_link = link_from_name(robot, TOOL_LINK.format(arm))
    #joint_names = HEAD_JOINTS
    #joints = joints_from_names(robot, joint_names)
    joints = base_joints + get_arm_joints(robot, arm)
    #joints = get_movable_joints(robot)
    print('Joints:', get_joint_names(robot, joints))

    ik_joints = get_ik_joints(robot, MOVO_INFOS[arm], tool_link)
    #fixed_joints = []
    fixed_joints = ik_joints[:1]
    #fixed_joints = ik_joints

    sample_fn = get_sample_fn(robot, joints)
    handles = []
    for i in range(10):
        print('Iteration:', i)
        conf = sample_fn()
        print(conf)
        set_joint_positions(robot, joints, conf)
        tool_pose = get_link_pose(robot, tool_link)
        remove_handles(handles)
        handles = draw_pose(tool_pose)
        wait_for_user()

        #conf = next(ikfast_inverse_kinematics(robot, MOVO_INFOS[arm], tool_link, tool_pose,
        #                                      fixed_joints=fixed_joints, max_time=0.1), None)
        #if conf is not None:
        #    set_joint_positions(robot, ik_joints, conf)
        #wait_for_user()
        test_retraction(robot,
                        MOVO_INFOS[arm],
                        tool_link,
                        fixed_joints=fixed_joints,
                        max_time=0.1)
    disconnect()
Ejemplo n.º 11
0
def main(group=SE3):
    connect(use_gui=True)
    set_camera_pose(camera_point=SIZE*np.array([1., -1., 1.]))
    # TODO: can also create all links and fix some joints
    # TODO: SE(3) motion planner (like my SE(3) one) where some dimensions are fixed

    obstacle = create_box(w=SIZE, l=SIZE, h=SIZE, color=RED)
    #robot = create_cylinder(radius=0.025, height=0.1, color=BLUE)
    obstacles = [obstacle]

    collision_id, visual_id = create_shape(get_cylinder_geometry(radius=0.025, height=0.1), color=BLUE)
    robot = create_flying_body(group, collision_id, visual_id)

    body_link = get_links(robot)[-1]
    joints = get_movable_joints(robot)
    joint_from_group = dict(zip(group, joints))
    print(joint_from_group)
    #print(get_aabb(robot, body_link))
    dump_body(robot, fixed=False)
    custom_limits = {joint_from_group[j]: l for j, l in CUSTOM_LIMITS.items()}

    # sample_fn = get_sample_fn(robot, joints, custom_limits=custom_limits)
    # for i in range(10):
    #     conf = sample_fn()
    #     set_joint_positions(robot, joints, conf)
    #     wait_for_user('Iteration: {}'.format(i))
    # return

    initial_point = SIZE*np.array([-1., -1., 0])
    #initial_point = -1.*np.ones(3)
    final_point = -initial_point
    initial_euler = np.zeros(3)
    add_line(initial_point, final_point, color=GREEN)

    initial_conf = np.concatenate([initial_point, initial_euler])
    final_conf = np.concatenate([final_point, initial_euler])

    set_joint_positions(robot, joints, initial_conf)
    #print(initial_point, get_link_pose(robot, body_link))
    #set_pose(robot, Pose(point=-1.*np.ones(3)))

    path = plan_joint_motion(robot, joints, final_conf, obstacles=obstacles,
                             self_collisions=False, custom_limits=custom_limits)
    if path is None:
        disconnect()
        return

    for i, conf in enumerate(path):
        set_joint_positions(robot, joints, conf)
        point, quat = get_link_pose(robot, body_link)
        #euler = euler_from_quat(quat)
        euler = intrinsic_euler_from_quat(quat)
        print(conf)
        print(point, euler)
        wait_for_user('Step: {}/{}'.format(i, len(path)))

    wait_for_user('Finish?')
    disconnect()
Ejemplo n.º 12
0
def main():
    parser = argparse.ArgumentParser()  # Automatically includes help
    parser.add_argument('-viewer', action='store_true', help='enable viewer.')
    args = parser.parse_args()

    connect(use_gui=True)

    with LockRenderer():
        draw_pose(unit_pose(), length=1, width=1)
        floor = create_floor()
        set_point(floor, Point(z=-EPSILON))

        table1 = create_table(width=TABLE_WIDTH, length=TABLE_WIDTH/2, height=TABLE_WIDTH/2,
                              top_color=TAN, cylinder=False)
        set_point(table1, Point(y=+0.5))

        table2 = create_table(width=TABLE_WIDTH, length=TABLE_WIDTH/2, height=TABLE_WIDTH/2,
                              top_color=TAN, cylinder=False)
        set_point(table2, Point(y=-0.5))

        tables = [table1, table2]

        #set_euler(table1, Euler(yaw=np.pi/2))
        with HideOutput():
            # data_path = add_data_path()
            # robot_path = os.path.join(data_path, WSG_GRIPPER)
            robot_path = get_model_path(WSG_50_URDF)  # WSG_50_URDF | PANDA_HAND_URDF
            robot = load_pybullet(robot_path, fixed_base=True)
            #dump_body(robot)

        block1 = create_box(w=BLOCK_SIDE, l=BLOCK_SIDE, h=BLOCK_SIDE, color=RED)
        block_z = stable_z(block1, table1)
        set_point(block1, Point(y=-0.5, z=block_z))

        block2 = create_box(w=BLOCK_SIDE, l=BLOCK_SIDE, h=BLOCK_SIDE, color=GREEN)
        set_point(block2, Point(x=-0.25, y=-0.5, z=block_z))

        block3 = create_box(w=BLOCK_SIDE, l=BLOCK_SIDE, h=BLOCK_SIDE, color=BLUE)
        set_point(block3, Point(x=-0.15, y=+0.5, z=block_z))

        blocks = [block1, block2, block3]

        set_camera_pose(camera_point=Point(x=-1, z=block_z+1), target_point=Point(z=block_z))

    block_pose = get_pose(block1)
    open_gripper(robot)
    tool_link = link_from_name(robot, 'tool_link')
    base_from_tool = get_relative_pose(robot, tool_link)
    #draw_pose(unit_pose(), parent=robot, parent_link=tool_link)
    grasps = get_side_grasps(block1, tool_pose=Pose(euler=Euler(yaw=np.pi/2)),
                             top_offset=0.02, grasp_length=0.03, under=False)[1:2]
    for grasp in grasps:
        gripper_pose = multiply(block_pose, invert(grasp))
        set_pose(robot, multiply(gripper_pose, invert(base_from_tool)))
        wait_for_user()

    wait_for_user('Finish?')
    disconnect()
def main():
    connect(use_gui=True)
    with HideOutput():
        pr2 = load_model(
            "models/drake/pr2_description/urdf/pr2_simplified.urdf")
    set_joint_positions(pr2, joints_from_names(pr2, PR2_GROUPS['left_arm']),
                        REST_LEFT_ARM)
    set_joint_positions(pr2, joints_from_names(pr2, PR2_GROUPS['right_arm']),
                        rightarm_from_leftarm(REST_LEFT_ARM))
    set_joint_positions(pr2, joints_from_names(pr2, PR2_GROUPS['torso']),
                        [0.2])
    dump_body(pr2)

    block = load_model(BLOCK_URDF, fixed_base=False)
    set_point(block, [2, 0.5, 1])
    target_point = point_from_pose(get_pose(block))

    # head_link = link_from_name(pr2, HEAD_LINK)
    head_joints = joints_from_names(pr2, PR2_GROUPS['head'])
    head_link = head_joints[-1]

    #max_detect_distance = 2.5
    max_register_distance = 1.0
    distance_range = (max_register_distance / 2, max_register_distance)
    base_generator = visible_base_generator(pr2, target_point, distance_range)

    base_joints = joints_from_names(pr2, PR2_GROUPS['base'])
    for i in range(5):
        base_conf = next(base_generator)
        set_joint_positions(pr2, base_joints, base_conf)

        p.addUserDebugLine(point_from_pose(get_link_pose(pr2, head_link)),
                           target_point,
                           lineColorRGB=(1, 0, 0))  # addUserDebugText
        p.addUserDebugLine(point_from_pose(
            get_link_pose(pr2, link_from_name(pr2, HEAD_LINK_NAME))),
                           target_point,
                           lineColorRGB=(0, 0, 1))  # addUserDebugText

        # head_conf = sub_inverse_kinematics(pr2, head_joints[0], HEAD_LINK, )
        head_conf = inverse_visibility(pr2, target_point)
        set_joint_positions(pr2, head_joints, head_conf)
        print(get_detections(pr2))
        # TODO: does this detect the robot sometimes?

        detect_mesh, z = get_detection_cone(pr2, block)
        detect_cone = create_mesh(detect_mesh, color=(0, 1, 0, 0.5))
        set_pose(detect_cone,
                 get_link_pose(pr2, link_from_name(pr2, HEAD_LINK_NAME)))
        view_cone = get_viewcone(depth=2.5, color=(1, 0, 0, 0.25))
        set_pose(view_cone,
                 get_link_pose(pr2, link_from_name(pr2, HEAD_LINK_NAME)))
        wait_for_user()
        remove_body(detect_cone)
        remove_body(view_cone)

    disconnect()
Ejemplo n.º 14
0
def main(execute='apply'):
    #parser = argparse.ArgumentParser()  # Automatically includes help
    #parser.add_argument('-display', action='store_true', help='enable viewer.')
    #args = parser.parse_args()
    #display = args.display
    display = True
    #display = False

    #filename = 'transporter.json' # simple | simple2 | cook | invert | kitchen | nonmonotonic_4_1
    #problem_fn = lambda: load_json_problem(filename)
    problem_fn = cooking_problem
    # holding_problem | stacking_problem | cleaning_problem | cooking_problem
    # cleaning_button_problem | cooking_button_problem

    with HideOutput():
        sim_world = connect(use_gui=False)
    set_client(sim_world)
    add_data_path()
    problem = problem_fn()
    print(problem)
    #state_id = save_state()

    if display:
        with HideOutput():
            real_world = connect(use_gui=True)
        add_data_path()
        with ClientSaver(real_world):
            problem_fn()  # TODO: way of doing this without reloading?
            update_state()
            wait_for_duration(0.1)

    #wait_for_interrupt()
    commands = plan_commands(problem)
    if (commands is None) or not display:
        with HideOutput():
            disconnect()
        return

    time_step = 0.01
    set_client(real_world)
    if execute == 'control':
        enable_gravity()
        control_commands(commands)
    elif execute == 'execute':
        step_commands(commands, time_step=time_step)
    elif execute == 'step':
        step_commands(commands)
    elif execute == 'apply':
        state = State()
        apply_commands(state, commands, time_step=time_step)
    else:
        raise ValueError(execute)

    wait_for_interrupt()
    with HideOutput():
        disconnect()
Ejemplo n.º 15
0
def main():
    connect(use_gui=True)

    with HideOutput():
        pr2 = load_model("models/pr2_description/pr2.urdf")
    test_clone_robot(pr2)
    test_clone_arm(pr2)

    user_input('Finish?')
    disconnect()
Ejemplo n.º 16
0
def main(use_pr2_drake=True):
    connect(use_gui=True)
    add_data_path()

    plane = p.loadURDF("plane.urdf")
    table_path = "models/table_collision/table.urdf"
    table = load_pybullet(table_path, fixed_base=True)
    set_quat(table, quat_from_euler(Euler(yaw=PI / 2)))
    # table/table.urdf, table_square/table_square.urdf, cube.urdf, block.urdf, door.urdf
    obstacles = [plane, table]

    pr2_urdf = DRAKE_PR2_URDF if use_pr2_drake else PR2_URDF
    with HideOutput():
        pr2 = load_model(pr2_urdf, fixed_base=True)  # TODO: suppress warnings?
    dump_body(pr2)

    z = base_aligned_z(pr2)
    print(z)
    #z = stable_z_on_aabb(pr2, AABB(np.zeros(3), np.zeros(3)))
    print(z)

    set_point(pr2, Point(z=z))
    print(get_aabb(pr2))
    wait_if_gui()

    base_start = (-2, -2, 0)
    base_goal = (2, 2, 0)
    arm_start = SIDE_HOLDING_LEFT_ARM
    #arm_start = TOP_HOLDING_LEFT_ARM
    #arm_start = REST_LEFT_ARM
    arm_goal = TOP_HOLDING_LEFT_ARM
    #arm_goal = SIDE_HOLDING_LEFT_ARM

    left_joints = joints_from_names(pr2, PR2_GROUPS['left_arm'])
    right_joints = joints_from_names(pr2, PR2_GROUPS['right_arm'])
    torso_joints = joints_from_names(pr2, PR2_GROUPS['torso'])
    set_joint_positions(pr2, left_joints, arm_start)
    set_joint_positions(pr2, right_joints,
                        rightarm_from_leftarm(REST_LEFT_ARM))
    set_joint_positions(pr2, torso_joints, [0.2])
    open_arm(pr2, 'left')
    # test_ikfast(pr2)

    add_line(base_start, base_goal, color=RED)
    print(base_start, base_goal)
    if use_pr2_drake:
        test_drake_base_motion(pr2, base_start, base_goal, obstacles=obstacles)
    else:
        test_base_motion(pr2, base_start, base_goal, obstacles=obstacles)

    test_arm_motion(pr2, left_joints, arm_goal)
    # test_arm_control(pr2, left_joints, arm_start)

    wait_if_gui('Finish?')
    disconnect()
Ejemplo n.º 17
0
def display_failure(node_points, extruded_elements, element):
    client = connect(use_gui=True)
    with ClientSaver(client):
        obstacles, robot = load_world()
        handles = []
        for e in extruded_elements:
            handles.append(draw_element(node_points, e, color=(0, 1, 0)))
        handles.append(draw_element(node_points, element, color=(1, 0, 0)))
        print('Failure!')
        wait_for_user()
        reset_simulation()
        disconnect()
Ejemplo n.º 18
0
def main(display='execute'): # control | execute | step
    # One of the arm's gantry carriage is fixed when the other is moving.
    connect(use_gui=True)
    set_camera(yaw=-90, pitch=-40, distance=10, target_position=(0, 7.5, 0))
    draw_pose(unit_pose(), length=1.0)
    disable_real_time()

    with HideOutput():
        root_directory = os.path.dirname(os.path.abspath(__file__))
        robot = load_pybullet(os.path.join(root_directory, ETH_RFL_URDF), fixed_base=True)
    # floor = load_model('models/short_floor.urdf')
    block = load_model(BLOCK_URDF, fixed_base=False)
    #link = link_from_name(robot, 'gantry_base_link')
    #print(get_aabb(robot, link))

    block_x = -0.2
    #block_y = 1 if ARM == 'right' else 13.5
    #block_x = 10
    block_y = 5.

    # set_pose(floor, Pose(Point(x=floor_x, y=1, z=1.3)))
    # set_pose(block, Pose(Point(x=floor_x, y=0.6, z=stable_z(block, floor))))
    set_pose(block, Pose(Point(x=block_x, y=block_y, z=3.5)))
    # set_default_camera()
    dump_world()

    #print(get_camera())
    saved_world = WorldSaver()
    with LockRenderer():
        command = plan(robot, block, fixed=[], teleport=False) # fixed=[floor],
    if (command is None) or (display is None):
        print('Unable to find a plan! Quit?')
        wait_for_interrupt()
        disconnect()
        return

    saved_world.restore()
    update_state()
    print('{}?'.format(display))
    wait_for_interrupt()
    if display == 'control':
        enable_gravity()
        command.control(real_time=False, dt=0)
    elif display == 'execute':
        command.refine(num_steps=10).execute(time_step=0.002)
    elif display == 'step':
        command.step()
    else:
        raise ValueError(display)

    print('Quit?')
    wait_for_interrupt()
    disconnect()
Ejemplo n.º 19
0
def main(use_pr2_drake=False):
    connect(use_gui=True)
    add_data_path()

    plane = p.loadURDF("plane.urdf")
    #table_path = "table/table.urdf"
    # table_path = "models/table_collision/table.urdf"
    # table = p.loadURDF(table_path, 0, 0, 0, 0, 0, 0.707107, 0.707107)
    # table_square/table_square.urdf, cube.urdf, block.urdf, door.urdf

    pr2_urdf = DRAKE_PR2_URDF if use_pr2_drake else PR2_URDF
    with HideOutput():
        pr2 = load_model(pr2_urdf, fixed_base=True)  # TODO: suppress warnings?
    dump_body(pr2)

    base_start = (-2, -2, 0)
    base_goal = (2, 2, 0)
    arm_start = SIDE_HOLDING_LEFT_ARM
    #arm_start = TOP_HOLDING_LEFT_ARM
    #arm_start = REST_LEFT_ARM
    arm_goal = TOP_HOLDING_LEFT_ARM
    #arm_goal = SIDE_HOLDING_LEFT_ARM

    left_joints = joints_from_names(pr2, PR2_GROUPS['left_arm'])
    right_joints = joints_from_names(pr2, PR2_GROUPS['right_arm'])
    torso_joints = joints_from_names(pr2, PR2_GROUPS['torso'])
    set_joint_positions(pr2, left_joints, arm_start)
    set_joint_positions(pr2, right_joints,
                        rightarm_from_leftarm(REST_LEFT_ARM))
    set_joint_positions(pr2, torso_joints, [0.2])
    open_arm(pr2, 'left')
    # test_ikfast(pr2)

    p.addUserDebugLine(base_start, base_goal,
                       lineColorRGB=(1, 0, 0))  # addUserDebugText
    print(base_start, base_goal)
    if use_pr2_drake:
        test_drake_base_motion(pr2, base_start, base_goal)
    else:
        test_base_motion(pr2, base_start, base_goal)

    test_arm_motion(pr2, left_joints, arm_goal)
    # test_arm_control(pr2, left_joints, arm_start)

    user_input('Finish?')
    disconnect()
Ejemplo n.º 20
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-shape',
                        default='box',
                        choices=['box', 'sphere', 'cylinder', 'capsule'])
    parser.add_argument('-video', action='store_true')
    args = parser.parse_args()
    video = 'video.mp4' if args.video else None

    connect(use_gui=True, mp4=video)
    if video is not None:
        set_renderer(enable=False)

    draw_global_system()
    set_camera_pose(camera_point=Point(+1.5, -1.5, +1.5),
                    target_point=Point(-1.5, +1.5, 0))

    add_data_path()
    plane = load_pybullet('plane.urdf', fixed_base=True)
    #plane = load_model('plane.urdf')
    set_point(plane, Point(z=-1e-3))

    ramp = create_ramp()
    dump_body(ramp)

    obj = create_object(args.shape)
    set_euler(obj, np.random.uniform(-np.math.radians(1), np.math.radians(1),
                                     3))
    set_point(obj, np.random.uniform(-1e-3, +1e-3, 3))
    #set_velocity(obj, linear=Point(x=-1))
    set_position(obj, z=2.)
    #set_position(obj, z=base_aligned_z(obj))
    dump_body(obj)

    #add_pose_constraint(obj, pose=(target_point, target_quat), max_force=200)

    set_renderer(enable=True)
    if video is None:
        wait_if_gui('Begin?')
    simulate(controller=condition_controller(lambda step:
                                             (step != 0) and at_rest(obj)))
    if video is None:
        wait_if_gui('Finish?')
    disconnect()
Ejemplo n.º 21
0
def main(display='execute'):  # control | execute | step
    connect(use_gui=True)
    disable_real_time()

    with HideOutput():
        root_directory = os.path.dirname(os.path.abspath(__file__))
        robot = load_pybullet(os.path.join(root_directory, IRB6600_TRACK_URDF), fixed_base=True)
    floor = load_model('models/short_floor.urdf')
    block = load_model(BLOCK_URDF, fixed_base=False)
    floor_x = 2
    set_pose(floor, Pose(Point(x=floor_x, z=0.5)))
    set_pose(block, Pose(Point(x=floor_x, y=0, z=stable_z(block, floor))))
    # set_default_camera()
    dump_world()

    saved_world = WorldSaver()
    with LockRenderer():
        command = plan(robot, block, fixed=[floor], teleport=False)
    if (command is None) or (display is None):
        print('Unable to find a plan!')
        print('Quit?')
        wait_for_interrupt()
        disconnect()
        return

    saved_world.restore()
    update_state()
    user_input('{}?'.format(display))
    if display == 'control':
        enable_gravity()
        command.control(real_time=False, dt=0)
    elif display == 'execute':
        command.refine(num_steps=10).execute(time_step=0.002)
    elif display == 'step':
        command.step()
    else:
        raise ValueError(display)

    print('Quit?')
    wait_for_interrupt()
    disconnect()
Ejemplo n.º 22
0
def main():
    connect(use_gui=True)
    add_data_path()
    draw_pose(Pose(), length=1.)
    set_camera_pose(camera_point=[1, -1, 1])

    plane = p.loadURDF("plane.urdf")
    with LockRenderer():
        with HideOutput(True):
            robot = load_pybullet(FRANKA_URDF, fixed_base=True)
            assign_link_colors(robot, max_colors=3, s=0.5, v=1.)
            #set_all_color(robot, GREEN)
    obstacles = [plane]  # TODO: collisions with the ground

    dump_body(robot)
    print('Start?')
    wait_for_user()

    info = PANDA_INFO
    tool_link = link_from_name(robot, 'panda_hand')
    draw_pose(Pose(), parent=robot, parent_link=tool_link)
    joints = get_movable_joints(robot)
    print('Joints', [get_joint_name(robot, joint) for joint in joints])
    check_ik_solver(info)

    sample_fn = get_sample_fn(robot, joints)
    for i in range(10):
        print('Iteration:', i)
        conf = sample_fn()
        set_joint_positions(robot, joints, conf)
        wait_for_user()
        #test_ik(robot, info, tool_link, get_link_pose(robot, tool_link))
        test_retraction(robot,
                        info,
                        tool_link,
                        use_pybullet=False,
                        max_distance=0.1,
                        max_time=0.05,
                        max_candidates=100)
    disconnect()
Ejemplo n.º 23
0
def main():
    # https://github.com/ros-teleop/teleop_twist_keyboard
    # http://openrave.org/docs/latest_stable/_modules/openravepy/misc/#SetViewerUserThread

    connect(use_gui=True)
    add_data_path()
    load_pybullet("plane.urdf")
    #load_pybullet("models/table_collision/table.urdf")
    with HideOutput():
        pr2 = load_model(DRAKE_PR2_URDF, fixed_base=True)
    enable_gravity()
    enable_real_time(
    )  # TODO: won't work as well on OS X due to simulation thread

    #run_simulate(pr2)
    run_thread(pr2)
    # TODO: keep working on this
    #userthread = threading.Thread(target=run_thread, args=[pr2])
    #userthread.start()
    #userthread.join()

    disconnect()
Ejemplo n.º 24
0
def main():
    benchmark = 'tmp-benchmark-data'
    problem = 'problem1'  # Hanoi
    #problem = 'problem2' # Blocksworld
    #problem = 'problem3' # Clutter
    #problem = 'problem4' # Nonmono

    root_directory = os.path.dirname(os.path.abspath(__file__))
    directory = os.path.join(root_directory, '..', 'problems', benchmark,
                             problem)
    [mesh_directory] = list(
        filter(os.path.isdir,
               (os.path.join(directory, o)
                for o in os.listdir(directory) if o.endswith('meshes'))))
    [xml_path] = [
        os.path.join(directory, o) for o in os.listdir(directory)
        if o.endswith('xml')
    ]
    if os.path.isdir(xml_path):
        xml_path = glob.glob(os.path.join(xml_path, '*.xml'))[0]

    print(mesh_directory)
    print(xml_path)
    xml_data = etree.parse(xml_path)

    connect(use_gui=True)
    #add_data_path()
    #load_pybullet("plane.urdf")
    draw_global_system()
    set_camera_pose(camera_point=[+1, -1, 1])

    #root = xml_data.getroot()
    #print(root.items())
    for obj in xml_data.findall('/objects/obj'):
        parse_object(obj, mesh_directory)
    for robot in xml_data.findall('/robots/robot'):
        parse_robot(robot)
    wait_if_gui()
    disconnect()
Ejemplo n.º 25
0
def main():
    parser = argparse.ArgumentParser()  # Automatically includes help
    parser.add_argument('-arm', required=True)
    parser.add_argument('-grasp', required=True)
    parser.add_argument('-viewer', action='store_true', help='enable viewer.')
    args = parser.parse_args()

    arm = args.arm
    other_arm = get_other_arm(arm)
    grasp_type = args.grasp

    connect(use_gui=args.viewer)
    add_data_path()

    robot = p.loadURDF("models/pr2_description/pr2_fixed_torso.urdf")
    set_arm_conf(robot, arm, get_carry_conf(arm, grasp_type))
    set_arm_conf(robot, other_arm, arm_conf(other_arm, REST_LEFT_ARM))

    #plane = p.loadURDF("plane.urdf")
    table = p.loadURDF("table/table.urdf", 0, 0, 0, 0, 0, 0.707107, 0.707107)
    box = create_box(.07, .05, .15)

    create_inverse_reachability(robot, box, table, arm=arm, grasp_type=grasp_type)
    disconnect()
Ejemplo n.º 26
0
def main(use_turtlebot=True):
    parser = argparse.ArgumentParser()
    parser.add_argument('-sim', action='store_true')
    parser.add_argument('-video', action='store_true')
    args = parser.parse_args()
    video = 'video.mp4' if args.video else None

    connect(use_gui=True, mp4=video)
    #set_renderer(enable=False)
    # print(list_pybullet_data())
    # print(list_pybullet_robots())

    draw_global_system()
    set_camera_pose(camera_point=Point(+1.5, -1.5, +1.5),
                    target_point=Point(-1.5, +1.5, 0))

    plane = load_plane()
    #door = load_pybullet('models/door.urdf', fixed_base=True) # From drake
    #set_point(door, Point(z=-.1))
    door = create_door()
    #set_position(door, z=base_aligned_z(door))
    set_point(door, base_aligned(door))
    #set_collision_margin(door, link=0, margin=0.)
    set_configuration(door, [math.radians(-5)])
    dump_body(door)

    door_joint = get_movable_joints(door)[0]
    door_link = child_link_from_joint(door_joint)
    #draw_pose(get_com_pose(door, door_link), parent=door, parent_link=door_link)
    draw_pose(Pose(), parent=door, parent_link=door_link)
    wait_if_gui()

    ##########

    start_x = +2
    target_x = -start_x
    if not use_turtlebot:
        side = 0.25
        robot = create_box(w=side, l=side, h=side, mass=5., color=BLUE)
        set_position(robot, x=start_x)
        #set_velocity(robot, linear=Point(x=-1))
    else:
        turtlebot_urdf = os.path.abspath(TURTLEBOT_URDF)
        print(turtlebot_urdf)
        #print(read(turtlebot_urdf))
        robot = load_pybullet(turtlebot_urdf, merge=True, fixed_base=True)
        robot_joints = get_movable_joints(robot)[:3]
        set_joint_positions(robot, robot_joints, [start_x, 0, PI])
    set_all_color(robot, BLUE)
    set_position(robot, z=base_aligned_z(robot))
    dump_body(robot)

    ##########

    set_renderer(enable=True)
    #test_door(door)
    if args.sim:
        test_simulation(robot, target_x, video)
    else:
        assert use_turtlebot  # TODO: extend to the block
        test_kinematic(robot, door, target_x)
    disconnect()
Ejemplo n.º 27
0
 def destroy(self):
     reset_simulation()
     disconnect()
Ejemplo n.º 28
0
def main(num_iterations=10):
    # The URDF loader seems robust to package:// and slightly wrong relative paths?
    connect(use_gui=True)
    add_data_path()
    plane = p.loadURDF("plane.urdf")
    side = 0.05
    block = create_box(w=side, l=side, h=side, color=RED)

    start_time = time.time()
    with LockRenderer():
        with HideOutput():
            # TODO: MOVO must be loaded last
            robot = load_model(MOVO_URDF, fixed_base=True)
        #set_all_color(robot, color=MOVO_COLOR)
        assign_link_colors(robot)
        base_joints = joints_from_names(robot, BASE_JOINTS)
        draw_base_limits((get_min_limits(
            robot, base_joints), get_max_limits(robot, base_joints)),
                         z=1e-2)
    print('Load time: {:.3f}'.format(elapsed_time(start_time)))

    dump_body(robot)
    #print(get_colliding(robot))
    #for arm in ARMS:
    #    test_close_gripper(robot, arm)
    #test_grasps(robot, block)

    arm = RIGHT
    tool_link = link_from_name(robot, TOOL_LINK.format(arm))

    #joint_names = HEAD_JOINTS
    #joints = joints_from_names(robot, joint_names)
    joints = base_joints + get_arm_joints(robot, arm)
    #joints = get_movable_joints(robot)
    print('Joints:', get_joint_names(robot, joints))

    ik_info = MOVO_INFOS[arm]
    print_ik_warning(ik_info)

    ik_joints = get_ik_joints(robot, ik_info, tool_link)
    #fixed_joints = []
    fixed_joints = ik_joints[:1]
    #fixed_joints = ik_joints

    wait_if_gui('Start?')
    sample_fn = get_sample_fn(robot, joints)
    handles = []
    for i in range(num_iterations):
        conf = sample_fn()
        print('Iteration: {}/{} | Conf: {}'.format(i + 1, num_iterations,
                                                   np.array(conf)))
        set_joint_positions(robot, joints, conf)
        tool_pose = get_link_pose(robot, tool_link)
        remove_handles(handles)
        handles = draw_pose(tool_pose)
        wait_if_gui()

        #conf = next(ikfast_inverse_kinematics(robot, MOVO_INFOS[arm], tool_link, tool_pose,
        #                                      fixed_joints=fixed_joints, max_time=0.1), None)
        #if conf is not None:
        #    set_joint_positions(robot, ik_joints, conf)
        #wait_if_gui()
        test_retraction(robot,
                        ik_info,
                        tool_link,
                        fixed_joints=fixed_joints,
                        max_time=0.05,
                        max_candidates=100)
    disconnect()
def main(floor_width=2.0):
    # Creates a pybullet world and a visualizer for it
    connect(use_gui=True)
    identity_pose = (unit_point(), unit_quat())
    origin_handles = draw_pose(
        identity_pose, length=1.0
    )  # Draws the origin coordinate system (x:RED, y:GREEN, z:BLUE)

    # Bodies are described by an integer index
    floor = create_box(w=floor_width, l=floor_width, h=0.001,
                       color=TAN)  # Creates a tan box object for the floor
    set_point(floor,
              [0, 0, -0.001 / 2.])  # Sets the [x,y,z] translation of the floor

    obstacle = create_box(w=0.5, l=0.5, h=0.1,
                          color=RED)  # Creates a red box obstacle
    set_point(
        obstacle,
        [0.5, 0.5, 0.1 / 2.])  # Sets the [x,y,z] position of the obstacle
    print('Position:', get_point(obstacle))
    set_euler(obstacle,
              [0, 0, np.pi / 4
               ])  #  Sets the [roll,pitch,yaw] orientation of the obstacle
    print('Orientation:', get_euler(obstacle))

    with LockRenderer(
    ):  # Temporarily prevents the renderer from updating for improved loading efficiency
        with HideOutput():  # Temporarily suppresses pybullet output
            robot = load_model(ROOMBA_URDF)  # Loads a robot from a *.urdf file
            robot_z = stable_z(
                robot, floor
            )  # Returns the z offset required for robot to be placed on floor
            set_point(robot,
                      [0, 0, robot_z])  # Sets the z position of the robot
    dump_body(robot)  # Prints joint and link information about robot
    set_all_static()

    # Joints are also described by an integer index
    # The turtlebot has explicit joints representing x, y, theta
    x_joint = joint_from_name(robot, 'x')  # Looks up the robot joint named 'x'
    y_joint = joint_from_name(robot, 'y')  # Looks up the robot joint named 'y'
    theta_joint = joint_from_name(
        robot, 'theta')  # Looks up the robot joint named 'theta'
    joints = [x_joint, y_joint, theta_joint]

    base_link = link_from_name(
        robot, 'base_link')  # Looks up the robot link named 'base_link'
    world_from_obstacle = get_pose(
        obstacle
    )  # Returns the pose of the origin of obstacle wrt the world frame
    obstacle_aabb = get_subtree_aabb(obstacle)
    draw_aabb(obstacle_aabb)

    random.seed(0)  # Sets the random number generator state
    handles = []
    for i in range(10):
        for handle in handles:
            remove_debug(handle)
        print('\nIteration: {}'.format(i))
        x = random.uniform(-floor_width / 2., floor_width / 2.)
        set_joint_position(robot, x_joint,
                           x)  # Sets the current value of the x joint
        y = random.uniform(-floor_width / 2., floor_width / 2.)
        set_joint_position(robot, y_joint,
                           y)  # Sets the current value of the y joint
        yaw = random.uniform(-np.pi, np.pi)
        set_joint_position(robot, theta_joint,
                           yaw)  # Sets the current value of the theta joint
        values = get_joint_positions(
            robot,
            joints)  # Obtains the current values for the specified joints
        print('Joint values: [x={:.3f}, y={:.3f}, yaw={:.3f}]'.format(*values))

        world_from_robot = get_link_pose(
            robot,
            base_link)  # Returns the pose of base_link wrt the world frame
        position, quaternion = world_from_robot  # Decomposing pose into position and orientation (quaternion)
        x, y, z = position  # Decomposing position into x, y, z
        print('Base link position: [x={:.3f}, y={:.3f}, z={:.3f}]'.format(
            x, y, z))
        euler = euler_from_quat(
            quaternion)  # Converting from quaternion to euler angles
        roll, pitch, yaw = euler  # Decomposing orientation into roll, pitch, yaw
        print('Base link orientation: [roll={:.3f}, pitch={:.3f}, yaw={:.3f}]'.
              format(roll, pitch, yaw))
        handles.extend(
            draw_pose(world_from_robot, length=0.5)
        )  # # Draws the base coordinate system (x:RED, y:GREEN, z:BLUE)
        obstacle_from_robot = multiply(
            invert(world_from_obstacle),
            world_from_robot)  # Relative transformation from robot to obstacle

        robot_aabb = get_subtree_aabb(
            robot,
            base_link)  # Computes the robot's axis-aligned bounding box (AABB)
        lower, upper = robot_aabb  # Decomposing the AABB into the lower and upper extrema
        center = (lower + upper) / 2.  # Computing the center of the AABB
        extent = upper - lower  # Computing the dimensions of the AABB
        handles.extend(draw_aabb(robot_aabb))

        collision = pairwise_collision(
            robot, obstacle
        )  # Checks whether robot is currently colliding with obstacle
        print('Collision: {}'.format(collision))
        wait_for_duration(1.0)  # Like sleep() but also updates the viewer
    wait_for_user()  # Like raw_input() but also updates the viewer

    # Destroys the pybullet world
    disconnect()
Ejemplo n.º 30
0
def main():
    connect(use_gui=True)
    add_data_path()

    set_camera(0, -30, 1)
    plane = load_pybullet('plane.urdf', fixed_base=True)
    #plane = load_model('plane.urdf')
    cup = load_model('models/cup.urdf', fixed_base=True)
    #set_point(cup, Point(z=stable_z(cup, plane)))
    set_point(cup, Point(z=.2))
    set_color(cup, (1, 0, 0, .4))

    num_droplets = 100
    #radius = 0.025
    #radius = 0.005
    radius = 0.0025
    # TODO: more efficient ways to make all of these
    droplets = [create_sphere(radius, mass=0.01)
                for _ in range(num_droplets)]  # kg
    cup_thickness = 0.001

    lower, upper = get_lower_upper(cup)
    print(lower, upper)
    buffer = cup_thickness + radius
    lower = np.array(lower) + buffer * np.ones(len(lower))
    upper = np.array(upper) - buffer * np.ones(len(upper))

    limits = zip(lower, upper)
    x_range, y_range = limits[:2]
    z = upper[2] + 0.1
    #x_range = [-1, 1]
    #y_range = [-1, 1]
    #z = 1
    for droplet in droplets:
        x = np.random.uniform(*x_range)
        y = np.random.uniform(*y_range)
        set_point(droplet, Point(x, y, z))

    for i, droplet in enumerate(droplets):
        x, y = np.random.normal(0, 1e-3, 2)
        set_point(droplet, Point(x, y, z + i * (2 * radius + 1e-3)))

    #dump_world()
    wait_for_user()

    #user_input('Start?')
    enable_gravity()
    simulate_for_duration(5.0)

    # enable_real_time()
    # try:
    #     while True:
    #         enable_gravity() # enable_real_time requires a command
    #         #time.sleep(dt)
    # except KeyboardInterrupt:
    #     pass
    # print()

    #time.sleep(1.0)
    wait_for_user('Finish?')
    disconnect()