Beispiel #1
0
def build_user_input(points=None, rectangulars=None, balls=None):
    points, rectangulars, balls = _prepare_user_input(points, rectangulars,
                                                      balls)
    user_input = scene_if.UserInput(
        flattened_point_list=points.flatten().tolist(), balls=[], polygons=[])
    for start in range(0, len(rectangulars), 8):
        rect = rectangulars[start:start + 8]
        vertices = []
        for i in range(4):
            vertices.append(
                scene_if.Vector(rect[2 * i] - rect[0],
                                rect[2 * i + 1] - rect[1]))
        user_input.polygons.append(
            scene_if.PolygonWithPosition(
                vertices=vertices,
                position=scene_if.Vector(rect[0], rect[1]),
                angle=0,
            ))
    for start in range(0, len(balls), 3):
        ball = balls[start:start + 3]
        user_input.balls.append(
            scene_if.CircleWithPosition(position=scene_if.Vector(
                ball[0], ball[1]),
                                        radius=ball[2]))
    return user_input
Beispiel #2
0
 def get_last_input(self):
     assert self._config['mode'] == DEV_MODE
     if os.path.exists(LAST_INPUT_PATH):
         user_input = util.load_user_input(LAST_INPUT_PATH)
     else:
         user_input = scene_if.UserInput()
         logging.warning('No last user input found')
     return user_input
Beispiel #3
0
 def action_to_user_input(self, action):
     if not all(0 <= x <= 1 for x in action):
         return EMPTY_USER_INPUT, False
     user_input = scene_if.UserInput(flattened_point_list=[],
                                     balls=[],
                                     polygons=[])
     BallScaler.add_to_user_input(action, user_input)
     if not _is_inside_scene(user_input):
         return EMPTY_USER_INPUT, False
     _quantize_user_input_in_place(user_input)
     return user_input, True
Beispiel #4
0
def load_user_input(fpath):
    # Try to read in text format first.
    points = _maybe_read_text_solution(fpath)
    user_input = scene_if.UserInput(flattened_point_list=[],
                                    polygons=[],
                                    balls=[])
    if points is not None:
        user_input.flattened_point_list = np.array(points).flatten().tolist()
    else:
        with open(fpath, 'rb') as stream:
            simulator.deserialize(user_input, stream.read())
    return user_input
def featurized_objects_vector_to_scene(featurized_objects: np.ndarray
                                      ) -> scene_if.Scene:
    """Convert an array of featurized objects into a Scene.

        Args:
            featurized_objects: np.ndarray of size (num_objects, OBJECT_FEATURE_SIZE)
        
        Returns:
            A scene_if.Scene contianing each of the featurized objects.
    """
    task = creator.creator.TaskCreator()
    user_input = scene_if.UserInput(flattened_point_list=[],
                                    balls=[],
                                    polygons=[])
    for features in featurized_objects:
        object_properties = _object_features_to_values(features)
        if object_properties['user_input']:
            assert object_properties['shape_type'] == 'ball', (
                'User input objects must be balls')
            user_input.balls.append(
                scene_if.CircleWithPosition(
                    position=scene_if.Vector(x=object_properties['x'],
                                             y=object_properties['y']),
                    radius=object_properties['diameter'] / 2.0))
        else:
            builder = shapes_lib.get_builders()[object_properties['shape_type']]
            shapes, phantom_vertices = builder.build(
                diameter=object_properties['diameter'])

            body = Body(shapes, object_properties['dynamic'],
                        object_properties['shape_type'],
                        object_properties['diameter'], phantom_vertices)
            body.push(object_properties['x'], object_properties['y'])
            body.set_angle(object_properties['angle'])
            body.set_color(object_properties['color'])

            task.scene.bodies.append(body._thrift_body)
            task.body_list.append(body)
    scene = phyre.simulator.add_user_input_to_scene(task.scene,
                                                    user_input,
                                                    allow_occlusions=True)
    return scene
Beispiel #6
0
    def action_to_user_input(
            self,
            action: GeneralizedAction) -> Tuple[scene_if.UserInput, bool]:
        if not all(0 <= x <= 1 for x in action):
            return EMPTY_USER_INPUT, False

        user_input = scene_if.UserInput(flattened_point_list=[],
                                        balls=[],
                                        polygons=[])
        BallScaler.add_to_user_input(action[:3], user_input)
        BallScaler.add_to_user_input(action[3:], user_input)
        if not _is_inside_scene(user_input):
            return EMPTY_USER_INPUT, False
        ball1, ball2 = user_input.balls
        x1, x2 = ball1.position.x, ball2.position.x
        y1, y2 = ball1.position.y, ball2.position.y
        dist = ((x1 - x2)**2 + (y1 - y2)**2)**0.5
        if dist < ball1.radius + ball2.radius + 1:
            return EMPTY_USER_INPUT, False
        if not _is_inside_scene(user_input):
            return EMPTY_USER_INPUT, False
        _quantize_user_input_in_place(user_input)
        return user_input, True
Beispiel #7
0
 def test_simulate_task(self):
     sim = self._handler.simulate_task_by_id(
         self._first_task_id, user_input=scene_if.UserInput(),
         dilate=False).simulation
     self.assertEqual(len(sim.sceneList),
                      1 + (simulator.DEFAULT_MAX_STEPS - 1) // 3)
Beispiel #8
0
from typing import ClassVar, Dict, FrozenSet, Optional, Sequence, Tuple, Union
import abc
import enum

import numpy as np

import phyre.creator
import phyre.interface.scene.ttypes as scene_if

GeneralizedAction = Union[np.ndarray, Sequence[float]]

SCENE_HEIGHT = phyre.creator.SCENE_HEIGHT
SCENE_WIDTH = phyre.creator.SCENE_WIDTH
EMPTY_USER_INPUT = scene_if.UserInput(flattened_point_list=[],
                                      balls=[],
                                      polygons=[])


def get_action_mapper(name: str) -> 'ActionMapper':
    """Get action mapper instance by name."""
    return ACTION_MAPPERS[name]()


class DimensionType(enum.IntEnum):
    """Type of values in a component of an action."""
    POSITION = 0
    SIZE = 1
    ANGLE = 2