training_navigation.py 5.13 KB
Newer Older
1
2
3
from flatland.envs.rail_env import *
from flatland.core.env_observation_builder import TreeObsForRailEnv
from flatland.utils.rendertools import *
4
5
from flatland.baselines.dueling_double_dqn import Agent
from collections import deque
Erik Nygren's avatar
Erik Nygren committed
6
import torch, random
7

8
9
10
random.seed(1)
np.random.seed(1)

11
12
# Example generate a rail given a manual specification,
# a map of tuples (cell_type, rotation)
13
14
15
16
17
18
19
20
transition_probability = [5,  # empty cell - Case 0
                          15,  # Case 1 - straight
                          5,  # Case 2 - simple switch
                          1,  # Case 3 - diamond crossing
                          1,  # Case 4 - single slip
                          1,  # Case 5 - double slip
                          1,  # Case 6 - symmetrical
                          0]  # Case 7 - dead end
21
22

# Example generate a random rail
23
24
env = RailEnv(width=10,
              height=10,
25
              rail_generator=random_rail_generator(cell_type_relative_proportion=transition_probability),
Erik Nygren's avatar
Erik Nygren committed
26
              number_of_agents=1)
27
"""
28
29
30
31
32
env = RailEnv(width=20,
              height=20,
              rail_generator=complex_rail_generator(nr_start_goal=20, min_dist=10, max_dist=99999, seed=0),
              number_of_agents=5)

Erik Nygren's avatar
Erik Nygren committed
33

34
35
36
env = RailEnv(width=20,
              height=20,
              rail_generator=rail_from_list_of_saved_GridTransitionMap_generator(
37
                  ['../env-data/tests/circle.npy']),
38
              number_of_agents=1)
Erik Nygren's avatar
Erik Nygren committed
39
"""
40

41
env_renderer = RenderTool(env, gl="QT")
Erik Nygren's avatar
Erik Nygren committed
42
handle = env.get_agent_handles()
43

Erik Nygren's avatar
Erik Nygren committed
44
state_size = 105
45
action_size = 4
Erik Nygren's avatar
Erik Nygren committed
46
n_trials = 15000
47
48
49
50
51
52
53
54
eps = 1.
eps_end = 0.005
eps_decay = 0.998
action_dict = dict()
scores_window = deque(maxlen=100)
done_window = deque(maxlen=100)
scores = []
dones_list = []
Erik Nygren's avatar
Erik Nygren committed
55
action_prob = [0] * 4
56
agent = Agent(state_size, action_size, "FC", 0)
57
agent.qnetwork_local.load_state_dict(torch.load('../flatland/baselines/Nets/avoid_checkpoint14900.pth'))
Erik Nygren's avatar
Erik Nygren committed
58
59
60

demo = True

Erik Nygren's avatar
Erik Nygren committed
61

Erik Nygren's avatar
Erik Nygren committed
62
63
64
65
66
def max_lt(seq, val):
    """
    Return greatest item in seq for which item < val applies.
    None is returned if seq was empty or all items in seq were >= val.
    """
Erik Nygren's avatar
Erik Nygren committed
67
    max = 0
Erik Nygren's avatar
Erik Nygren committed
68
    idx = len(seq) - 1
Erik Nygren's avatar
Erik Nygren committed
69
70
71
72
73
    while idx >= 0:
        if seq[idx] < val and seq[idx] >= 0 and seq[idx] > max:
            max = seq[idx]
        idx -= 1
    return max
Erik Nygren's avatar
Erik Nygren committed
74

Erik Nygren's avatar
Erik Nygren committed
75

Erik Nygren's avatar
Erik Nygren committed
76
77
78
79
80
81
def min_lt(seq, val):
    """
    Return smallest item in seq for which item > val applies.
    None is returned if seq was empty or all items in seq were >= val.
    """
    min = np.inf
Erik Nygren's avatar
Erik Nygren committed
82
    idx = len(seq) - 1
Erik Nygren's avatar
Erik Nygren committed
83
    while idx >= 0:
Erik Nygren's avatar
Erik Nygren committed
84
85
        if seq[idx] > val and seq[idx] < min:
            min = seq[idx]
Erik Nygren's avatar
Erik Nygren committed
86
        idx -= 1
Erik Nygren's avatar
Erik Nygren committed
87
    return min
88

Erik Nygren's avatar
Erik Nygren committed
89

90
for trials in range(1, n_trials + 1):
91

92
    # Reset environment
93
    obs = env.reset()
94
    for a in range(env.number_of_agents):
95
        norm = max(1, max_lt(obs[a], np.inf))
Erik Nygren's avatar
Erik Nygren committed
96
        obs[a] = np.clip(np.array(obs[a]) / norm, -1, 1)
97

98
99
100
101
102
103
    # env.obs_builder.util_print_obs_subtree(tree=obs[0], num_elements_per_node=5)

    score = 0
    env_done = 0

    # Run episode
104
    for step in range(100):
Erik Nygren's avatar
Erik Nygren committed
105
106
        if demo:
            env_renderer.renderEnv(show=True)
Erik Nygren's avatar
Erik Nygren committed
107
        # print(step)
108
109
        # Action
        for a in range(env.number_of_agents):
Erik Nygren's avatar
Erik Nygren committed
110
111
            if demo:
                eps = 0
112
            action = agent.act(np.array(obs[a]), eps=eps)
113
            action_prob[action] += 1
114
            action_dict.update({a: action})
115
            #env.obs_builder.util_print_obs_subtree(tree=obs[a], num_features_per_node=5)
116
117
        # Environment step
        next_obs, all_rewards, done, _ = env.step(action_dict)
118
        for a in range(env.number_of_agents):
Erik Nygren's avatar
Erik Nygren committed
119
120
            norm = max(1, max_lt(next_obs[a], np.inf))
            next_obs[a] = np.clip(np.array(next_obs[a]) / norm, -1, 1)
121
122
123
124
125
126
        # Update replay buffer and train agent
        for a in range(env.number_of_agents):
            agent.step(obs[a], action_dict[a], all_rewards[a], next_obs[a], done[a])
            score += all_rewards[a]

        obs = next_obs.copy()
127
        if done['__all__']:
128
129
            env_done = 1
            break
130
    # Epsilon decay
131
    eps = max(eps_end, eps_decay * eps)  # decrease epsilon
Erik Nygren's avatar
Erik Nygren committed
132

133
134
135
136
    done_window.append(env_done)
    scores_window.append(score)  # save most recent score
    scores.append(np.mean(scores_window))
    dones_list.append((np.mean(done_window)))
Erik Nygren's avatar
Erik Nygren committed
137

Erik Nygren's avatar
Erik Nygren committed
138
139
140
141
142
143
144
145
146
147
    print(
        '\rTraining {} Agents.\tEpisode {}\tAverage Score: {:.0f}\tDones: {:.2f}%\tEpsilon: {:.2f} \t Action Probabilities: \t {}'.format(
            env.number_of_agents,
            trials,
            np.mean(
                scores_window),
            100 * np.mean(
                done_window),
            eps, action_prob / np.sum(action_prob)),
        end=" ")
148
149
    if trials % 100 == 0:
        print(
150
            '\rTraining {} Agents.\tEpisode {}\tAverage Score: {:.0f}\tDones: {:.2f}%\tEpsilon: {:.2f} \t Action Probabilities: \t {}'.format(
Erik Nygren's avatar
Erik Nygren committed
151
152
153
154
155
156
                env.number_of_agents,
                trials,
                np.mean(
                    scores_window),
                100 * np.mean(
                    done_window),
157
                eps, action_prob / np.sum(action_prob)))
Erik Nygren's avatar
Erik Nygren committed
158
159
        torch.save(agent.qnetwork_local.state_dict(),
                   '../flatland/baselines/Nets/avoid_checkpoint' + str(trials) + '.pth')
Erik Nygren's avatar
Erik Nygren committed
160
        action_prob = [1] * 4