Python gym.error.Error() Examples

The following are 30 code examples of gym.error.Error(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gym.error , or try the search function .
Example #1
Source File: registration.py    From gym-pull with MIT License 7 votes vote down vote up
def spec(self, id):
        # +-+--+-+-+-+ PATCHING --+-+-+-+-+-+
        _self = gym.envs.registry
        # +-+--+-+-+-+ /PATCHING --+-+-+-+-+-+
        match = env_id_re.search(id)
        if not match:
            raise error.Error('Attempted to look up malformed environment ID: {}. (Currently all IDs must be of the form {}.)'.format(id.encode('utf-8'), env_id_re.pattern))

        try:
            return _self.env_specs[id]
        except KeyError:
            # Parse the env name and check to see if it matches the non-version
            # part of a valid env (could also check the exact number here)
            env_name = match.group(1)
            matching_envs = [valid_env_name for valid_env_name, valid_env_spec in _self.env_specs.items()
                             if env_name == valid_env_spec._env_name]
            if matching_envs:
                raise error.DeprecatedEnv('Env {} not found (valid versions include {})'.format(id, matching_envs))
            else:
                raise error.UnregisteredEnv('No registered env with id: {}'.format(id)) 
Example #2
Source File: registration.py    From ia-course with MIT License 6 votes vote down vote up
def spec(self, id):
        match = env_id_re.search(id)
        if not match:
            raise error.Error('Attempted to look up malformed environment ID: {}. (Currently all IDs must be of the form {}.)'.format(id.encode('utf-8'), env_id_re.pattern))

        try:
            return self.env_specs[id]
        except KeyError:
            # Parse the env name and check to see if it matches the non-version
            # part of a valid env (could also check the exact number here)
            env_name = match.group(1)
            matching_envs = [valid_env_name for valid_env_name, valid_env_spec in self.env_specs.items()
                             if env_name == valid_env_spec._env_name]
            if matching_envs:
                raise error.DeprecatedEnv('Env {} not found (valid versions include {})'.format(id, matching_envs))
            else:
                raise error.UnregisteredEnv('No registered env with id: {}'.format(id)) 
Example #3
Source File: registration.py    From DQN-DDPG_Stock_Trading with MIT License 6 votes vote down vote up
def __init__(self, id, entry_point=None, reward_threshold=None, kwargs=None, nondeterministic=False, tags=None, max_episode_steps=None):
        self.id = id
        # Evaluation parameters
        self.reward_threshold = reward_threshold
        # Environment properties
        self.nondeterministic = nondeterministic
        self.entry_point = entry_point

        if tags is None:
            tags = {}
        self.tags = tags

        tags['wrapper_config.TimeLimit.max_episode_steps'] = max_episode_steps
        
        self.max_episode_steps = max_episode_steps

        # We may make some of these other parameters public if they're
        # useful.
        match = env_id_re.search(id)
        if not match:
            raise error.Error('Attempted to register malformed environment ID: {}. (Currently all IDs must be of the form {}.)'.format(id, env_id_re.pattern))
        self._env_name = match.group(1)
        self._kwargs = {} if kwargs is None else kwargs 
Example #4
Source File: seeding.py    From DRL_DeliveryDuel with MIT License 6 votes vote down vote up
def create_seed(a=None, max_bytes=8):
    """Create a strong random seed. Otherwise, Python 2 would seed using
    the system time, which might be non-robust especially in the
    presence of concurrency.

    Args:
        a (Optional[int, str]): None seeds from an operating system specific randomness source.
        max_bytes: Maximum number of bytes to use in the seed.
    """
    # Adapted from https://svn.python.org/projects/python/tags/r32/Lib/random.py
    if a is None:
        a = _bigint_from_bytes(os.urandom(max_bytes))
    elif isinstance(a, str):
        a = a.encode('utf8')
        a += hashlib.sha512(a).digest()
        a = _bigint_from_bytes(a[:max_bytes])
    elif isinstance(a, integer_types):
        a = a % 2**(8 * max_bytes)
    else:
        raise error.Error('Invalid type for seed: {} ({})'.format(type(a), a))

    return a

# TODO: don't hardcode sizeof_int here 
Example #5
Source File: registration.py    From gym-pull with MIT License 6 votes vote down vote up
def __init__(self, id, entry_point=None, timestep_limit=1000, trials=100, reward_threshold=None, local_only=False, kwargs=None, nondeterministic=False, wrappers=None):
        self.id = id
        # Evaluation parameters
        self.timestep_limit = timestep_limit
        self.trials = trials
        self.reward_threshold = reward_threshold
        # Environment properties
        self.nondeterministic = nondeterministic

        # We may make some of these other parameters public if they're
        # useful.
        match = env_id_re.search(id)
        if not match:
            raise error.Error('Attempted to register malformed environment ID: {}. (Currently all IDs must be of the form {}.)'.format(id, env_id_re.pattern))
        self._env_name = match.group(1)
        self._entry_point = entry_point
        self._local_only = local_only
        self._kwargs = {} if kwargs is None else kwargs
        self._wrappers = wrappers 
Example #6
Source File: seeding.py    From DQN-DDPG_Stock_Trading with MIT License 6 votes vote down vote up
def create_seed(a=None, max_bytes=8):
    """Create a strong random seed. Otherwise, Python 2 would seed using
    the system time, which might be non-robust especially in the
    presence of concurrency.

    Args:
        a (Optional[int, str]): None seeds from an operating system specific randomness source.
        max_bytes: Maximum number of bytes to use in the seed.
    """
    # Adapted from https://svn.python.org/projects/python/tags/r32/Lib/random.py
    if a is None:
        a = _bigint_from_bytes(os.urandom(max_bytes))
    elif isinstance(a, str):
        a = a.encode('utf8')
        a += hashlib.sha512(a).digest()
        a = _bigint_from_bytes(a[:max_bytes])
    elif isinstance(a, integer_types):
        a = a % 2**(8 * max_bytes)
    else:
        raise error.Error('Invalid type for seed: {} ({})'.format(type(a), a))

    return a

# TODO: don't hardcode sizeof_int here 
Example #7
Source File: registration.py    From DRL_DeliveryDuel with MIT License 6 votes vote down vote up
def spec(self, id):
        match = env_id_re.search(id)
        if not match:
            raise error.Error('Attempted to look up malformed environment ID: {}. (Currently all IDs must be of the form {}.)'.format(id.encode('utf-8'), env_id_re.pattern))

        try:
            return self.env_specs[id]
        except KeyError:
            # Parse the env name and check to see if it matches the non-version
            # part of a valid env (could also check the exact number here)
            env_name = match.group(1)
            matching_envs = [valid_env_name for valid_env_name, valid_env_spec in self.env_specs.items()
                             if env_name == valid_env_spec._env_name]
            if matching_envs:
                raise error.DeprecatedEnv('Env {} not found (valid versions include {})'.format(id, matching_envs))
            else:
                raise error.UnregisteredEnv('No registered env with id: {}'.format(id)) 
Example #8
Source File: agent_register.py    From bullet-gym with MIT License 6 votes vote down vote up
def spec(self, id):
        match = agent_id_re.search(id)
        if not match:
            raise error.Error('Attempted to look up malformed agent ID: {}. (Currently all IDs must be of the form {}.)'.format(id.encode('utf-8'), agent_id_re.pattern))

        try:
            return self.agent_specs[id]
        except KeyError:
            # Parse the agent name and check to see if it matches the non-version
            # part of a valid agent (could also check the exact number here)
            agent_name = match.group(1)
            matching_agents = [valid_agent_name for valid_agent_name, valid_agent_spec in self.agent_specs.items()
                             if agent_name == valid_agent_spec._agent_name]
            if matching_agents:
                raise error.DeprecatedEnv('Agent {} not found (valid versions include {})'.format(id, matching_agents))
            else:
                raise error.UnregisteredEnv('No registered agent with id: {}'.format(id)) 
Example #9
Source File: registration.py    From rl-generalization with MIT License 6 votes vote down vote up
def spec(self, id):
        match = env_id_re.search(id)
        if not match:
            raise error.Error('Attempted to look up malformed environment ID: {}. (Currently all IDs must be of the form {}.)'.format(id.encode('utf-8'), env_id_re.pattern))

        try:
            return self.env_specs[id]
        except KeyError:
            # Parse the env name and check to see if it matches the non-version
            # part of a valid env (could also check the exact number here)
            env_name = match.group(1)
            matching_envs = [valid_env_name for valid_env_name, valid_env_spec in self.env_specs.items()
                             if env_name == valid_env_spec._env_name]
            if matching_envs:
                raise error.DeprecatedEnv('Env {} not found (valid versions include {})'.format(id, matching_envs))
            else:
                raise error.UnregisteredEnv('No registered env with id: {}'.format(id)) 
Example #10
Source File: util.py    From gym-gomoku with MIT License 6 votes vote down vote up
def check_five_in_row(self, board_state):
        ''' Args: board_state 2D list
            Return: exist, color
        '''
        size = len(board_state)
        black_pattern = [self.color_dict[self.BLACK] for _ in range(5)] # [1,1,1,1,1]
        white_pattern = [self.color_dict[self.WHITE] for _ in range(5)] # [2,2,2,2,2]
        
        exist_final = False
        color_final = "empty"
        black_win, _ = self.check_pattern(board_state, black_pattern)
        white_win, _ = self.check_pattern(board_state, white_pattern)
        
        if (black_win and white_win):
            raise error.Error('Both Black and White has 5-in-row, rules conflicts')
        # Check if there is any one party wins
        if not (black_win or white_win):
            return exist_final, "empty"
        else:
            exist_final = True
        if (black_win):
            return exist_final, self.BLACK
        if (white_win):
            return exist_final, self.WHITE 
Example #11
Source File: gomoku.py    From gym-gomoku with MIT License 6 votes vote down vote up
def play(self, action, color):
        '''
            Args: input action, current player color
            Return: new copy of board object
        '''
        b = Board(self.size)
        b.copy(self.board_state) # create a board copy of current board_state
        b.move = self.move
        
        coord = self.action_to_coord(action)
        # check if it's legal move
        if (b.board_state[coord[0]][coord[1]] != 0): # the action coordinate is not empty
            raise error.Error("Action is illegal, position [%d, %d] on board is not empty" % ((coord[0]+1),(coord[1]+1)))
        
        b.board_state[coord[0]][coord[1]] = gomoku_util.color_dict[color]
        b.move += 1 # move counter add 1
        b.last_coord = coord # save last coordinate
        b.last_action = action
        return b 
Example #12
Source File: seeding.py    From ia-course with MIT License 6 votes vote down vote up
def create_seed(a=None, max_bytes=8):
    """Create a strong random seed. Otherwise, Python 2 would seed using
    the system time, which might be non-robust especially in the
    presence of concurrency.

    Args:
        a (Optional[int, str]): None seeds from an operating system specific randomness source.
        max_bytes: Maximum number of bytes to use in the seed.
    """
    # Adapted from https://svn.python.org/projects/python/tags/r32/Lib/random.py
    if a is None:
        a = _bigint_from_bytes(os.urandom(max_bytes))
    elif isinstance(a, str):
        a = a.encode('utf8')
        a += hashlib.sha512(a).digest()
        a = _bigint_from_bytes(a[:max_bytes])
    elif isinstance(a, integer_types):
        a = a % 2**(8 * max_bytes)
    else:
        raise error.Error('Invalid type for seed: {} ({})'.format(type(a), a))

    return a

# TODO: don't hardcode sizeof_int here 
Example #13
Source File: rendering.py    From malib with MIT License 6 votes vote down vote up
def get_display(spec):
    """Convert a display specification (such as :0) into an actual Display
    object.

    Pyglet only supports multiple Displays on Linux.
    """
    if spec is None:
        return None
    elif isinstance(spec, six.string_types):
        return pyglet.canvas.Display(spec)
    else:
        raise error.Error(
            "Invalid display specification: {}. (Must be a string like :0 or None.)".format(
                spec
            )
        ) 
Example #14
Source File: test_registration.py    From DQN-DDPG_Stock_Trading with MIT License 5 votes vote down vote up
def test_malformed_lookup():
    registry = registration.EnvRegistry()
    try:
        registry.spec(u'“Breakout-v0”')
    except error.Error as e:
        assert 'malformed environment ID' in '{}'.format(e), 'Unexpected message: {}'.format(e)
    else:
        assert False 
Example #15
Source File: seeding.py    From DQN-DDPG_Stock_Trading with MIT License 5 votes vote down vote up
def np_random(seed=None):
    if seed is not None and not (isinstance(seed, integer_types) and 0 <= seed):
        raise error.Error('Seed must be a non-negative integer or omitted, not {}'.format(seed))

    seed = create_seed(seed)

    rng = np.random.RandomState()
    rng.seed(_int_list_from_bigint(hash_seed(seed)))
    return rng, seed 
Example #16
Source File: registration.py    From DQN-DDPG_Stock_Trading with MIT License 5 votes vote down vote up
def register(self, id, **kwargs):
        if id in self.env_specs:
            raise error.Error('Cannot re-register id: {}'.format(id))
        self.env_specs[id] = EnvSpec(id, **kwargs)

# Have a global registry 
Example #17
Source File: registration.py    From rl-generalization with MIT License 5 votes vote down vote up
def __init__(self, id, entry_point=None, trials=100, reward_threshold=None, local_only=False, kwargs=None, nondeterministic=False, tags=None, max_episode_steps=None, max_episode_seconds=None, timestep_limit=None):
        self.id = id
        # Evaluation parameters
        self.trials = trials
        self.reward_threshold = reward_threshold
        # Environment properties
        self.nondeterministic = nondeterministic

        if tags is None:
            tags = {}
        self.tags = tags

        # BACKWARDS COMPAT 2017/1/18
        if tags.get('wrapper_config.TimeLimit.max_episode_steps'):
            max_episode_steps = tags.get('wrapper_config.TimeLimit.max_episode_steps')
            # TODO: Add the following deprecation warning after 2017/02/18
            # warnings.warn("DEPRECATION WARNING wrapper_config.TimeLimit has been deprecated. Replace any calls to `register(tags={'wrapper_config.TimeLimit.max_episode_steps': 200)}` with `register(max_episode_steps=200)`. This change was made 2017/1/31 and is included in gym version 0.8.0. If you are getting many of these warnings, you may need to update universe past version 0.21.3")

        tags['wrapper_config.TimeLimit.max_episode_steps'] = max_episode_steps
        ######

        # BACKWARDS COMPAT 2017/1/31
        if timestep_limit is not None:
            max_episode_steps = timestep_limit
            # TODO: Add the following deprecation warning after 2017/03/01
            # warnings.warn("register(timestep_limit={}) is deprecated. Use register(max_episode_steps={}) instead.".format(timestep_limit, timestep_limit))
        ######

        self.max_episode_steps = max_episode_steps
        self.max_episode_seconds = max_episode_seconds

        # We may make some of these other parameters public if they're
        # useful.
        match = env_id_re.search(id)
        if not match:
            raise error.Error('Attempted to register malformed environment ID: {}. (Currently all IDs must be of the form {}.)'.format(id, env_id_re.pattern))
        self._env_name = match.group(1)
        self._entry_point = entry_point
        self._local_only = local_only
        self._kwargs = {} if kwargs is None else kwargs 
Example #18
Source File: seeding.py    From DQN-DDPG_Stock_Trading with MIT License 5 votes vote down vote up
def _int_list_from_bigint(bigint):
    # Special case 0
    if bigint < 0:
        raise error.Error('Seed must be non-negative, not {}'.format(bigint))
    elif bigint == 0:
        return [0]

    ints = []
    while bigint > 0:
        bigint, mod = divmod(bigint, 2 ** 32)
        ints.append(mod)
    return ints 
Example #19
Source File: monitor.py    From DQN-DDPG_Stock_Trading with MIT License 5 votes vote down vote up
def _set_mode(self, mode):
        if mode == 'evaluation':
            type = 'e'
        elif mode == 'training':
            type = 't'
        else:
            raise error.Error('Invalid mode {}: must be "training" or "evaluation"', mode)
        self.stats_recorder.type = type 
Example #20
Source File: physical_world.py    From rl-generalization with MIT License 5 votes vote down vote up
def __init__(self, obs_type='image', frameskip=4, world='baseline'):
        self._env = PhysicalEnvironment(world=self.worlds[world])
        self._world = world
        self.action_space = spaces.Discrete(self._env.world.n_actions)

        if obs_type == 'image':
            self.observation_space = spaces.Box(low=0, high=255, shape=(self._env.height, self._env.width, 3))
        else:
            raise error.Error("Unrecognized observation type: {}".format(obs_type))

        self._obs_type = obs_type
        self._frameskip = frameskip 
Example #21
Source File: monitor.py    From DQN-DDPG_Stock_Trading with MIT License 5 votes vote down vote up
def collapse_env_infos(env_infos, training_dir):
    assert len(env_infos) > 0

    first = env_infos[0]
    for other in env_infos[1:]:
        if first != other:
            raise error.Error('Found two unequal env_infos: {} and {}. This usually indicates that your training directory {} has commingled results from multiple runs.'.format(first, other, training_dir))

    for key in ['env_id', 'gym_version']:
        if key not in first:
            raise error.Error("env_info {} from training directory {} is missing expected key {}. This is unexpected and likely indicates a bug in gym.".format(first, training_dir, key))
    return first 
Example #22
Source File: env_modalities.py    From GtS with MIT License 5 votes vote down vote up
def check_port_available(self):
        assert(self._require_camera_input)
        # TODO (hzyjerry)
        ports = []
        if self._require_depth: ports.append(self.port_depth)
        if self._require_normal: ports.append(self.port_normal)
        if self._require_semantics: ports.append(self.port_sem)
        for port in ports:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                result = s.bind(("127.0.0.1", port - 1))
            except socket.error as e:
                raise e
                raise error.Error("Gibson initialization Error: port {} is in use".format(port))
    # Gym v0.10.5 compatibility 
Example #23
Source File: rendering.py    From multiagent-gail with MIT License 5 votes vote down vote up
def get_display(spec):
    """Convert a display specification (such as :0) into an actual Display
    object.

    Pyglet only supports multiple Displays on Linux.
    """
    if spec is None:
        return None
    elif isinstance(spec, six.string_types):
        return pyglet.canvas.Display(spec)
    else:
        raise error.Error('Invalid display specification: {}. (Must be a string like :0 or None.)'.format(spec)) 
Example #24
Source File: stats_recorder.py    From DQN-DDPG_Stock_Trading with MIT License 5 votes vote down vote up
def before_reset(self):
        assert not self.closed

        if self.done is not None and not self.done and self.steps > 0:
            raise error.Error("Tried to reset environment which is not done. While the monitor is active for {}, you cannot call reset() unless the episode is over.".format(self.env_id))

        self.done = False
        if self.initial_reset_timestamp is None:
            self.initial_reset_timestamp = time.time() 
Example #25
Source File: stats_recorder.py    From ia-course with MIT License 5 votes vote down vote up
def before_reset(self):
        assert not self.closed

        if self.done is not None and not self.done and self.steps > 0:
            raise error.Error("Tried to reset environment which is not done. While the monitor is active for {}, you cannot call reset() unless the episode is over.".format(self.env_id))

        self.done = False
        if self.initial_reset_timestamp is None:
            self.initial_reset_timestamp = time.time() 
Example #26
Source File: stats_recorder.py    From ia-course with MIT License 5 votes vote down vote up
def type(self, type):
        if type not in ['t', 'e']:
            raise error.Error('Invalid episode type {}: must be t for training or e for evaluation', type)
        self._type = type 
Example #27
Source File: monitor.py    From ia-course with MIT License 5 votes vote down vote up
def _set_mode(self, mode):
        if mode == 'evaluation':
            type = 'e'
        elif mode == 'training':
            type = 't'
        else:
            raise error.Error('Invalid mode {}: must be "training" or "evaluation"', mode)
        self.stats_recorder.type = type 
Example #28
Source File: registration.py    From ia-course with MIT License 5 votes vote down vote up
def register(self, id, **kwargs):
        if id in self.env_specs:
            raise error.Error('Cannot re-register id: {}'.format(id))
        self.env_specs[id] = EnvSpec(id, **kwargs)

# Have a global registry 
Example #29
Source File: test_registration.py    From DQN-DDPG_Stock_Trading with MIT License 5 votes vote down vote up
def test_make_deprecated():
    try:
        envs.make('Humanoid-v0')
    except error.Error:
        pass
    else:
        assert False 
Example #30
Source File: registration.py    From ia-course with MIT License 5 votes vote down vote up
def make(self):
        """Instantiates an instance of the environment with appropriate kwargs"""
        if self._entry_point is None:
            raise error.Error('Attempting to make deprecated env {}. (HINT: is there a newer registered version of this env?)'.format(self.id))

        elif callable(self._entry_point):
            env = self._entry_point(**self._kwargs)
        else:
            cls = load(self._entry_point)
            env = cls(**self._kwargs)

        # Make the enviroment aware of which spec it came from.
        env.unwrapped.spec = self

        return env