File size: 18,736 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
"""Bridge that executes the RELEASED Case 1 controller code verbatim (NEW CODE).

The released ROS 2 node /sbel/Desktop/ros_ws/src/path_follower/path_follower/
path_follower.py and its MPC module mpc_wpts.py are imported unchanged from the
image (SHA256 checked against pinned values). Only the rclpy executor layer is replaced (ros_stubs.py).
ControlNode.state_callback, vel_callback, error_state and pub_callback run
unmodified; the DriverInputs message passed to publish() is intercepted.

Two non-numerical adaptations, both verified by parity tests:
1. keras_core.models.load_model is wrapped by a cache that (a) checks the
   SHA256 of the requested released checkpoint, (b) loads it from a
   byte-identical private copy (keras_core opens .keras files with mode
   'r+b', which a non-root container user cannot do on the root-owned
   originals), and (c) returns the same model object for every new
   ControlNode so a fresh node per episode costs no reload.
2. model.predict is wrapped to force verbose=0 (silences the progress bar;
   no numerical effect -- checked bitwise in the parity test).

Raw (pre-rate-limit) controller outputs are read from pub_callback's own
local variables with a sys.settrace hook that only observes the pub_callback
frame (no code is changed or re-implemented).
"""
import hashlib
import importlib.util
import os
import shutil
import sys
import time

import numpy as np

from . import ros_stubs

RELEASED_DIR = '/sbel/Desktop/ros_ws/src/path_follower/path_follower'
RELEASED_SHA256 = {
    'path_follower.py': '1df60ad0cc857d366c48d644ad5c01d05d6b93589b71617b4adf718c3cddf870',
    'mpc_wpts.py': '68b2fac17a53799832715b4c7503d3bbe1762aee7432dbdc853985a8f70c35a8',
}
CHECKPOINT_SHA256 = {
    '/sbel/Desktop/ros_ws/src/nn_models_lib/single_speed_MC_IL_NN.keras':
        '4acd9d199d81bb981f5f6cd43c5a87ba2f994d886aaa50e2a6a8d2e9c0c2305f',
    '/sbel/Desktop/ros_ws/src/nn_models_lib/single_speed_MPC_IL_NN.keras':
        '65118a5c45d9018aef4a6258b1bca23dfe3dde37ff708c6bba61d4b16392bae0',
}
WAYPOINT_DIR = '/sbel/Desktop/waypoints_paths'
# Controller copies shipped with the runner: path relative to runner/ and the
# pinned SHA256 (checked before import). The copy differs from the released mpc_wpts.py only in the horizon N.
RUNNER_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MPC_N5_FILE = os.path.join(RUNNER_ROOT, 'controllers', 'mpc_wpts_n5.py')
CONTROLLER_COPY_FILES = (MPC_N5_FILE,)
RELEASED_CONTROLLERS = ('mpc', 'nnmpc', 'pid', 'nnhd')
OSQP_FAILURE_TEXT = 'OSQP did not solve the problem!'

_MODULE = None
_MODEL_CACHE = {}
_OSQP_PIN = {'interval': 25, 'patched': False}
# READ-ONLY OSQP diagnostics. Every
# osqp.OSQP.solve() call made by released MPC code (or an MPC-based plug-in) appends one record here; the episode loop
# drains the list after each controller tick and writes mpc_diag.csv.gz. Nothing is passed back into the solver.
_OSQP_DIAG = {'records': []}
OSQP_INFO_FIELDS = ('status', 'status_val', 'status_polish', 'iter', 'rho_updates', 'rho_estimate', 'obj_val',
                    'pri_res', 'dua_res', 'setup_time', 'solve_time', 'update_time', 'polish_time', 'run_time')
OSQP_WALL_FIELDS = ('setup_time', 'solve_time', 'update_time', 'polish_time', 'run_time')  # wall clock (seconds)


def set_osqp_adaptive_rho_interval(n):
    """None = released behaviour (OSQP picks the interval from wall-clock time); int = pinned."""
    _OSQP_PIN['interval'] = n


def osqp_diag_take():
    """Return and clear the OSQP solve records collected since the last call."""
    recs = _OSQP_DIAG['records']
    _OSQP_DIAG['records'] = []
    return recs


def _record_osqp_solve(prob, res):
    """Copy scalar fields of res.info and the problem size into a plain dict. Read-only: it only reads attributes of
    the returned results object, the Python-side setup record and OSQP.dimensions() (two C ints). It never calls
    OSQP._model._get_workspace(), which in osqp 0.6.5 wraps the solver's own C memory in numpy arrays flagged
    OWNDATA (src/extension/include/osqpworkspacepy.h) and is therefore unsafe to call on a live solver.
    Never raises (a diagnostic failure is recorded in 'diag_error' and cannot change an outcome)."""
    try:
        info = getattr(res, 'info', None)
        rec = {k: getattr(info, k, None) for k in OSQP_INFO_FIELDS}
        rec['adaptive_rho_interval_requested'] = getattr(prob, '_tr_adaptive_rho_interval', None)
        rec['setup_max_iter'] = getattr(prob, '_tr_max_iter', None)
        rec['setup_warm_start'] = getattr(prob, '_tr_warm_start', None)
        try:
            n, m = prob._model.dimensions()
            rec['qp_n'], rec['qp_m'] = int(n), int(m)
        except Exception:
            rec['qp_n'] = rec['qp_m'] = None
        rec['diag_error'] = None
    except Exception as e:  # pragma: no cover - defensive
        rec = {'diag_error': f'{type(e).__name__}: {e}'}
    _OSQP_DIAG['records'].append(rec)


def _patch_osqp():
    """Wrap osqp.OSQP.setup so that, if pinned, adaptive_rho_interval=<n> is passed. The released call
    prob.setup(P, q, A, l, u, warm_start=True, max_iter=10000) is otherwise unchanged.
    Also wraps osqp.OSQP.solve READ-ONLY. The wrapper calls the original
    solve with the same arguments, records res.info (status, iterations, rho updates / estimate, wall timings) and the
    problem size, and returns the identical results object. The setup wrapper additionally stores the settings it
    passed (adaptive_rho_interval, max_iter, warm_start) as attributes of the Python OSQP object."""
    import osqp
    if _OSQP_PIN['patched']:
        return
    original_setup = osqp.OSQP.setup
    original_solve = osqp.OSQP.solve

    def setup(self, *args, **kwargs):
        if _OSQP_PIN['interval'] is not None and 'adaptive_rho_interval' not in kwargs:
            kwargs['adaptive_rho_interval'] = _OSQP_PIN['interval']
        self._tr_adaptive_rho_interval = kwargs.get('adaptive_rho_interval')  # None = OSQP automatic (wall clock)
        self._tr_max_iter = kwargs.get('max_iter')
        self._tr_warm_start = kwargs.get('warm_start')
        return original_setup(self, *args, **kwargs)

    def solve(self, *args, **kwargs):
        res = original_solve(self, *args, **kwargs)
        _record_osqp_solve(self, res)
        return res

    setup._tr_original = original_setup
    solve._tr_original = original_solve
    osqp.OSQP.setup = setup
    osqp.OSQP.solve = solve
    _OSQP_PIN['patched'] = True


def sha256_file(path):
    h = hashlib.sha256()
    with open(path, 'rb') as f:
        for chunk in iter(lambda: f.read(1 << 20), b''):
            h.update(chunk)
    return h.hexdigest()


def load_released_module(cache_dir=None):
    """Import the released path_follower.py once per process and return it."""
    global _MODULE
    if _MODULE is not None:
        return _MODULE
    for name, digest in RELEASED_SHA256.items():
        got = sha256_file(os.path.join(RELEASED_DIR, name))
        if got != digest:
            raise RuntimeError(f'released {name} hash mismatch: {got}')
    os.environ['KERAS_BACKEND'] = 'torch'
    ros_stubs.install()
    _patch_osqp()
    import keras_core.models
    cache_dir = cache_dir or os.path.join(os.environ.get('TMPDIR', '/tmp'), f'tr_c1_ckpt_{os.getpid()}')
    os.makedirs(cache_dir, exist_ok=True)
    original_load_model = keras_core.models.load_model

    def cached_load_model(filepath, *args, **kwargs):
        key = os.path.abspath(filepath)
        if key not in _MODEL_CACHE:
            expected = CHECKPOINT_SHA256.get(key)
            if expected is None:
                raise RuntimeError(f'unexpected checkpoint requested: {key}')
            got = sha256_file(key)
            if got != expected:
                raise RuntimeError(f'checkpoint hash mismatch {key}: {got}')
            copy = os.path.join(cache_dir, os.path.basename(key))
            shutil.copyfile(key, copy)
            if sha256_file(copy) != expected:
                raise RuntimeError('checkpoint copy hash mismatch')
            model = original_load_model(copy, *args, **kwargs)
            original_predict = model.predict

            def predict_silent(x, *a, **k):
                k['verbose'] = 0
                return original_predict(x, *a, **k)

            model._tr_original_predict = original_predict
            model.predict = predict_silent
            _MODEL_CACHE[key] = model
        return _MODEL_CACHE[key]

    keras_core.models.load_model = cached_load_model
    spec = importlib.util.spec_from_file_location('path_follower_released',
                                                  os.path.join(RELEASED_DIR, 'path_follower.py'))
    module = importlib.util.module_from_spec(spec)
    sys.modules['path_follower_released'] = module
    spec.loader.exec_module(module)
    keras_core.models.load_model = original_load_model
    solver_file = module.mpc_wpts_solver.__code__.co_filename
    if os.path.realpath(solver_file) != os.path.realpath(os.path.join(RELEASED_DIR, 'mpc_wpts.py')):
        raise RuntimeError(f'mpc_wpts imported from unexpected file {solver_file}')
    module._tr_cached_load_model = cached_load_model
    _MODULE = module
    return module


# ---------------------------------------------------------------------------
# Message construction (exactly what ChROSBodyHandler publishes)
# ---------------------------------------------------------------------------
def make_messages(state, noise=(0.0, 0.0, 0.0)):
    """Build (PoseStamped, TwistStamped) from a physics-server state dict.

    ChROSBodyHandler.cpp:52-85 (image): position = chassis->GetPos() (COG),
    orientation.x/y/z/w = rot[0]/rot[1]/rot[2]/rot[3] (Chrono e0=w,e1,e2,e3),
    twist.linear = GetPos_dt() (absolute frame), twist.angular = GetWvel_loc().
    Optional observation noise (dx, dy, dyaw) is applied to the position and
    as a rotation about the world z axis (q' = qz(dyaw) * q).
    """
    from geometry_msgs.msg import PoseStamped, TwistStamped
    pose = PoseStamped()
    twist = TwistStamped()
    t = state['time']
    sec = int(np.floor(t))
    pose.header.stamp.sec = sec
    pose.header.stamp.nanosec = int(round((t - sec) * 1e9)) % 1000000000
    twist.header.stamp = pose.header.stamp
    e0, e1, e2, e3 = (float(state[k]) for k in ('q_e0', 'q_e1', 'q_e2', 'q_e3'))
    dx, dy, dyaw = (float(v) for v in noise)
    if dyaw != 0.0:
        cw, sw = np.cos(0.5 * dyaw), np.sin(0.5 * dyaw)
        e0, e1, e2, e3 = (cw * e0 - sw * e3, cw * e1 - sw * e2, cw * e2 + sw * e1, cw * e3 + sw * e0)
        e0, e1, e2, e3 = float(e0), float(e1), float(e2), float(e3)
    pose.pose.position.x = float(state['cog_x']) + dx
    pose.pose.position.y = float(state['cog_y']) + dy
    pose.pose.position.z = float(state['cog_z'])
    pose.pose.orientation.x = e0
    pose.pose.orientation.y = e1
    pose.pose.orientation.z = e2
    pose.pose.orientation.w = e3
    twist.twist.linear.x = float(state['vel_x'])
    twist.twist.linear.y = float(state['vel_y'])
    twist.twist.linear.z = float(state['vel_z'])
    twist.twist.angular.x = float(state['wloc_x'])
    twist.twist.angular.y = float(state['wloc_y'])
    twist.twist.angular.z = float(state['wloc_z'])
    return pose, twist


class _FrameCapture:
    """sys.settrace hook capturing the locals of one code object at return."""

    def __init__(self, code):
        self.code = code
        self.locals = None

    def global_trace(self, frame, event, arg):
        if frame.f_code is self.code:
            return self.local_trace
        return None

    def local_trace(self, frame, event, arg):
        if event == 'return':
            self.locals = dict(frame.f_locals)
        return self.local_trace


def _f(v):
    return None if v is None else float(v)


class ReleasedController:
    """One of the four released controllers, run through the released node."""

    kind = 'released'

    def __init__(self, name, module=None, capture_locals=True):
        if name not in RELEASED_CONTROLLERS:
            raise ValueError(f'unknown released controller {name}')
        self.name = name
        self.module = module or load_released_module()
        self.capture_locals = capture_locals
        self.node = None
        self._capture = _FrameCapture(self.module.ControlNode.pub_callback.__code__)

    def reset(self, reference):
        """Construct a FRESH ControlNode (released __init__) for a new episode.

        reference.released_stem is passed as the ref_path parameter, so for a
        released CSV the node loads it itself with np.loadtxt; a generated
        reference overrides node.ref_traj after construction.
        """
        ros_stubs.Node.parameter_overrides = {
            'controller': self.name,
            'ref_path': reference.ref_path_parameter,
            'exp_index': 1,
        }
        node = self.module.ControlNode()
        node.file.close()
        if reference.override_array is not None:
            node.ref_traj = np.array(reference.override_array, dtype=float, copy=True)
        self.node = node
        return node

    def observe(self, pose_msg, twist_msg):
        self.node.state_callback(pose_msg)
        self.node.vel_callback(twist_msg)

    def tick(self):
        node = self.node
        n_before = len(node._published)
        cap = self._capture
        cap.locals = None
        exc = None
        t0 = time.perf_counter()
        if self.capture_locals:
            sys.settrace(cap.global_trace)
        try:
            node.pub_callback()
        except Exception as e:  # classified by the episode loop
            exc = e
        finally:
            if self.capture_locals:
                sys.settrace(None)
        wall = time.perf_counter() - t0
        loc = cap.locals or {}
        published = node._published[n_before:]
        out = {
            'published': len(published) > 0,
            'n_published': len(published),
            'compute_wall_s': wall,
            'exception': exc,
            'e': [float(v) for v in loc['e']] if 'e' in loc else None,
            'e_track': [float(v) for v in loc['e_tracking']] if 'e_tracking' in loc else None,
            'raw_throttle': _f(node.throttle) if 'e' in loc else None,
            'raw_steering': _f(loc.get('steering')),
            'rate_limited': (abs(float(loc['delta_steering'])) > 0.25) if 'delta_steering' in loc else None,
            'ratelimited_steering': _f(node.steering),
            'obs_x': float(node.x), 'obs_y': float(node.y), 'obs_theta': float(node.theta), 'obs_v': float(node.v),
        }
        if published:
            msg = published[-1]
            out['pub_steering'] = float(msg.steering)
            out['pub_throttle'] = float(msg.throttle)
            out['pub_braking'] = float(msg.braking)
        return out


def controller_code_files():
    """Files whose code counts as CONTROLLER code for the outcome classification: the released node and MPC module
    in the image, plus verbatim-derived controller copies shipped with the runner (runner/controllers/, e.g. the
    MPC-N5 variant)."""
    files = {os.path.realpath(os.path.join(RELEASED_DIR, n)) for n in RELEASED_SHA256}
    files |= {os.path.realpath(p) for p in CONTROLLER_COPY_FILES}
    return files


def classify_controller_exception(exc):
    """Return (category, text). category in {'controller_solver_failure', 'controller_exception', 'infrastructure'}.

    Anchors are frames in controller code (released files, controller copies) or a plug-in frame that hands control
    to a released law (_PLUGIN_LAW_ANCHORS: plugin:wrapped_released and plugin:mpc_n5). Rules, deepest frame last:
      * OSQP 'did not solve' ValueError raised in controller code            -> controller_solver_failure
      * no anchor on the stack                                               -> infrastructure (runner / plug-in bug)
      * deepest frame in runner code (art_runner/), incl. the anchor itself  -> infrastructure
      * a runner frame between the last anchor and the deepest frame that is not a transparent wrapper
                                                                             -> infrastructure
      * otherwise (deepest frame in keras / torch / osqp / numpy / scipy / other libraries or controller code)
                                                                             -> controller_exception
    For the four released controllers the anchors are exactly the released-file frames, so their classification is
    unchanged by the plug-in anchors."""
    import traceback
    tb = traceback.extract_tb(exc.__traceback__)
    files = [os.path.realpath(fr.filename) for fr in tb]
    ctrl = controller_code_files()
    own = os.path.realpath(os.path.dirname(os.path.abspath(__file__)))
    text = ''.join(traceback.format_exception(type(exc), exc, exc.__traceback__))[-4000:]

    def is_runner(f):
        return f.startswith(own + os.sep) and f not in ctrl

    if isinstance(exc, ValueError) and str(exc) == OSQP_FAILURE_TEXT and files and files[-1] in ctrl:
        return 'controller_solver_failure', text
    anchors = [i for i, (f, fr) in enumerate(zip(files, tb))
               if f in ctrl or (is_runner(f) and (os.path.basename(f), fr.name) in _PLUGIN_LAW_ANCHORS)]
    if anchors:
        if is_runner(files[-1]):
            return 'infrastructure', text  # the exception was raised in runner code (stubs, wrappers, plug-in code)
        # The numerically transparent wrappers below sit between released code and keras/OSQP; an exception raised
        # INSIDE those libraries is not labelled infrastructure only because the wrapper frame is on the stack.
        tail = [(f, fr.name) for f, fr in zip(files[anchors[-1] + 1:], tb[anchors[-1] + 1:])]
        if any(is_runner(f) and (os.path.basename(f), n) not in _TRANSPARENT_WRAPPERS for f, n in tail):
            return 'infrastructure', text  # bug in the runner's stubs/wrappers called by controller code
        # raised while executing controller code (incl. third-party libraries it calls)
        return 'controller_exception', text
    return 'infrastructure', text


# Runner frames that only forward a call from controller code to keras_core / OSQP (see module docstring);
# ('released.py', 'solve') = the read-only OSQP diagnostics wrapper.
_TRANSPARENT_WRAPPERS = {('released.py', 'predict_silent'), ('released.py', 'setup'), ('released.py', 'solve')}
# Plug-in frames that call a released controller law directly. They play the
# role of the released pub_callback branch for plugin:wrapped_released (incl. the scaled NN-HD variants
# and the scaled MPC / PID variants) and plugin:mpc_n5.
_PLUGIN_LAW_ANCHORS = {('plugins.py', '_call_released_law'), ('plugins.py', '_call_mpc_n5_law')}