File size: 7,738 Bytes
c399dd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
"""Train new PPO goal-reaching policies on the ROM (Sim2Sim campaign, Case 2).

Copies the release GoalEnv dynamics, reward and PPO hyperparameters (rl_script/rl_train_goal_reach.py)
into a Gymnasium env, because SB3 2.7 needs Gymnasium. Only the training-noise config and the seed change.

Configs:
  nonoise : no action noise; powertrain fixed at tau0=1000, omega0=2600.
  release : release semantics. N(0,0.05) on throttle and steering each step; tau0, omega0 drawn once
            at env construction with sd 50 and 100.
  robust  : N(0,0.10) action noise; tau0, omega0 redrawn every episode with sd 100 and 200;
            actuation delay drawn every episode uniform from {0,1,2} control steps (0-0.2 s).

Usage: python train_ppo.py --config release --seed 11 --out policies/release_s11
"""
import argparse
import json
import platform
import time
from pathlib import Path

import gymnasium as gym
import numpy as np
import torch as th
from gymnasium import spaces
from stable_baselines3 import PPO
from stable_baselines3.common.callbacks import BaseCallback
from stable_baselines3.common.vec_env import DummyVecEnv

CONFIGS = {
    'nonoise': dict(act_sigma=0.0, tau_sigma=0.0, omega_sigma=0.0, powertrain_redraw='never', delay_steps=[0]),
    'release': dict(act_sigma=0.05, tau_sigma=50.0, omega_sigma=100.0, powertrain_redraw='construction', delay_steps=[0]),
    'robust': dict(act_sigma=0.10, tau_sigma=100.0, omega_sigma=200.0, powertrain_redraw='episode', delay_steps=[0, 1, 2]),
}


class GoalEnvG(gym.Env):
    """Release GoalEnv (same constants, dynamics, reward, termination), Gymnasium API, configurable noise."""

    def __init__(self, cfg, seed):
        super().__init__()
        self.cfg = cfg
        self.rng = np.random.default_rng(seed)
        self.action_space = spaces.Box(low=np.array([0.2, -1.0]), high=np.array([0.5, 1.0]), shape=(2,), dtype=np.float32)
        self.observation_space = spaces.Box(low=-np.inf, high=np.inf, shape=(4,), dtype=np.float32)
        self.r_wheel, self.i_wheel, self.gamma = 0.47, 6.69, 1 / 3
        self.c1, self.c0, self.car_length = 1e-4, 0.02, 1.0
        self.dt, self.max_steps = 0.1, 400
        self._draw_powertrain()
        self.old_distance = 0.0

    def _draw_powertrain(self):
        self.tau_0 = 1000 + self.rng.normal(0, self.cfg['tau_sigma'])
        self.omega_0 = 2600 + self.rng.normal(0, self.cfg['omega_sigma'])

    def f_vdot(self, alpha, v):
        omega_m = v / (self.r_wheel * self.gamma)
        f1_m = -self.tau_0 * omega_m / self.omega_0 + self.tau_0
        T_fun = alpha * f1_m - self.c1 * omega_m - self.c0
        return T_fun * self.gamma / self.i_wheel * self.r_wheel

    def relative_state_to_goal(self):
        x, y, theta, v = self.state[:4]
        rot_mat = np.array([[np.cos(theta), np.sin(theta)], [-np.sin(theta), np.cos(theta)]])
        relative_pos = np.dot(rot_mat, np.array(self.goal) - np.array([x, y]))
        relative_theta = np.arctan2(relative_pos[1], relative_pos[0])
        return np.array([relative_pos[0], relative_pos[1], relative_theta, v], dtype=np.float32)

    def reset(self, seed=None, options=None):
        if self.cfg['powertrain_redraw'] == 'episode':
            self._draw_powertrain()
        self.delay = int(self.rng.choice(self.cfg['delay_steps']))
        self.queue = [np.array([0.0, 0.0])] * self.delay
        r = self.rng.uniform(10.0, 20.0)
        theta = self.rng.uniform(0, 2 * np.pi)
        self.goal = [r * np.cos(theta), r * np.sin(theta)]
        self.state = np.array([0, 0, 0, 0.0], dtype=np.float32)
        self.steps = 0
        self.old_distance = np.sqrt(self.goal[0] ** 2 + self.goal[1] ** 2)
        return self.relative_state_to_goal(), {}

    def step(self, action):
        self.queue.append(np.asarray(action, dtype=np.float64))
        alpha, beta = self.queue.pop(0)
        if self.cfg['act_sigma'] > 0:
            alpha = alpha + self.rng.normal(0, self.cfg['act_sigma'])
            beta = beta + self.rng.normal(0, self.cfg['act_sigma'])
        x, y, theta, v = self.state
        x_dot = np.cos(theta) * v
        y_dot = np.sin(theta) * v
        theta_dot = v * np.tan(beta * 0.7) / self.car_length
        v_dot = self.f_vdot(alpha, v)
        x += x_dot * self.dt
        y += y_dot * self.dt
        theta += theta_dot * self.dt
        v += v_dot * self.dt
        v = np.clip(v, 0.0, 5.0)
        self.state = np.array([x, y, theta, v], dtype=np.float32)
        self.steps += 1
        distance = np.sqrt((x - self.goal[0]) ** 2 + (y - self.goal[1]) ** 2)
        progress = self.old_distance - distance
        reward = 0.0
        if progress > 0:
            reward = progress * 50
        if progress < 0.1:
            reward -= 100
        done = False
        if distance < 1.0:
            reward += self.max_steps * 15
            done = True
        if self.steps >= self.max_steps:
            reward -= 1000 * distance
            done = True
        self.old_distance = distance
        # Release treats both goal and timeout as terminal (old Gym done=True); keep that.
        return self.relative_state_to_goal(), float(reward), done, False, {'velocity': float(v)}


class SaveEvery(BaseCallback):
    def __init__(self, every, out):
        super().__init__()
        self.every, self.out, self.k = every, Path(out), 0
        self.ep_returns, self.cur = [], 0.0

    def _on_step(self):
        self.cur += float(self.locals['rewards'][0])
        if self.locals['dones'][0]:
            self.ep_returns.append(self.cur)
            self.cur = 0.0
        if self.n_calls % self.every == 0:
            self.k += 1
            self.model.save(self.out / f'ckpt_{self.k}.zip')
        return True


def main():
    p = argparse.ArgumentParser()
    p.add_argument('--config', choices=list(CONFIGS), required=True)
    p.add_argument('--seed', type=int, required=True)
    p.add_argument('--out', required=True)
    p.add_argument('--timesteps', type=int, default=2_000_000)
    p.add_argument('--save-every', type=int, default=500_000)
    a = p.parse_args()
    th.set_num_threads(1)
    out = Path(a.out)
    out.mkdir(parents=True, exist_ok=False)
    cfg = CONFIGS[a.config]
    env = GoalEnvG(cfg, seed=a.seed + 7)
    vec = DummyVecEnv([lambda: env])
    model = PPO('MlpPolicy', vec, learning_rate=3e-4, n_steps=env.max_steps * 3, batch_size=64, n_epochs=20,
                gamma=0.99, clip_range=0.2, verbose=0, seed=a.seed, device='cpu',
                policy_kwargs=dict(net_arch=dict(pi=[64, 128, 128, 64], vf=[64, 128, 128, 64]), activation_fn=th.nn.ReLU))
    cb = SaveEvery(a.save_every, out)
    t0 = time.time()
    model.learn(total_timesteps=a.timesteps, callback=cb)
    rets = np.array(cb.ep_returns)
    meta = dict(config=a.config, config_values=cfg, seed=a.seed, env_seed=a.seed + 7, timesteps=a.timesteps,
                save_every=a.save_every, wall_s=time.time() - t0,
                fixed_construction_powertrain=dict(tau0=env.tau_0, omega0=env.omega_0) if cfg['powertrain_redraw'] == 'construction' else None,
                episodes=len(rets), mean_return_last100=float(rets[-100:].mean()) if len(rets) else None,
                hyperparameters=dict(learning_rate=3e-4, n_steps=1200, batch_size=64, n_epochs=20, gamma=0.99, clip_range=0.2,
                                     net_arch=[64, 128, 128, 64], activation='ReLU'),
                versions=dict(python=platform.python_version(), torch=th.__version__, numpy=np.__version__,
                              sb3=__import__('stable_baselines3').__version__))
    np.save(out / 'episode_returns.npy', rets.astype(np.float32))
    (out / 'train_meta.json').write_text(json.dumps(meta, indent=2) + '\n')


if __name__ == '__main__':
    main()