File size: 14,165 Bytes
0c3dd1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""Plug-in interface for NEW, simulation-only controllers (NEW CODE).

A plug-in sees exactly what the released node sees and is subjected to exactly
the released post-processing:

* state: the released ControlNode.state_callback / vel_callback are applied to
  the plug-in's state object (same theta formula, same planar speed);
* error state: e = ControlNode.error_state(1.0), e_track = error_state(0.0)
  (the released functions, called on the plug-in state object);
* schedule: the same 10 Hz tick / latency model as the released controllers;
* post-processing: the released 0.25-per-tick steering rate limit and
  clipping (path_follower.py:230-242) -- copied verbatim below and verified
  bit-for-bit against the released pub_callback (parity test).

Plug-in contract:
    class MyController(PluginBase):
        name = 'my_controller'
        def reset(self, ref_traj, params): ...
        def compute(self, e, e_track, st) -> (throttle, steering)
`st` exposes x, y, theta, v (as set by the released callbacks), ref_traj,
and the previous throttle/steering. Return raw (unclipped) commands.

The simulation-only controllers below (pure pursuit, Stanley, MPC-N5 and the wrapped released laws) have fixed
defaults; pure pursuit and Stanley gains can be set per episode. They are not used in the paper (except the wrapped
NN-HD) and have no physical evaluation.
"""
import time

import numpy as np


class PluginBase:
    name = 'base'

    def __init__(self, params=None):
        self.params = dict(params or {})

    def reset(self, ref_traj, params):
        pass

    def compute(self, e, e_track, st):
        raise NotImplementedError


class _State:
    pass


class PluginController:
    """Adapter giving a plug-in the released node's interface (observe/tick)."""

    kind = 'plugin'

    def __init__(self, plugin, module):
        self.plugin = plugin
        self.name = 'plugin:' + plugin.name
        self.module = module
        self.st = None

    def reset(self, reference):
        st = _State()
        # same initial values as ControlNode.__init__ (path_follower.py:84-98)
        st.steering = 0.0
        st.throttle = 0.0
        st.braking = 0.0
        st.x = 0.0
        st.y = 0.0
        st.theta = 0.0
        st.v = 0.0
        st.go = False
        st.ref_traj = np.array(reference.array, dtype=float, copy=True)
        self.st = st
        self.plugin.reset(st.ref_traj, self.plugin.params)
        return st

    def observe(self, pose_msg, twist_msg):
        self.module.ControlNode.state_callback(self.st, pose_msg)
        self.module.ControlNode.vel_callback(self.st, twist_msg)

    def tick(self):
        from chrono_ros_interfaces.msg import DriverInputs as VehicleInput
        st = self.st
        out = {'published': False, 'n_published': 0, 'exception': None, 'e': None, 'e_track': None,
               'raw_throttle': None, 'raw_steering': None, 'rate_limited': None,
               'obs_x': float(st.x), 'obs_y': float(st.y), 'obs_theta': float(st.theta), 'obs_v': float(st.v)}
        t0 = time.perf_counter()
        try:
            if not st.go:
                out['ratelimited_steering'] = float(st.steering)
                out['compute_wall_s'] = time.perf_counter() - t0
                return out
            e = self.module.ControlNode.error_state(st, 1.0)
            e_tracking = self.module.ControlNode.error_state(st, 0.0)
            throttle, steering = self.plugin.compute(e, e_tracking, st)
            st.throttle = throttle
            # ---- verbatim copy of path_follower.py:230-242 ----
            delta_steering = steering - st.steering
            if abs(delta_steering) > 0.25:
                st.steering = st.steering + 0.25 * delta_steering / abs(delta_steering)
            else:
                st.steering = steering
            msg = VehicleInput()
            msg.steering = np.clip(st.steering, -1.0, 1.0)
            msg.throttle = np.clip(st.throttle, 0, 1)
            msg.braking = np.clip(st.braking, 0, 1)
            # ----------------------------------------------------
            out.update({'published': True, 'n_published': 1, 'e': [float(v) for v in e],
                        'e_track': [float(v) for v in e_tracking], 'raw_throttle': float(throttle),
                        'raw_steering': float(steering), 'rate_limited': abs(float(delta_steering)) > 0.25,
                        'pub_steering': float(msg.steering), 'pub_throttle': float(msg.throttle),
                        'pub_braking': float(msg.braking)})
        except Exception as exc:
            out['exception'] = exc
        out['ratelimited_steering'] = float(st.steering)
        out['compute_wall_s'] = time.perf_counter() - t0
        return out


# ---------------------------------------------------------------------------
# Simulation-only controllers
# ---------------------------------------------------------------------------
# Every plug-in lists its parameters and defaults in config.PLUGIN_PARAM_SPECS; config.normalize rejects unknown
# plug-ins and unknown / non-finite parameters before a batch starts. The defaults are not tuned.
from .config import PLUGIN_PARAM_SPECS, plugin_effective_params  # noqa: E402

STEER_ANGLE_PER_COMMAND = 0.6  # rad per unit command, as assumed by mpc_wpts.py (delta = u*0.6; cmd = angle*1.6667)


def _wrap(a):
    return float(np.arctan2(np.sin(a), np.cos(a)))


def p_speed_throttle(e, throttle_ff, k_v):
    """P speed loop of the new controllers: throttle = clip(throttle_ff + k_v * (v_ref - v), 0, 1).
    v_ref - v = e[3] of the released error_state(1.0), the same speed error the released controllers receive (every
    released reference and the TR straight line have v_ref = 1.0 m/s at every waypoint)."""
    return float(np.clip(float(throttle_ff) + float(k_v) * float(e[3]), 0.0, 1.0))


class ReplicaPID(PluginBase):
    """Exact replica of the released PID law (path_follower.py:226-227), used to
    verify the plug-in path end-to-end against the released node."""
    name = 'replica_pid'

    def compute(self, e, e_track, st):
        throttle = sum([x * y for x, y in zip(e, [0.37013526, 0.00507144, 0.15476554, 1.0235402])])
        steering = sum([x * y for x, y in zip(e, [0.02176878, 0.72672704, 0.78409284, -0.0105355])])
        return throttle, steering


class PurePursuit(PluginBase):
    """Geometric pure pursuit (simulation-only). Definition:
    position = observed COG (st.x, st.y), heading = st.theta (released state_callback);
    i0 = nearest waypoint (first argmin of the Euclidean distance, as the released zero-lookahead error state);
    target j = first waypoint at or after i0 whose distance from the vehicle is >= lookahead_m (last waypoint if none;
    if the vehicle is farther than lookahead_m from the path, the target is the nearest waypoint);
    L_d = distance to the target, alpha = wrap(atan2(target - position) - heading);
    steering angle delta = atan2(2 * wheelbase_m * sin(alpha), L_d) (= atan(2 L sin(alpha) / L_d));
    steering command = delta / 0.6 (released MPC mapping); throttle = P speed loop (p_speed_throttle).
    Defaults: lookahead_m = 1.0 (the released controller lookahead), wheelbase_m = 0.5 (l_car of the released MPC
    model), k_v = 1.0, throttle_ff = 0.0 (untuned)."""
    name = 'pure_pursuit'

    def reset(self, ref_traj, params):
        self.p = plugin_effective_params(self.name, self.params)

    def compute(self, e, e_track, st):
        p = self.p
        ref = st.ref_traj
        d = np.hypot(ref[:, 0] - st.x, ref[:, 1] - st.y)
        i0 = int(d.argmin())
        ahead = np.flatnonzero(d[i0:] >= p['lookahead_m'])
        j = i0 + int(ahead[0]) if len(ahead) else len(ref) - 1
        dx, dy = float(ref[j, 0] - st.x), float(ref[j, 1] - st.y)
        ld = float(np.hypot(dx, dy))
        alpha = _wrap(np.arctan2(dy, dx) - st.theta)
        delta = float(np.arctan2(2.0 * p['wheelbase_m'] * np.sin(alpha), ld))
        return p_speed_throttle(e, p['throttle_ff'], p['k_v']), delta / STEER_ANGLE_PER_COMMAND


class Stanley(PluginBase):
    """Stanley lateral law (simulation-only), referenced to the observed COG (no front-axle projection).
    Definition: delta = e_track[2] + atan2(k * e_track[1], softening + max(v, 0)), with e_track = the
    released error_state(0.0) (e_track[1] > 0 when the path lies to the vehicle's left, e_track[2] = yaw_ref - yaw;
    positive steering = CCW); steering command = delta / 0.6; throttle = P speed loop (p_speed_throttle).
    Defaults: k = 1.0, softening = 0.5 m/s, k_v = 1.0, throttle_ff = 0.0 (untuned)."""
    name = 'stanley'

    def reset(self, ref_traj, params):
        self.p = plugin_effective_params(self.name, self.params)

    def compute(self, e, e_track, st):
        p = self.p
        delta = float(e_track[2]) + float(np.arctan2(p['k'] * float(e_track[1]), p['softening'] + max(float(st.v), 0.0)))
        return p_speed_throttle(e, p['throttle_ff'], p['k_v']), delta / STEER_ANGLE_PER_COMMAND


class WrappedReleased(PluginBase):
    """Wraps a RELEASED controller law (mpc / nnmpc / pid / nnhd), optionally
    (a) scaling its steering (e.g. NN-HD {base: nnhd, steering_scale: 1.75 or 1.5}; MPC-sluggish
        {base: mpc, steering_scale: 0.5}, PID-aggressive {base: pid, steering_scale: 2.0}) and/or
    (b) replacing its throttle with a shared longitudinal law
        throttle = throttle_bias + kp_speed * (v_ref - v)  (shared-speed option; not used in the paper).
    The released law is called directly (mpc_wpts_solver / model.predict / PID gains) on the released error state,
    inside _call_released_law (the frame the outcome classification treats as the released branch)."""
    name = 'wrapped_released'

    def __init__(self, params=None, module=None):
        super().__init__(params)
        self.module = module

    def reset(self, ref_traj, params):
        self.p = plugin_effective_params(self.name, self.params)
        self.base = self.p['base']
        if self.base not in ('mpc', 'nnmpc', 'pid', 'nnhd'):
            raise ValueError('base must be a released controller')

    def _call_released_law(self, e, st):
        m = self.module
        if self.base == 'mpc':
            thr, steer = m.mpc_wpts_solver(e, [st.throttle, st.steering], st.v, 1)
            steer = steer * 1.6667
        elif self.base in ('nnmpc', 'nnhd'):
            path = ('/sbel/Desktop/ros_ws/src/nn_models_lib/single_speed_MPC_IL_NN.keras' if self.base == 'nnmpc'
                    else '/sbel/Desktop/ros_ws/src/nn_models_lib/single_speed_MC_IL_NN.keras')
            out = m._tr_cached_load_model(path).predict(np.array(e).reshape(1, -1))
            thr, steer = out[0][0], out[0][1]
        else:
            thr = sum([x * y for x, y in zip(e, [0.37013526, 0.00507144, 0.15476554, 1.0235402])])
            steer = sum([x * y for x, y in zip(e, [0.02176878, 0.72672704, 0.78409284, -0.0105355])])
        return thr, steer

    def compute(self, e, e_track, st):
        thr, steer = self._call_released_law(e, st)
        steer = steer * float(self.params.get('steering_scale', 1.0))
        if self.params.get('shared_speed', False):
            thr = float(self.params.get('throttle_bias', 0.0)) + float(self.params.get('kp_speed', 1.0)) * e[3]
        return thr, steer


_MPC_N5 = {'module': None}


def load_mpc_n5_module():
    """Import runner/controllers/mpc_wpts_n5.py once per process after two checks: (1) its SHA256 equals the pinned
    value; (2) its bytes equal the image's released mpc_wpts.py (hash-checked) with the single line
    '        N = 10' replaced by '        N = 5' (so the variant differs from the released MPC ONLY in the horizon)."""
    if _MPC_N5['module'] is not None:
        return _MPC_N5['module']
    import importlib.util
    import os
    import sys
    from .released import MPC_N5_FILE, RELEASED_DIR, RELEASED_SHA256, sha256_file
    got = sha256_file(MPC_N5_FILE)
    if got != MPC_N5_SHA256:
        raise RuntimeError(f'mpc_wpts_n5.py hash mismatch: {got}')
    rel = os.path.join(RELEASED_DIR, 'mpc_wpts.py')
    if sha256_file(rel) != RELEASED_SHA256['mpc_wpts.py']:
        raise RuntimeError('released mpc_wpts.py hash mismatch')
    with open(rel, 'rb') as f:
        released_bytes = f.read()
    with open(MPC_N5_FILE, 'rb') as f:
        copy_bytes = f.read()
    old, new = b'\n        N = 10\n', b'\n        N = 5\n'
    if released_bytes.count(old) != 1 or released_bytes.replace(old, new) != copy_bytes:
        raise RuntimeError('mpc_wpts_n5.py is not the released mpc_wpts.py with only N = 10 -> N = 5')
    spec = importlib.util.spec_from_file_location('mpc_wpts_n5_runner_copy', MPC_N5_FILE)
    mod = importlib.util.module_from_spec(spec)
    sys.modules['mpc_wpts_n5_runner_copy'] = mod
    spec.loader.exec_module(mod)
    _MPC_N5['module'] = mod
    return mod


MPC_N5_SHA256 = 'd6a9530c9e6feed836d1e3a147c91b1a20e07a2227a8972b078197ce19d94b8f'


class MpcN5(PluginBase):
    """MPC-N5 (variant): the released MPC branch of pub_callback (u_prev = [throttle, steering],
    v, v_ref = 1, steering x 1.6667) with the solver from runner/controllers/mpc_wpts_n5.py, i.e. the released
    mpc_wpts.py with prediction horizon N = 5 instead of 10 and no other change. OSQP is pinned and diagnosed exactly
    as for the released MPC (same osqp.OSQP class). No parameters."""
    name = 'mpc_n5'

    def __init__(self, params=None, module=None):
        super().__init__(params)
        self.module = module

    def reset(self, ref_traj, params):
        self.p = plugin_effective_params(self.name, self.params)
        self.solver = load_mpc_n5_module().mpc_wpts_solver

    def _call_mpc_n5_law(self, e, st):
        thr, steer = self.solver(e, [st.throttle, st.steering], st.v, 1)
        return thr, steer * 1.6667

    def compute(self, e, e_track, st):
        return self._call_mpc_n5_law(e, st)


PLUGINS = {cls.name: cls for cls in (ReplicaPID, PurePursuit, Stanley, WrappedReleased, MpcN5)}
_NEEDS_MODULE = (WrappedReleased, MpcN5)


def make_plugin(name, params, module):
    cls = PLUGINS[name]
    if cls in _NEEDS_MODULE:
        return cls(params, module=module)
    return cls(params)