Coveralls logob
Coveralls logo
  • Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

postrational / gym-demo / 168

2 Jun 2019 - 7:30 coverage: 85.593%. Remained the same
168

push

travis-ci

328601fa565fe79af819bf679d001c44?size=18&default=identiconpostrational
Update coveralls from 1.7.0 to 1.8.0 (#62)

101 of 118 relevant lines covered (85.59%)

3.42 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

77.92
/gym_demo/demo.py
1
#!/usr/bin/env python
2

3
"""Usage: gym_demo.py [--steps=NN --no-render --observations] ENV_NAME
4×
4

5
Show a random agent playing in a given OpenAI environment.
6

7
Arguments:
8
  ENV_NAME          Name of the Gym environment to run
9

10
Options:
11
  -h --help
12
  --steps=<STEPS>   How many iteration to run for.  [default: 5000]
13
  --no-render       Don't render the environment graphically.
14
  --observations    Print environment observations.
15

16
"""
17
import re
4×
18
from time import sleep
4×
19
from typing import List, Text
4×
20

21
import gym
4×
22
from docopt import docopt
4×
23

24
from gym_demo.formatting import list_to_columns, print_error, print_header
4×
25

26

27
def get_environment_names() -> List[Text]:
4×
28
    """Return a list of names of registered Open AI Gym environments."""
29
    return sorted(spec.id for spec in gym.envs.registry.all())
4×
30

31

32
def group_environments(env_names: List[Text]) -> List[Text]:
4×
33
    """Group a sorted list of environment names into families."""
34
    names_without_version = [name.split("-")[0] for name in env_names]
4×
35
    family_names = [names_without_version.pop(0)]
4×
36
    for name in names_without_version:
4×
37
        if not family_names[-1] in name:
4×
38
            family_names.append(name)
4×
39
    return family_names
4×
40

41

42
def get_space_description(space: gym.Space) -> Text:
4×
43
    """Return a textual description of gym.Space object."""
44
    description = repr(space)
4×
45
    if isinstance(space, gym.spaces.Box):
4×
46
        description += "\nLow values:\n{0}".format(space.low)
4×
47
        description += "\nHigh values:\n{0}".format(space.high)
4×
48
    return description
4×
49

50

51
def print_environment_description(env: gym.Env) -> None:
4×
52
    """Output the Gym environment description to standard out."""
53
    print_header("Environment: {0}".format(env.spec.id))
4×
54
    print_header("\nObservation Space:")
4×
55
    print(get_space_description(env.observation_space))
4×
56

57
    print_header("\nAction Space:")
4×
58
    print(get_space_description(env.action_space))
4×
59
    if hasattr(env.unwrapped, "get_action_meanings"):
4×
60
        print("Action meanings:", env.unwrapped.get_action_meanings())
!
61
    print("")
4×
62

63

64
def render_environment(env: gym.Env) -> bool:
4×
65
    """Graphically render state of environment.
66

67
    Return true if rendering was successful, false otherwise.
68
    """
69
    try:
4×
70
        env.render()
4×
71
        sleep(0.02)
4×
72
        return True
4×
73
    except NotImplementedError:
4×
74
        return False
4×
75

76

77
def run_environment(
4×
78
    env: gym.Env,
79
    steps_count: int = 1000,
80
    render: bool = True,
81
    print_observation: bool = False,
82
) -> None:
83
    """Execute main environment run loop.
84

85
    Renders environment state graphically and outputs environment information to
86
    standard out.
87

88
    :param env: the environment to run
89
    :param steps_count: how many steps to run for?
90
    :param render: should the environment be rendered graphically?
91
    :param print_observation: should the full observed state be output to std out?
92
    """
93
    env.reset()
4×
94
    print_header("Running environment demonstration...")
4×
95
    print("Unique environment information is output to standard out:")
4×
96
    prev_env_output = None
4×
97
    for step_number in range(steps_count):
4×
98
        observation, reward, done, info = env.step(env.action_space.sample())
4×
99

100
        if render:
4×
101
            render = render_environment(env)
!
102

103
        if (reward, done, info) != prev_env_output:
4×
104
            print("Reward: {0}, Done: {1}, Info: {2}".format(reward, done, info))
4×
105
            prev_env_output = (reward, done, info)
4×
106

107
        if print_observation:
4×
108
            print("Observation: {0}".format(observation))
4×
109

110
        if done:
4×
111
            print("Done after {0} steps.".format(step_number + 1))
4×
112
            break
4×
113

114
    env.close()
4×
115

116

117
def main() -> None:
4×
118
    """Process script argument and run."""
119
    environment_names = get_environment_names()
4×
120
    environment_families = group_environments(environment_names)
4×
121

122
    help_string = "{0}\n\nAvailable environments:\n\n{1}".format(
4×
123
        __doc__, list_to_columns(environment_families)
124
    )
125
    arguments = docopt(help_string)
4×
126

127
    steps = int(arguments.get("--steps"))
!
128
    render_env = not arguments.get("--no-render")
!
129
    print_observations = arguments.get("--observations")
!
130
    env_name = arguments.get("ENV_NAME")
!
131

132
    if env_name in environment_names:
!
133
        environment = gym.make(env_name)
!
134
        print_environment_description(environment)
!
135
        run_environment(environment, steps, render_env, print_observations)
!
136

137
    else:
138
        print_error("ERROR: Environment with requested ID not found.")
!
139
        regex = re.compile(".*{0}.*".format(env_name), re.IGNORECASE)
!
140
        environment_names = [
!
141
            spec.id for spec in gym.envs.registry.all() if regex.match(spec.id)
142
        ]
143
        if len(environment_names):
!
144
            print_header("\nPerhaps you were looking for:")
!
145
            print(list_to_columns(environment_names))
!
146

147

148
if __name__ == "__main__":
4×
149
    main()
!
Troubleshooting · Open an Issue · Sales · Support · ENTERPRISE · CAREERS · STATUS
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2023 Coveralls, Inc