utils.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Finds all the specs that we can test with"""
  2. from typing import Optional
  3. import gym
  4. import numpy as np
  5. from gym import logger
  6. from gym.envs.registration import EnvSpec
  7. def try_make_env(env_spec: EnvSpec) -> Optional[gym.Env]:
  8. """Tries to make the environment showing if it is possible. Warning the environments have no wrappers, including time limit and order enforcing."""
  9. try:
  10. return env_spec.make(disable_env_checker=True).unwrapped
  11. except ImportError as e:
  12. logger.warn(f"Not testing {env_spec.id} due to error: {e}")
  13. return None
  14. # Tries to make all gym_minigrid environment to test with
  15. all_testing_initialised_envs = list(
  16. filter(
  17. None,
  18. [
  19. try_make_env(env_spec)
  20. for env_spec in gym.envs.registry.values()
  21. if env_spec.entry_point.startswith("gym_minigrid.envs")
  22. ],
  23. )
  24. )
  25. all_testing_env_specs = [env.spec for env in all_testing_initialised_envs]
  26. def assert_equals(a, b, prefix=None):
  27. """Assert equality of data structures `a` and `b`.
  28. Args:
  29. a: first data structure
  30. b: second data structure
  31. prefix: prefix for failed assertion message for types and dicts
  32. """
  33. assert type(a) == type(b), f"{prefix}Differing types: {a} and {b}"
  34. if isinstance(a, dict):
  35. assert list(a.keys()) == list(b.keys()), f"{prefix}Key sets differ: {a} and {b}"
  36. for k in a.keys():
  37. v_a = a[k]
  38. v_b = b[k]
  39. assert_equals(v_a, v_b)
  40. elif isinstance(a, np.ndarray):
  41. np.testing.assert_array_equal(a, b)
  42. elif isinstance(a, tuple):
  43. for elem_from_a, elem_from_b in zip(a, b):
  44. assert_equals(elem_from_a, elem_from_b)
  45. else:
  46. assert a == b