Public release
This commit is contained in:
+32
@@ -0,0 +1,32 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.pyd
|
||||
|
||||
# Models and Archives
|
||||
models/*.onnx
|
||||
telemetry_plugin/release_*/
|
||||
*.zip
|
||||
|
||||
# Visual artifacts
|
||||
hud_preview.png
|
||||
install_log.txt
|
||||
diagnostics/
|
||||
reference/
|
||||
installers/
|
||||
|
||||
# Native build and game/runtime binaries
|
||||
native/**/build/
|
||||
**/__pycache__/
|
||||
*.dll
|
||||
*.exe
|
||||
*.obj
|
||||
*.lib
|
||||
*.pdb
|
||||
*.onnx
|
||||
*.scs
|
||||
|
||||
# Local test/runtime state
|
||||
.coverage
|
||||
*.tmp
|
||||
@@ -0,0 +1,9 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
"C:\Users\Nicholas\.cache\codex-runtimes\codex-primary-runtime\dependencies\native\powershell\pwsh.exe" -NoProfile -ExecutionPolicy Bypass -File "%~dp0native\forward_camera\setup.ps1" -Disable
|
||||
if errorlevel 1 (
|
||||
echo Disable failed or was cancelled. See diagnostics\forward-camera-setup.log.
|
||||
) else (
|
||||
echo SPF disabled. Restart ATS normally.
|
||||
)
|
||||
pause
|
||||
@@ -0,0 +1,9 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
"C:\Users\Nicholas\.cache\codex-runtimes\codex-primary-runtime\dependencies\native\powershell\pwsh.exe" -NoProfile -ExecutionPolicy Bypass -File "%~dp0native\forward_camera\setup.ps1"
|
||||
if errorlevel 1 (
|
||||
echo Camera setup failed or was cancelled. See diagnostics\forward-camera-setup.log.
|
||||
) else (
|
||||
echo Passive camera prototype installed. Restart ATS and keep FSD disengaged for the first test.
|
||||
)
|
||||
pause
|
||||
@@ -0,0 +1,9 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0tools\install_inset_top_right.ps1" -Projection pop-wide
|
||||
if errorlevel 1 (
|
||||
echo Installation failed. Keep ATS and the driving runtime closed; inspect the reported error.
|
||||
) else (
|
||||
echo Top-right Pop wide preview installed. Restart ATS for passive camera verification.
|
||||
)
|
||||
pause
|
||||
@@ -0,0 +1,9 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0tools\install_inset_top_right.ps1"
|
||||
if errorlevel 1 (
|
||||
echo Installation failed. Keep ATS and the driving runtime closed; existing files are preserved or restored.
|
||||
) else (
|
||||
echo Top-right inset installed. Restart ATS; the first run is passive while the new placement is verified.
|
||||
)
|
||||
pause
|
||||
@@ -0,0 +1,9 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0tools\install_pop_camera_rectification.ps1"
|
||||
if errorlevel 1 (
|
||||
echo Installation failed. Keep ATS and the driving runtime closed. Existing files are preserved or restored.
|
||||
) else (
|
||||
echo Asymmetric camera profile installed. No driving calibration is granted. Start ATS manually for passive verification.
|
||||
)
|
||||
pause
|
||||
@@ -0,0 +1,10 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
set "ATS_OP_PWSH=C:\Users\Nicholas\.cache\codex-runtimes\codex-primary-runtime\dependencies\native\powershell\pwsh.exe"
|
||||
"%ATS_OP_PWSH%" -NoProfile -ExecutionPolicy Bypass -File "%~dp0tools\install_tesla_screens.ps1" -EnableDisplay
|
||||
if errorlevel 1 (
|
||||
echo Installation failed. Close ATS first. If Program Files access was denied, run this file as administrator.
|
||||
) else (
|
||||
echo Installation complete. Start ATS and activate ATS OP Tesla screens above the original Tesla mod.
|
||||
)
|
||||
pause
|
||||
@@ -0,0 +1,950 @@
|
||||
# Tesla Semi ATS driving assistant
|
||||
|
||||
## Current runtime: ATS-native autopilot
|
||||
|
||||
`Run-Tesla-FSD.bat` now starts the native ATS backend. It does not load
|
||||
openpilot, WMI, Pop v2, ONNX, or camera inference for control. The backend
|
||||
follows the active game GPS route over the mounted lane graph, reads simulator
|
||||
traffic/trailer geometry and authored signal data, and drives through the
|
||||
verified vJoy input path. The optional in-game SPF bridge (`native/input_bridge`)
|
||||
is retained for explicit diagnostics, but its acknowledgement alone does not
|
||||
prove that ATS has mapped the semantic device into the truck controls. With
|
||||
`--input auto`, the runner therefore selects vJoy first and only tries ETS2LA
|
||||
if vJoy is unavailable; `--input spf`, `--input ets2la`, and `--input vjoy`
|
||||
select a transport explicitly. The Tesla Semi right and left screen surfaces
|
||||
remain the native backend's display and diagnostics output.
|
||||
|
||||
The older WMI/Pop launchers remain available for passive comparison and
|
||||
rollback only. They are not part of the native control path.
|
||||
|
||||
Cabin rendering runs on a separate worker with one pending frame; slow screen
|
||||
updates cannot hold up fresh steering commands. Authored road coordinates are
|
||||
immutable after verification, so detached driving scenes share those static
|
||||
points while copying mutable observations. Lane association projects all
|
||||
segments together. vJoy writes serialize with neutral/release separately from
|
||||
the command mailbox, allowing the next command to be queued during a slow
|
||||
device write. The 500 ms command watchdog remains active. The native actuator
|
||||
worker neutralizes immediately on a failed focus check and latches a fault if
|
||||
it persists for 100 ms; a brief window handoff can resume the existing lease
|
||||
only with an unexpired command. The main loop still releases on focus loss,
|
||||
Escape, or manual takeover. A confirmed fault requires a new human F8 press.
|
||||
The control log records scene-copy, planning, SDK-to-control, command dispatch,
|
||||
and cabin-render timings separately.
|
||||
|
||||
Road-profile handoffs use a fixed qualified bridge between both complete road
|
||||
primitives. Its forward path does not shrink when the truck enters the bridge;
|
||||
lane membership uses that same curve until it joins the next road centerline.
|
||||
The bridge requires verified sources, consecutive GPS edges, an explicit
|
||||
route-bound profile connection, and qualified geometry on both sides. Ordinary
|
||||
off-path, height, heading, and freshness checks still apply.
|
||||
|
||||
Native automatic passing uses the mounted ordinary-road lane definitions and
|
||||
measured actor bodies. When the set speed exceeds a verified lead's speed by
|
||||
more than 5 MPH, the planner checks the adjacent left lane, signals, and follows
|
||||
a road-anchored transition. It keeps the maneuver when the lead leaves the
|
||||
forward view, follows the passing lane, and signals right to return only after
|
||||
the passed consist clears the rear of the player's trailer and the return gap
|
||||
is usable. A controlled junction queue does not trigger a pass. Shoulders and
|
||||
opposing lanes are excluded. The cockpit status and bounded native control log
|
||||
report the maneuver phase and reasons for waiting.
|
||||
|
||||
Lane-change steering and collision checking use the maneuver's chosen path;
|
||||
the departure lane's center and old forward corridor no longer fight the pass.
|
||||
Only a fresh permitted transition expands the lane-membership gate at the
|
||||
midpoint. An occupied lane pauses the maneuver with braking. Lane permissions
|
||||
are refreshed in the background after map expansion, using the current mounted
|
||||
definition catalog rather than retaining an obsolete graph hash.
|
||||
|
||||
A measured parked vehicle blocking the route can trigger the same adjacent-lane
|
||||
bypass. Authored construction-prefab paths remain part of native GPS following.
|
||||
Random roadwork cones, barriers, and full-road detours are **not detected by the
|
||||
vehicle actor reader**. Handling those events requires live event/obstacle
|
||||
geometry and a route that excludes the closed corridor; an empty vehicle list
|
||||
does not establish that a work zone is clear. SCS documents random road events
|
||||
and lane-blocking behavior at
|
||||
https://modding.scssoft.com/wiki/Documentation/Engine/Units/journey_events_road_event
|
||||
and whole-road detours at
|
||||
https://modding.scssoft.com/wiki/Documentation/Engine/Detours.
|
||||
|
||||
## Continuous WMI / Pop v2 gameplay
|
||||
|
||||
`Run-WMI-Drive.bat` selects the pinned stock openpilot 0.11.0 WMI model; `Run-Pop-v2-Drive.bat` retains Pop v2 as a fallback. The panel names the selected model. Both use the same verified split vision/policy tensor layout, decoder, paired narrow/wide camera input and temporal context. To select directly: `python tools/run_pop_gameplay.py --model wmi-v0.11.0` or `--model pop-v2`. Matching contracts do not establish equivalent ATS driving performance.
|
||||
|
||||
Continuous gameplay accepts the Peterbilt 579 and the Tesla Semi, reported by the SDK as `Semi truck 2019`. The installed forward inset and native camera checks remain in use. On October 3, 2026, the user reported that the inset remains fixed through the full camera look range in the Tesla Semi. This is a visual observation; the earlier 579 calibration evidence is preserved separately.
|
||||
|
||||
GPS is optional when fresh SDK telemetry reports zero route distance and the GPS reader explicitly reports no active route. The panel then shows model road following, and F8 can engage without a destination. Setting a destination restores GPS checks; missing or invalid data for an active route does not silently switch to model-only driving.
|
||||
|
||||
Use `Run-Pop-v2-Drive.bat` for continuous experimental driving with Pop v2, analog vJoy steering, and Chill speed hold at the saved target (35 MPH initially). Keep ATS in front, select a forward gear, release the parking brake, and press **F8** when the panel reports ready. F8 toggles driving; manual steering or braking and focus loss release controls. Camera looks remain available. Escape releases driving controls while leaving the panel open, so ATS menus work normally. Close the panel or press Q while it is focused to exit.
|
||||
|
||||
This mode has no trial timer or narrow engagement speed band. Model uncertainty and incomplete historical slots after initial warmup appear as warnings. Disengaging leaves the original model/GPS/traffic dashboard live, and a later F8 press can engage again. The model uses CPU inference; GPS is displayed as route guidance and does not yet steer navigation turns. With ATS focused, **Home raises MAX by 5 MPH; End lowers it by 5 MPH**, while engaged or disengaged. Range is 5–80 MPH. The panel updates immediately and the target is saved for the next launch. First launch defaults to 35 MPH; `python tools/run_pop_gameplay.py --speed 40` overrides the initial target.
|
||||
|
||||
Temporal warmup resamples the policy's historical feature timeline between real
|
||||
recorded model features at the observed CPU cadence. Interpolation is bounded
|
||||
to 250 ms and to normal local cadence; unsupported intervals remain incomplete.
|
||||
Observed/interpolated slot counts and bracket widths are recorded explicitly.
|
||||
Actual camera pairs retain their separate 100 ms sampling bound. A brief capture
|
||||
interruption no longer erases all history; long pauses and projection changes
|
||||
still reset it. An unqualified GPS first-node connection permits camera lane
|
||||
assistance while automatic route execution remains pending. Matched route/model
|
||||
disagreement and manual junction handoffs still retain their control gates.
|
||||
|
||||
Steering follows the actual model path with an 18 metre / 2.5 second lookahead, reducing correction strength when the forecast is shorter. Gameplay speed hold can ramp throttle to 100% for truck load and retains learned holding power near the target instead of repeatedly dropping to coast. Following uses native actor/trailer boxes and the measured truck front extent. Missing motion estimates do not erase a position hazard. A centered camera lead with probability at least 0.90 over three consecutive frames and at least 95 ms can provide a nearer rear estimate or a fallback; adjacent/single-frame detections cannot. Incomplete traffic coverage still requires manual following. SDK feedback from our own vJoy brake is not treated as a manual takeover; physical steering/brake keys still release control. Brief command gaps can recover with a unique model frame no older than 350 ms; a 500 ms command deadline still releases controls and requires a new F8 press.
|
||||
|
||||
Stopping-distance and time-to-contact estimates drive traffic braking, including 100% emergency brake instead of the earlier 20% cap. With fresh measured native motion, low-speed traffic following uses a 16-foot minimum buffer for a moving lead and follows its measured pace; stopped or uncertain leads retain the 26-foot buffer. A matching camera rear can tighten the gap without erasing measured departure motion. Close leads persist as explicitly estimated gaps for at most one second across read dropouts, without extending the last observation timestamp; held estimates cannot enable the reduced queue buffer. A traffic feed gap with no retained lead inhibits throttle while leaving steering engaged. Brief model/path gaps retain traffic braking instead of unconditionally clearing the pedals. The panel labels following/emergency braking and unknown-feed coasting. Native linked trailer chains are bounded to four; unverified or longer chains reject the snapshot, and coverage is still incomplete. These are experimental simulator heuristics, not guaranteed collision avoidance.
|
||||
|
||||
The experimental painted-lane blend is disabled after a reported lane-keeping regression; steering currently uses the previous model-path controller. The helper remains available for offline analysis. A rejected vJoy write gets one identical retry only if the SDK still confirms ownership. Persistent actuator or neutral-write failures leave the panel alive and passive, report the fault, and require a new human F8 press to retry.
|
||||
|
||||
The truck navigator's SDK posted speed limit can raise MAX. A valid limit must remain stable for 0.3 seconds; the first known limit or a change to a higher posted limit raises MAX only if it exceeds the current target, within the existing 80 MPH cap. The automatic offset is +5 MPH while a verified trailer is attached (or its state is still unknown) and +10 MPH when the verified own chain says the tractor is bobtail. Home/End still adjust MAX by 5 MPH. An unchanged or lower sign does not overwrite a manual setting; zero, missing, paused or stale limits are ignored. Target changes are saved and shown immediately. This increase-only mode does not reduce MAX for lower posted limits.
|
||||
|
||||
MAX is a ceiling. Predicted path curvature reduces the effective cruise target using a 2 m/s² lateral acceleration budget. Covered path points up to 100 m also provide bend anticipation with a 1.5 m/s² braking budget; the planner never extrapolates beyond the model path. Speed recovers at up to 3 MPH per second after a bend. The saved MAX stays unchanged by curve caps. This is a simulator heuristic, not validated rollover prevention; path branch selection and lane keeping remain incomplete.
|
||||
|
||||
A supervised simulator controller using the existing Supercombo model, ATS telemetry, and analog vJoy or keyboard controls. F8 selects the camera for the chosen mode, centers the cabin with NumPad 5, and engages after ten usable road frames. Steering tracks the detected lane center at distance-indexed lookahead points. The calibrated road inset supports a limited steering test with manual speed; the separate bumper mode also supports cruise.
|
||||
|
||||
## Finish setup
|
||||
|
||||
1. Close ATS and double-click `install_plugin.bat`. Approve the Windows administrator prompt. The installer copies and verifies the bundled RenCloud v1.12.1 64-bit plugin; results go to `install_log.txt`.
|
||||
2. Restart ATS and enter the driving view. Start the engine, select a forward gear, and release the parking brake.
|
||||
3. For keyboard fallback, leave ATS configured for A/D and W/S. For smoother analog control, finish the vJoy setup below. The assistant sends no mouse movement.
|
||||
4. The **Tesla Semi FSD** desktop shortcut opens the calibrated inset steering test with CPU inference, vJoy and the original dashboard. Bring ATS to the foreground on a straight road with clear lane markings, drive at 10–15 MPH, then press **F8**. Control the pedals manually. Inset testing disengages above 20 MPH. `Run-Tesla-FSD-Passive.bat` opens observation without acquiring driving controls.
|
||||
5. F8 again, Escape, physical driving keys, or camera keys take over. Focus loss, paused/stale telemetry, unclear lanes, and actuator errors also release controls.
|
||||
|
||||
The HUD shows engagement-blocking reasons. Tab belongs to ATS. Lane-change shortcuts are disabled during initial lane-keeping validation. The HUD moves to a second monitor when available; on a single monitor keep it behind ATS while driving.
|
||||
|
||||
The original dashboard panel is still the default. It shows the actual 512x256 model input, lanes, predicted path, speed, gear, status, selected model, driving mode, model provider, and inference timing. `--no-hud` hides it for diagnostic tests. `--hud-mode cockpit_screen` selects the compact visualization; with the panel focused, M switches layouts and Q exits. C cycles driving modes and N cycles compatible registered models, only with fresh stationary telemetry, the parking brake set and F8 off. Focusing the panel while driving releases control because ATS loses focus. The ordinary inset launcher retains manual pedals; C cannot bypass its restriction to steering-only control.
|
||||
|
||||
## IQ Pilot feature integration
|
||||
|
||||
The comparison uses only the requested [IQ.Pilot beta-radarless-pq branch](https://gitlvb.teallvbs.xyz/IQ.Lvbs/IQ.Pilot/src/branch/beta-radarless-pq/), pinned to commit `821597d28fba40a531c3e2afa02fb0c0198a8d04`. Public source was read through its Gitea contents API; file revisions are preserved in the ignored `reference/iqpilot-beta-radarless-pq/source.json`. The ATS code implements these concepts independently. The reviewed branch maps Stock ACC to factory longitudinal control, IQ.Chill to IQ longitudinal with relaxed personality, and IQ.Pilot to end-to-end model longitudinal control. Its signal lane-change modes include direct and timed activation, brake cancellation, a consumed state, and optional blind-spot waiting. IQ.Dynamic exists in the newer separate local checkout, but is outside this branch comparison.
|
||||
|
||||
| Feature | Available here | Work before active use |
|
||||
| --- | --- | --- |
|
||||
| Driving modes | `--driving-mode manual`, `cruise`, or `chill`; Chill limits throttle/ramp and increases following distance. Neither cruise mode is model-driven IQ.Pilot. | Tune the remaining speed error and test bends/lead following. End-to-end mode needs a validated model trajectory and speed planner. |
|
||||
| Model selector | `--list-models`, `--model ID`, and parked panel N; every local entry has its own manifest, hash and decoder contract. The historical model and an experimental passive Pop v2 adapter are installed. | Validate Pop's camera, cadence and vehicle response before control. Its split vision/policy bundle has a separate runner and decoder; it cannot replace the historical ONNX directly. |
|
||||
| Laneless path | `--dry-run --path-preview` evaluates model geometry without acquiring vJoy. Pop's passive assessor also checks predicted road edges, uncertainty and temporal coverage. | Validate camera pose, live cadence, obstacle handling and closed-loop response. Hypothesis weight is not road confidence. |
|
||||
| Nudgeless turn signals | `--dry-run --signal-preview` reads actual SDK signal flags and issues one model-intent pulse per activation, with configurable delay and brake cancellation. This never commands a lane change. | Validate the model's maneuver response, adjacent-lane geometry and side traffic; add completion/abort states and trailer clearance. Nearby ATS vehicles can now be displayed, but blind-spot clearance logic is not validated. |
|
||||
|
||||
`Run-Tesla-FSD-Chill-Test.bat` opens a restricted 120-second, 15 MPH inset cruise test with the usual camera identity, telemetry, focus, takeover and watchdog checks. The desktop shortcut still opens manual-pedal lane keeping. Chill is an ATS speed controller inspired by the mode distinction; it is not the IQ.Pilot implementation or its complete driving stack.
|
||||
|
||||
`Run-Tesla-FSD-Feature-Preview.bat` opens passive path and signal evaluation with the original dashboard and paired input/output recording. You drive. The previews require `--dry-run` and cannot acquire vJoy or actuate the truck. Signals use active flags rather than flashing lamp states. The preview delay defaults to one second; `--signal-delay` accepts 0.05, 0.5, 1, 2 or 3 seconds. Preview cancellation does not establish that a neighboring lane is clear.
|
||||
|
||||
Assess a recording with `python -m tools.assess_path_recording diagnostics/RECORDING_DIRECTORY`. Existing moving calibration had usable path geometry in 253 of 266 frames, but a median 0.64 m offset from the detected lane center. The other 13 paths lacked usable forward extent. This is a geometry assessment, not validation of laneless driving; the saved frame review confirms that the path can be offset from lane center.
|
||||
|
||||
The implementation order is: clean camera input and comfortable speed control; paired passive path/signal recordings and model comparison; calibrated laneless tracking; then controlled turn-signal lane-change tests with explicit clearance and abort behavior. The current runner still uses CPU ONNX Runtime; this feature work does not enable ROCm.
|
||||
|
||||
## Cabin driving with a separate model camera
|
||||
|
||||
An experimental `--camera auxiliary` mode reads a dedicated 512x256 road inset while the main ATS view stays in the cabin. It uses [SCS custom multi-view rendering](https://eurotrucksimulator2.com/multimon_config.php), with cabin geometry disabled only in the inset. This is an additional rendered camera, not access to an invisible camera 6 feed. `Run-Tesla-FSD.bat` selects the calibrated inset steering test with CPU inference and opens the original dashboard. `Run-Tesla-FSD-Passive.bat` keeps observation available without driving commands. Running `python main.py` directly still defaults to the validated bumper mode with automatic provider selection.
|
||||
|
||||
Run `python -m vision.configure_auxiliary_camera` to generate a preview. Close ATS, then run it with `--apply` to back up `config.cfg` and any existing `multimon_config.sii` and install the layout. The initial camera offset is truck-dependent and needs live calibration. Restart ATS in cabin view (top-row 1), then run `python main.py --camera auxiliary --dry-run --record-calibration --inference-provider cpu`. The dashboard camera preview should show only the inset road image, with plausible lanes and stable confidence. Recording saves the exact input and matching live model outputs. Active auxiliary control requires a reviewed calibration matching the truck, layout, model, plugin and settings. Resolution/layout changes require recalibration. Physical steering and camera keys still take over. Mouse-look is permitted only in active inset mode with live camera correction; a short supervised road check passed.
|
||||
|
||||
On October 3 the inset was verified live at the top center, 32 pixels below the top of the 2560x1440 game screen. The original SCS layout followed cabin head movement. The installed ForwardCamera render integration compensates for that movement, and the Pinnacle calibration now permits restricted steering-only control. The original game configuration is preserved in `fsd-camera-backup-20261003-031258-083728` inside the ATS documents directory. Game notification overlays can obscure the inset because capture reads the rendered screen.
|
||||
|
||||
An independent truck-facing view requires a render integration that fixes the auxiliary camera to the truck while preserving the driver's camera. [SCS explains the main-camera dependency](https://forum.scssoft.com/viewtopic.php?p=375768). The inspected [ETS2LA capture plugin](https://github.com/ETS2LA/capture) captures already-rendered frames, and the [ETS2LA communication plugin](https://github.com/ETS2LA/plugin) exposes camera properties; neither documented interface creates the independent view.
|
||||
|
||||
A [ForwardCamera prototype](native/forward_camera/README.md) uses [SPF Framework v1.2.5](https://github.com/TrackAndTruckDevs/SPF-Framework/releases/tag/v1.2.5) to compensate for cabin head movement in the `road` inset. The direct per-monitor render hook retains truck rotation while removing head rotation. It requires exact loaded-code comparisons across five inspected ATS 1.61.2 functions, a signature/location check, and road rectangle/FOV checks. Version 0.2.3 also compensates for head translation using the existing read-only RenCloud telemetry mapping. All 117 parked look samples matched, with median/P95 feature shifts of zero pixels at detector precision. No different parked pose was held long enough for a settled result, and the user still reported very slight movement. Subsequent moving calibration found usable lanes in all 155 recorded look frames, with reviewed lane overlays following the paint. The original dashboard remains available. The installer backs up existing SPF files and preserves camera settings.
|
||||
|
||||
## GPS-guided driving
|
||||
|
||||
The target is a destination-to-destination simulator experience: the selected ATS GPS route guides lane selection, exits and turns; the road camera supplies local road/traffic observations; the controller applies steering and speed. This is a navigation-guided architecture. The existing historical Supercombo input contract has no GPS/navigation tensor, so GPS cannot be passed directly to that model without changing its interface or adding a planner.
|
||||
|
||||
The RenCloud reader now exposes SCS navigation distance (metres), ETA (seconds), speed limit (m/s), local map scale, and the truck's world position/rotation. The dashboard displays GPS distance and speed limit, and paired passive recordings preserve this metadata. These fields are observations; no driving behavior is changed by them. Invalid optional navigation metadata is marked unavailable without invalidating otherwise healthy steering telemetry.
|
||||
|
||||
Run `python -m tools.check_navigation` to inspect the live inputs without acquiring controls. The October 3 check found fresh ATS telemetry, 55.4 km remaining, 2324 seconds ETA, a 75 MPH reported limit and finite world pose. The independent `Local\\ETS2LARoute` feed was absent, matching the installed plugin inventory. Details are saved in `diagnostics/navigation-input-check.json`.
|
||||
|
||||
[ETS2LA's navigation reader](https://github.com/ETS2LA/ETS2LA/blob/main/ETS2LA.Game/SDK/Navigation.cs) documents a separate game-side feed of route node IDs with distances/times to the destination. Those IDs still require matching map geometry to produce turns, exits or an ego-relative path. The implemented read-only adapter opens only an existing route mapping, verifies snapshot consistency/format, and always marks it unsuitable for control. It does not create a mapping, open the ETS2LA input feed, or send steering commands.
|
||||
|
||||
The reviewed [route exporter](https://github.com/ETS2LA/plugin/blob/main/src/core.cpp) updates on a change in route node count and does not clear the previous route in its no-route branch. Its shared buffer has no heartbeat or route-generation ID. Identical node counts can therefore conceal reroutes; two matching reads do not establish freshness. Compatibility with this ATS 1.61 build also needs verification before installing or adapting a game-side exporter. A production bridge must publish its supported game/build and protocol version, heartbeat, route generation/hash, explicit route-active state, and bounded coordinate data. It must clear route guidance on cancellation, rerouting, pause, stale telemetry or map mismatch.
|
||||
|
||||
Next steps:
|
||||
|
||||
1. The first route connection is now implemented without a new plugin: `telemetry/gps_route_reader.py` reads the live GPS task through read-only process access. It requires the exact verified ATS executable SHA256 and compares both loaded GPS getters with that file before reading pointers. Route array bounds, repeated pointer/array/node snapshots and SDK distance/ETA agreement reject mismatched or changing data. Each snapshot re-reads all route points, including same-count reroutes. Pause, stale telemetry and zero GPS distance clear cached guidance immediately. This build-specific adapter will refuse an ATS update until reverified.
|
||||
2. Run `Run-Tesla-FSD-Navigation-Preview.bat` for the original dashboard with the model camera, GPS map and next route bend. Leave F8 off and drive manually; F8 cannot enable driving in this mode. Route nodes are graph points, not a lane-center steering path; bends are not classified as exits or intersections. The preview matches world position, heading and advisor progress, then records coordinates and paired road/model frames. The first live parked check read a 52-point route and matched the truck to its current segment with 2.85 world metres cross-track error, 0.02 advisor metres progress error and heading dot product 0.9999998. All eight live snapshots matched. Next, record a manual bend, exit and intersection; verify rerouting and cancellation in the game. Use `python -m tools.check_gps_route --duration 2 --render` for a route-only diagnostic without any controller.
|
||||
3. Add a navigation planner or a compatible model accepting route context. Keep route instructions, lane changes and intersection turns distinct; the current model's lane-change pulse is not a general navigation-turn command.
|
||||
4. Validate supervised highway exits, then turns/intersections, speed changes, traffic lights, yielding and trailer clearance. A GPS route alone does not resolve obstacles, right-of-way or stop conditions.
|
||||
|
||||
The first manual navigation drive recorded 732 moving samples across 40.57 seconds. Route matching succeeded in 695 (94.95%), progressing through segments 3–6 with a minimum heading dot product of 0.99908. Median graph cross-track error was 2.91 world metres (maximum 7.01); graph offsets are not lane-center errors. Two SDK/GPS disagreement episodes hid guidance for 1.05 and 1.10 seconds. The reader now retains its verified read-only handle after snapshot disagreements and retries after 50 ms instead of forcing a one-second reconnect; strict data checks remain unchanged. This recovery change passes regression checks but still needs a moving retest. Only 575 of the 732 moving model frames passed the existing lane checks, so this run does not validate automatic navigation steering. Evidence is `diagnostics/inset-cal-20261003-060527-828098/navigation-assessment.json`. Reproduce the assessment with `python -m tools.assess_navigation_recording <recording-directory>`.
|
||||
|
||||
A subsequent run used the ordinary steering launcher (`dry_run=False`, manual pedals), without GPS route snapshots. Its first engagement lasted 0.480 seconds before a lane-confidence release; its second lasted 14.053 seconds before the existing 20 MPH limit released steering. The saved confidence-drop road image was unobstructed, so this release cannot be attributed to a HUD popup. That run does not validate the requested GPS bend/exit/reroute check. Evidence is `diagnostics/steering-review-20261003-061208.json`; the two release folders preserve exact model inputs. Use the Navigation Preview launcher for the next GPS recording.
|
||||
|
||||
### Bounded GPS driving and road scene
|
||||
|
||||
`Run-Tesla-FSD-GPS-Driving-Test.bat` runs GPS-assisted camera steering and
|
||||
12 MPH Chill cruise for at most 120 seconds. F8 engages after the existing
|
||||
camera/telemetry checks; F8 or physical driving inputs release control. The
|
||||
ordinary `Run-Tesla-FSD.bat` still uses manual pedals and now shows/records GPS.
|
||||
The GPS graph constrains camera-supported guidance; it is not a lane-center
|
||||
path and does not establish right-of-way at exits or intersections.
|
||||
|
||||
The October 3 GPS trial recorded 777 engaged samples over 43.06 seconds, with
|
||||
all 777 matched to the route. Measured steering and throttle followed the
|
||||
commands. Control released when the gearbox entered neutral. The 12 MPH
|
||||
setting had a remaining speed error on an uphill section. The Chill speed
|
||||
loop now learns a bounded throttle offset to compensate for load, clearing
|
||||
it on reset, stale telemetry, lower targets, overspeed and following limits.
|
||||
Its existing throttle/brake caps remain unchanged; this adjustment needs a
|
||||
moving retest. Evidence: `diagnostics/navigation-drive-20261003-061834-419967`.
|
||||
|
||||
The road scene preserves all four historical model lane-line outputs with
|
||||
their individual probabilities. It displays only confident observations,
|
||||
with brighter ego boundaries and dimmer adjacent boundaries. Four possible
|
||||
lines do not prove four lanes, and uncertain road geometry is not filled in.
|
||||
In the live parked exit-split check, the model confirmed only one boundary;
|
||||
it cannot yet supply an accurate complete highway layout at that location.
|
||||
|
||||
Nearby vehicles now come from a separate, read-only ATS actor adapter. The
|
||||
reader requires the exact verified ATS 1.61.2 executable, compares the loaded
|
||||
traffic getter with that executable, validates bounded lists and repeated
|
||||
snapshots, and checks the player's position against SDK telemetry. It
|
||||
excludes the player's truck/trailer and reports measured vehicle positions,
|
||||
dimensions and headings ahead, beside and behind the truck. The live parked
|
||||
check verified vehicles queued behind the truck and on the opposite
|
||||
carriageway. A game update disables this source until it is verified again.
|
||||
|
||||
The dashboard keeps its original camera preview and GPS map. Its surround
|
||||
view shows actual loaded actors, with model-observed forward lane lines in
|
||||
the same metric view. Coverage is incomplete: no displayed vehicle is not
|
||||
proof of a clear lane. Traffic observations currently improve the display
|
||||
and recordings; they do not authorize lane changes or select a traffic-aware
|
||||
route. Lane selection needs verified lane geometry, tracked gaps and an
|
||||
abort-capable planner before it can control the truck.
|
||||
|
||||
A local read-only map cache now supplies lane counts independently of the
|
||||
camera model. Seven nearby map sectors were completely decoded in format 907;
|
||||
the nearby highway's `us_tmpl12` definition explicitly contains two lanes in
|
||||
the truck's travel direction. Both road endpoint IDs and coordinates matched
|
||||
the live GPS route. The current parked pose is just before that road, so the
|
||||
panel labels this **nearby map** information and does not claim lane membership.
|
||||
The dashed green curve is a sampled road reference; lane widths and template
|
||||
boundaries remain unverified. It is never used as a steering target.
|
||||
|
||||
`telemetry/road_geometry.py` verifies the game executable, archive hashes,
|
||||
loaded version and active mod order; it rejects stale/paused SDK poses,
|
||||
ambiguous matches and locations outside the local cache. The active Tesla mod
|
||||
has no map or lane-definition overrides. The cache and extraction evidence
|
||||
are under `diagnostics/map-cache`; rebuild it after game/map changes. Road
|
||||
definitions are matched read-only, and no game files or DLLs were changed.
|
||||
The measured reader startup was 0.76 seconds and median snapshot time 2.47 ms.
|
||||
Road-template PMD/PMG lane semantics still need a supported decoder before the
|
||||
map can supply physically accurate lane boundaries.
|
||||
|
||||
The original camera, GPS map
|
||||
and both dashboard layouts are retained. `Run-Tesla-FSD-Passive.bat` opens the
|
||||
combined scene with driving disabled and paired recording enabled. Use
|
||||
`python -m tools.render_recorded_scene RECORDING_DIRECTORY --sequence N` to
|
||||
review the exact recorded camera, model, traffic and map scene offline; the
|
||||
export marks unavailable observations and never replays controls.
|
||||
|
||||
The road-split view now includes verified roads attached to nearby junction
|
||||
prefabs, even when there is no verified current-road match inside the junction.
|
||||
Each arm stays separate; the panel does not draw a guessed path across the
|
||||
unknown interior. Fresh GPS node pairs that agree with cached map coordinates
|
||||
highlight matching road arms in blue. On the 2,195-frame October 3 recorded
|
||||
drive, all 302 formerly blank map frames gained junction approach context,
|
||||
with no change to the original road-match results.
|
||||
|
||||
Eight nearby freeway and town prefab types now have decoded PPD v25 AI lane
|
||||
connections from the installed game assets. All 75 mounted archives were
|
||||
checked for overrides. World placement validates every prefab attachment,
|
||||
including height; invalid, stale or unsupported geometry is hidden. Purple
|
||||
curves show authored traffic paths, with brighter GPS-matched connections.
|
||||
These are sampled AI lane centres, not decoded painted road boundaries;
|
||||
the game's exact interpolation remains unverified. The local cache covers
|
||||
these prefabs and is not a complete map of ATS.
|
||||
|
||||
`control/lane_choice_preview.py` reports stable corridors between adjacent
|
||||
confident model boundaries and forward tracked-vehicle footprint overlaps.
|
||||
It qualifies road height, preserves straddling overlaps, and marks incomplete
|
||||
side/rear coverage. It separately exposes authored input-lane indices matching
|
||||
GPS node connections. It does not identify a model corridor with a map input
|
||||
lane, recommend a lane, or permit automatic lane changes.
|
||||
|
||||
The stable inset retains a driver-seat anchor: its nominal origin is about
|
||||
0.55 m left and 4.01 m forward of the truck origin. `vision/scene_frame.py`
|
||||
rebases independent display copies into the native truck frame using SDK
|
||||
rest positions and an explicitly captured seat baseline. Controller inputs
|
||||
and original recorded model arrays retain their existing calibration.
|
||||
`diagnostics/scene-origin.json` pins the truck, model, plugin and settings;
|
||||
changed rest positions or unsupported pose values reject alignment. Cabin
|
||||
heading/pitch/roll and truck body pitch/roll are applied to the camera anchor
|
||||
and copied geometry using the SCS SDK's documented rotation composition.
|
||||
Native map/traffic coordinates remain world-up with truck heading removed.
|
||||
Rotated lane polylines are resampled only within their common observed forward
|
||||
coverage, preserving the model's nonuniform spacing without extrapolation.
|
||||
The display envelope is limited to 5 degrees of cabin rotation and 15 degrees
|
||||
of body tilt; these limits do not authorize steering. The panel labels the
|
||||
result as an SDK pose estimate: final render extrinsics have
|
||||
not been measured. Missing alignment disables cross-frame traffic overlap
|
||||
assessment and native overlays on the model perspective.
|
||||
|
||||
The town cache adds the exact installed definitions for `2k046`, `2o01g`,
|
||||
`2k00w`, `2o01h`, `2o083` and `us_12`, alongside the two freeway definitions.
|
||||
Its signalized intersection uses version-25 semaphore records with the extra
|
||||
16-byte tail retained as unknown metadata; the preview makes no traffic-light
|
||||
or permitted-turn claims. All seven prefab instances observed in the manual
|
||||
test pass attachment validation. Other pitched or incomplete instances still
|
||||
fail, and their rejection reasons are recorded. Authored raw lane slot numbers
|
||||
are preserved independently from filtered entry ordinals. Asset rebuilding
|
||||
verifies installed token bindings and archive precedence before atomic update.
|
||||
|
||||
Display-only traffic tracking reprojects the exact observed world positions
|
||||
into the current truck view, including cached measurements. At least three
|
||||
distinct observations are required for measured speed labels and relative
|
||||
motion arrows; repeated cached samples do not become new measurements.
|
||||
Unavailable/stale/paused samples hide actors immediately. Identity changes,
|
||||
teleports, clock resets and implausible motion reset the track. The same drive
|
||||
retained 2,111 fresh traffic samples and supplied measured motion in 1,591
|
||||
frames. Tracking does not extrapolate positions or establish lane clearance.
|
||||
|
||||
`python -m tools.replay_scene_context RECORDING_DIRECTORY --start N --end M`
|
||||
creates a separate offline derivative with recomputed map/traffic context,
|
||||
unchanged model observations and copied exact camera frames. It never accesses
|
||||
the live game or replays controls; the export explicitly labels recomputation.
|
||||
Evidence: `diagnostics/road-scene-context-replay-20261003-verified/`.
|
||||
Use `--scene-origin diagnostics/scene-origin.json` only when explicitly
|
||||
replaying a matching historical camera configuration. Old recordings lack
|
||||
SDK rest vectors and cabin rotation; the derivative records which values
|
||||
were seeded from that nominal proof and does not describe them as measured
|
||||
at the historical frame. Camera images and original model arrays stay intact.
|
||||
|
||||
The earlier aligned replay of 2,195 frames includes authored junction paths in 1,134,
|
||||
stable observed corridors in 2,057, and forward footprint overlap in 935.
|
||||
GPS-matched authored input-lane indices are available in 859 frames. All
|
||||
historical frames are explicitly marked as seeded nominal pose estimates;
|
||||
no driving controls were replayed. Evidence:
|
||||
`diagnostics/junction-path-aligned-replay-20261003/`.
|
||||
|
||||
The latest manual bend/junction replay covers sequences 3301–4021 (721 frames).
|
||||
Recorded SDK cabin/body pose now permits display alignment in all 721 frames,
|
||||
recovering all 134 moving-frame rotation dropouts. Expanded town assets provide
|
||||
authored paths in 713 frames (previously 152) and GPS-matched input-lane indices
|
||||
in 699 (previously zero). Native traffic remains available in 674 frames, with
|
||||
measured motion in 434. The preservation audit checks all original model,
|
||||
telemetry and control fields, 8,247 actor world measurements and 53 exact camera
|
||||
image hashes. No pose was seeded, no controls were replayed, and no lane
|
||||
recommendation or clearance was inferred. Evidence:
|
||||
`diagnostics/manual-junction-fixed-replay-20261003-verified/replay-audit.json`.
|
||||
These are passive scene improvements; final render extrinsics and painted lane
|
||||
identity remain unverified. That stage passed 193 regression tests.
|
||||
|
||||
The follow-up live trial is preserved in
|
||||
`diagnostics/town-junction-live-test-20261003/`. Display alignment stayed
|
||||
available in all 1,239 moving frames, but the driving model was usable in only
|
||||
589. ATS fatigue notifications obscured the input, including one frame that
|
||||
still passed the old model-confidence checks. The new auxiliary-camera guard
|
||||
checks the exact raw frame for the observed anchored notification panel before
|
||||
inference. A detection skips inference, resets temporal history, cancels pending
|
||||
or engaged controls, and saves the raw frame with previous model arrays marked
|
||||
stale. The panel and saved overlays hide that stale geometry. This detector
|
||||
covers the tested ATS notification layout; absence does not establish a clear
|
||||
road or detect every possible obstruction. Exact hashed camera fixtures are
|
||||
included under `tests/fixtures/camera-obstruction/`.
|
||||
|
||||
The same trial exposed a GPS rejection when the first stored route node was
|
||||
ahead of the truck. The reader now validates a bounded approach using SDK pose,
|
||||
height, heading, local distance scale and remaining-distance consistency while
|
||||
preserving exact native nodes and IDs. That connector is an estimated display
|
||||
schematic, never a road or lane center; the driving planner rejects it.
|
||||
Endpoint and residual diagnostics are retained on rejection, and a large GPS
|
||||
progress jump invalidates the cached route immediately. A qualified comparison
|
||||
using a later accepted node array supports 382 of 384 settled poses; it does
|
||||
not prove that array existed at the historical rejected frame. See
|
||||
`diagnostics/town-junction-lead-in-candidate-20261003.json`.
|
||||
|
||||
The passive route/corridor check compares directed GPS/authored paths with
|
||||
fresh unobstructed scene-aligned model boundaries over measured 5–30 metre
|
||||
coverage. It rejects missing, folded, disjoint, stale or ambiguous evidence,
|
||||
and labels a unique candidate as an estimate. It never recommends a lane,
|
||||
grants clearance or controls the truck. Nearby junctions explicitly require
|
||||
manual handling because STOP requirements, signals and right-of-way remain
|
||||
unverified. The earlier trial produced no supported route/corridor match.
|
||||
Active steering calibration remains specific to the Pinnacle. The Peterbilt
|
||||
579 now has a separate nominal display origin in
|
||||
`diagnostics/scene-origin-579.json`: 30 fresh stationary SDK samples and four
|
||||
fresh camera-hook records, with the model, plugin and settings identities
|
||||
checked before and after capture. It aligns display copies using the 579's
|
||||
own cabin/head rest configuration. The original Pinnacle proof and active
|
||||
calibration remain unchanged; the 579 proof cannot authorize control or claim
|
||||
measured final render extrinsics. The live panel selects the matching truck's
|
||||
display proof, and offline rendering preserves that selection per recorded row.
|
||||
Capture again while parked with
|
||||
`python tools/snapshot_scene_origin.py --truck 579 --output diagnostics/scene-origin-579.json`.
|
||||
The tool refuses paused, stale, moving, mismatched or unstable measurements.
|
||||
The 579 follow-up passed 237 tests, and the live parked panel confirmed display
|
||||
alignment with controls off. See `diagnostics/scene-579-live-check-20261003.json`.
|
||||
The first lock-measurement window contained no head movements, so full-look
|
||||
stability and moving calibration remain pending.
|
||||
|
||||
The subsequent 579 sweep revealed a left-window failure: camera frames show
|
||||
cabin/grille geometry starting around 112 degrees of left yaw in the reviewed
|
||||
examples, while right-pan frames remain forward. Some grille frames still
|
||||
passed model confidence. `diagnostics/579-left-pan-20261003.json` preserves the
|
||||
paired evidence. Until the native correction is validated, the auxiliary input
|
||||
guard rejects the 579 above 80 degrees left yaw or with more than 5 cm left head
|
||||
displacement. Position also catches the left-window branch across yaw wrap.
|
||||
The runtime rereads head telemetry after capture, skips inference, clears
|
||||
history, marks old geometry stale and releases pending/engaged controls.
|
||||
This is a restricted pose envelope, not general grille/traffic recognition.
|
||||
|
||||
ForwardCamera 0.2.4 adds a diagnostic-only 60-second render pose trace at at most
|
||||
10 Hz. It records the actual composition quaternion, SPF/SDK head angles,
|
||||
interior-outside state, translation and offsets; camera correction is unchanged.
|
||||
The minute starts only with fresh, unpaused, stationary SDK telemetry and the
|
||||
parking brake set; menus cannot consume the recording window.
|
||||
`python tools/prepare_camera_trace.py` previews the hashed diagnostic installation.
|
||||
`--apply` requires ATS closed, backs up the DLL/settings/manifest, preserves the
|
||||
historical proof files and explicitly invalidates active camera calibration.
|
||||
`python tools/analyze_render_pose.py <ForwardCamera.log> --recording <recording-directory>`
|
||||
compares the recorded angle sources and offset composition using fresh parked
|
||||
telemetry. All 259 Python checks and native diagnostic/build checks pass; a new trace and
|
||||
camera correction are still required before full-left stability can be claimed.
|
||||
The installed diagnostic's first minute missed the manual sweep. A parked SPF
|
||||
Framework reload rearmed it without restarting ATS. The second trace captured
|
||||
the sweep: corrected orientation drift stayed below 0.002425 degrees, yet the
|
||||
held-left raw image still showed the grille while SPF/SDK angles agreed.
|
||||
This narrows investigation to camera position/visibility; it does not verify
|
||||
the render origin or authorize control. See
|
||||
`diagnostics/579-rearmed-render-sweep-audit-20261003.json`. All 129 guarded rows
|
||||
skipped inference and marked old geometry stale, with no driving commands.
|
||||
The analyzer retains only the latest SDK timestamp epoch after a reload; the
|
||||
camera `outside` flag is descriptive and cannot disqualify a centered baseline
|
||||
because it is also true in the observed forward view.
|
||||
This follow-up passed 221 regression tests. The restarted passive panel was
|
||||
checked with the 579 parked: fresh inference and GPS preview were available,
|
||||
controls remained off, and scene alignment correctly rejected the truck's
|
||||
unverified calibration. See
|
||||
`diagnostics/road-scene-guarded-live-check-20261003.json`.
|
||||
|
||||
## Analog vJoy setup
|
||||
|
||||
Use the official [signed vJoy release](https://github.com/BrunnerInnovation/vJoy/releases) (v2.2.2.0 was checked). Installation requires the Windows administrator prompt and may require a restart. No virtual-controller driver is bundled or installed automatically.
|
||||
|
||||
1. In Configure vJoy, enable device 1 with **X, Y, and Z** axes. Close other vJoy feeders so the assistant can acquire it.
|
||||
2. In ATS Controls, select keyboard plus vJoy, using the steering-wheel control type. Bind **X to steering**, **Y to throttle**, and **Z to brake**, with separate pedal axes in **centered mode**, using center-to-maximum for pedal travel. To move an axis during binding, run `python -m control.bind_vjoy steering` (or `throttle` / `brake`), then return to ATS and select that axis within five seconds. The helper stops after twelve seconds and refuses to operate while ATS is unpaused. Use linear steering (nonlinearity zero), minimal deadzone, and normal steering direction: decreasing X turns left. Pedal center must mean released and maximum must mean fully pressed; use normal (uninverted) centered pedal mode.
|
||||
3. Verify the ATS input bars before driving: X midpoint centers the wheel, Y/Z midpoint release the pedals. The parked telemetry check passed on this installation on October 3, 2026.
|
||||
4. Launch with `python main.py --backend vjoy --lane-only --speed 15` for the first lane test. F8/Escape and physical steering/camera keys take over. Manual pedal keys are allowed in lane-only mode.
|
||||
5. Once direction and lane tracking are verified, use `python main.py --backend vjoy --speed 15` to test cruise and braking.
|
||||
|
||||
The desktop steering launcher explicitly uses the validated vJoy device. The direct CLI default `--backend auto` selects vJoy when its matching DLL is installed, otherwise keyboard feedback. An installed but disabled, unconfigured, or busy vJoy device produces an error rather than silently changing backends. `--backend keyboard` explicitly selects the fallback. Dry run and diagnose never acquire a vJoy device or change its axes.
|
||||
|
||||
If menu binding is inconvenient, `python -m control.configure_vjoy "PROFILE_DIRECTORY"` previews the bindings using vJoy's exact device identification from `game.log.txt`. Close ATS and add `--apply` to save a timestamped backup and set the three axes, centered pedals, linear steering, and zero deadzones. This uses [SCS's documented input format](https://modding.scssoft.com/wiki/Documentation/Engine/Advanced_input_configuration); verify the resulting input bars when restarting ATS.
|
||||
|
||||
vJoy sends a steady wheel position and independent pedal values instead of pulses. Disengagement, focus loss, stale commands, and shutdown center steering and release both pedals. Physical keyboard takeover is supported; physical gamepad/wheel takeover is not yet monitored.
|
||||
|
||||
## Validation and diagnostics
|
||||
|
||||
```powershell
|
||||
python -m unittest discover -s tests -v
|
||||
python main.py --diagnose
|
||||
python main.py --dry-run --no-hud --duration 30
|
||||
python main.py --speed 15
|
||||
python main.py --lane-only
|
||||
python main.py --backend vjoy --lane-only --speed 15
|
||||
python -m control.verify_vjoy
|
||||
```
|
||||
|
||||
- Diagnose reports game/provider/telemetry health without injecting controls.
|
||||
- Dry run checks readiness and logs intended controls and perception measurements without applying them. Manual pedal keys are allowed during passive tests.
|
||||
- Lane-only mode allows manual throttle/brake; steering/camera controls still take over.
|
||||
- Speed accepts 5–55 MPH (default 15). Runtime logs go to `diagnostics/session.log`.
|
||||
- The actuator watchdog releases analog inputs after a 500 ms command stall (keyboard: 250 ms); focus loss releases immediately. Game state is refreshed after inference before applying controls.
|
||||
- vJoy sends direct analog positions. The keyboard fallback uses pedal pulse modulation and measured steering feedback.
|
||||
- The vJoy input check requires the driving view, fresh telemetry, a stationary truck, parking brake, and either neutral gear or the engine off. In simple automatic mode, use E to turn the engine off for this check. It sends brief 20% steering/pedal commands, compares ATS's reported user inputs and camera orientation, verifies release after shutdown, and saves `diagnostics/vjoy-input-check.json`. Every exit centers steering and releases pedals. A passing parked input check precedes lane-keeping tests.
|
||||
|
||||
## Current validation
|
||||
|
||||
76 regression tests passed, including capture isolation, calibration recording, live camera health, independent-camera readiness, engagement confidence, comfort cruise, model pins, parked setting changes, passive path/signal previews and read-only GPS route geometry. GPS tests cover same-count route changes, torn snapshots, stale/paused/cancelled routes, SDK mismatch, recovery from a GPS update disagreement, wrong builds, pose/heading matching and left/right bends. The installed telemetry and vJoy device have been verified live. The parked input check measured left/right steering at +/-0.20, independent throttle/brake at 0.20, unchanged camera orientation, and zero controls after shutdown. Centered pedals also removed the previous idle 50% throttle/brake.
|
||||
|
||||
The initial October 3 passive inset drive recorded 298 telemetry samples and 50 model-camera
|
||||
images. Of 52 moving one-second model reports, 50 had usable lane geometry; those
|
||||
reports had median left/right confidence of 0.96/0.93 and lane widths of 3.60–4.37 m.
|
||||
The final two low-confidence reports coincided with pulling onto the shoulder,
|
||||
confirmed by saved images. Brief confidence drops also occurred between reports,
|
||||
so these counts are not a per-frame pass rate. Head rotation stayed constant
|
||||
during this drive; moving cabin looks and live projection alignment remain to be
|
||||
checked in that initial drive. Evidence is in
|
||||
`diagnostics/manual-inset-calibration/summary.json`. This run used ONNX Runtime
|
||||
DirectML; the current Python runtime exposes DirectML and CPU providers only.
|
||||
|
||||
The subsequent live calibration saved the actual model output paired with each
|
||||
input frame. Of 266 moving frames, 253 had usable lanes; all 155 frames during
|
||||
cabin looks had usable lanes, with median left/right confidence of 0.97/0.96.
|
||||
Reviewed overlays align with lane paint. Lane z already contains camera-relative
|
||||
height in the historical decoder; adding another 1.22 m produced an incorrect
|
||||
review overlay, which was corrected against the original UI source. The reviewed
|
||||
evidence is `diagnostics/inset-cal-20261003-044742-900055/summary.json`.
|
||||
The inset is now calibrated only for a limited `--lane-only` test with manual
|
||||
speed. Active startup checks the model, truck, plugin and settings identity;
|
||||
missing, stale, or stopped render/translation correction blocks or disengages
|
||||
control. Speed above 20 MPH also disengages the inset test. The default desktop
|
||||
launcher now opens the limited steering test. With CPU inference, an active inset road test stayed
|
||||
engaged for 21.054 seconds at sampled speeds of 9.4–16.9 MPH. It applied only
|
||||
small steering corrections while the user controlled speed. Manual takeover
|
||||
released control; fresh parked telemetry then showed zero steering and pedals.
|
||||
Evidence is `diagnostics/inset-steering-20261003-045631.json`. This validates a
|
||||
short, mostly straight centered-view test. A later attempt disengaged after
|
||||
0.214 seconds on a confidence dip before active cabin looks could be checked.
|
||||
The next run stayed engaged for 25.029 seconds during mouse-look, including
|
||||
sampled yaw from -80.3 to +59.1 degrees, before releasing on a lane-confidence
|
||||
drop. Another episode released at the 20 MPH speed limit. Fresh parked SDK
|
||||
telemetry showed zero steering, throttle and brake after test shutdown. Evidence:
|
||||
`diagnostics/inset-steering-20261003-050109.json`. These are short supervised
|
||||
tests; bends, intersections and general lane-change behavior remain unvalidated.
|
||||
On automatic inset release after successful inference, the runtime saves the exact model input,
|
||||
matching live outputs, input age and release telemetry under `inset-release-*`
|
||||
after releasing controls. This diagnostic has now been exercised by multiple live releases.
|
||||
|
||||
Saved release images exposed ATS notifications over the road inset: first a fatigue warning, then "Kingman discovered." Fatigue was disabled in the backed-up Ger profile, but that did not remove discovery notifications. Manually pressing F3 hid the widgets for the next test. Keep widgets hidden while using screen capture; clipping out a popup cannot recover the road it covers. Longer-term capture before the game's UI would remove this dependency.
|
||||
|
||||
The runtime permits at most 150 ms of marginal lane confidence (both scores at least 0.30), holding the last steering and releasing pedals. Holding frames do not renew the deadline. Geometry faults, lower scores, camera faults and other readiness failures still release immediately. Live evidence caught a 46 ms dip that recovered, followed by release when a fatigue popup drove confidence lower.
|
||||
|
||||
After hiding widgets and adding predictive, ramped comfort braking, the restricted Chill test stayed engaged for 67.287 seconds. The 15-to-8 MPH target change used at most 0.05 brake in one-second control reports, tapering to zero before reaching the target; sampled speed settled around 7 MPH (minimum 6.8). The previous attempt used 0.23 brake and sampled 5.6 MPH before a discovery popup forced release. The new run released when the truck entered neutral. Fresh parked telemetry after shutdown showed zero steering/throttle/brake. Evidence is `diagnostics/inset-cruise-20261003-052254.json` and its matching log. This validates a short straight-road response with a remaining speed error; ordinary inset cruise remains restricted to the bounded test launcher.
|
||||
|
||||
Use `--inference-provider cpu` on this installation to avoid GPU contention with
|
||||
ATS. In a foreground-game benchmark, CPU inference took a median 6.60 ms and a
|
||||
maximum 7.29 ms; DirectML took a median 2.18 ms but spiked to 501.23 ms while
|
||||
another DirectML session was also running. The first CPU road test's one-second
|
||||
control reports showed 6–7 ms inference. Three same-input recurrent steps agreed
|
||||
between providers within 0.000367 maximum absolute output difference. The model
|
||||
has not been changed or connected to ROCm. `auto` remains the direct CLI default,
|
||||
and `--inference-provider directml` explicitly requires DirectML.
|
||||
|
||||
For the corrected inset, F8 preserves model history only if the most recent
|
||||
inference is less than 250 ms old. Other camera modes and stale history reset
|
||||
as before. Inset preflight requires ten consecutive usable frames with both
|
||||
lane confidences at least 0.55; active release retains its 0.35 threshold.
|
||||
|
||||
The initial cabin road test disengaged on implausible lane geometry. Its crop did not match the historical MED model projection. A corrected bumper-camera crop passed all 30 sampled frames with about 99% lane confidence and 3.29 m lane width. This crop was checked at 2560x1440; other camera/FOV setups need validation. `--camera cabin` retains the experimental cabin mode. The forward bumper view is the validated default.
|
||||
|
||||
Live validation on October 3, 2026:
|
||||
|
||||
- In the earlier bumper-camera test, steering-only control remained engaged for about 40 seconds through a bend at roughly 20–23 MPH, with measured wheel input following the command.
|
||||
- Combined lane keeping and cruise remained engaged for about 47 seconds. It accelerated from 1.6 to 14.0 MPH toward a 15 MPH setting, tapering measured throttle from 0.45 to about 0.08 and coasting near the set-speed deadband.
|
||||
- F8 disengagement returned measured steering/throttle/brake to zero. Camera telemetry stayed centered throughout.
|
||||
- Both pedals passed the parked 20% input check, including release after feeder shutdown. The moving braking check engaged at 12.3 MPH and reduced the cruise setting from 15 to 8 MPH. It commanded 0.29 brake, slowed to 7.1 MPH by the next one-second log sample, then resumed light throttle after dipping to 6.4 MPH. This verifies braking response; the speed loop still needs tuning for smoother set-speed changes.
|
||||
- The braking diagnostic exited normally after its timed run. Fresh SDK telemetry then reported zero steering, throttle, and brake inputs, with unchanged centered camera orientation.
|
||||
- Focus/stalled-command release and stale/paused SDK rejection are covered by regression tests. DirectML frame spikes caused false 250 ms analog timeouts; the analog deadline is now 500 ms, with game state refreshed after inference.
|
||||
|
||||
Clearly marked roads are required; intersections and lane changes are outside this first milestone. This is a custom Supercombo simulator controller, not the full openpilot stack.
|
||||
|
||||
## Contracts and sources
|
||||
|
||||
Pop Model v2 is installed as an experimental, passive option (`--model pop-v2
|
||||
--dry-run --path-preview`). Both original split ONNX files are SHA-256 pinned;
|
||||
the March 24, 2026 catalog entry resolves to commaai/openpilot revision
|
||||
`62bf6fb072880905a4c490f0f4f4a6b3c23346ec`. It uses 200 ms image pairs and 25
|
||||
feature samples over 4.8 seconds, with a separate wide camera input. Its unary
|
||||
trajectory has no plan-selection confidence. This Windows runner uses ONNX
|
||||
Runtime CPU or DirectML; it is not ROCm.
|
||||
|
||||
The complete 33x15 motion plan is now decoded into position, three-axis
|
||||
velocity, acceleration, orientation and orientation rate, with the pinned
|
||||
quadratic time grid. `control/pop_model_actions.py` extracts curvature from
|
||||
planned yaw and initial yaw rate, and acceleration/stop intent from planned
|
||||
forward speed and acceleration using the
|
||||
[pinned upstream action formulas](https://github.com/commaai/openpilot/blob/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/controls/lib/drive_helpers.py).
|
||||
It retains upstream 0.05-second smoothing steps and 0.3-second longitudinal
|
||||
smoothing. The default ATS lateral and longitudinal delays are each 0.2 seconds
|
||||
and are explicitly **unvalidated**. Missing complete modern outputs are marked
|
||||
unavailable; older recordings cannot supply acceleration or stop intent from
|
||||
position alone. These actions remain previews and never command pedals.
|
||||
|
||||
The current 2560x1440 layout keeps the road inset at left 2016/top 32.
|
||||
`Install-Pop-Camera-Rectification.bat` installs the native asymmetric SBIG
|
||||
profile using ForwardCamera 0.2.6, native pitch zero, equal 58.727464-degree
|
||||
full-frustum FOVs and a bottom-origin subrect at y=0.296484375, height=0.5.
|
||||
This uses [SCS's documented frustum cropping](https://modding.scssoft.com/wiki/Documentation/Engine/Multi_monitor_configuration)
|
||||
to target SBIG intrinsics fx=fy=455, cx=256, cy=151.8. The narrow MED input is
|
||||
derived with nearest-neighbor sampling. The camera XYZ offset and cabin view
|
||||
are preserved. The earlier MED/top-right and pitched SBIG installers remain
|
||||
historical profiles and are not interchangeable with the current one.
|
||||
|
||||
The asymmetric installer was applied with backup
|
||||
`diagnostics/inset-top-right-backup-20261003-125918-777899`. It re-prepares and
|
||||
checks exact current hashes while ATS and the runtime are closed, uses
|
||||
transactional backup/rollback, and requests elevation only if ordinary writes
|
||||
are denied. Preparation alone leaves installed files unchanged. Prior control
|
||||
and nominal-origin proofs are invalidated. Native FOV/subrect readback was
|
||||
observed after restart, but final rendered physical pose and control calibration
|
||||
remain unverified. Inset placement cannot guarantee every game overlay stays
|
||||
outside the camera.
|
||||
|
||||
`Run-Pop-v2-Preview.bat` keeps driving controls off and records both real camera
|
||||
streams for two minutes after the truck starts moving, at up to 20 saved frames
|
||||
per second. It waits indefinitely with sparse parked evidence until forward
|
||||
motion is observed. Actual timestamps
|
||||
are retained; missing frames are not synthesized. The earlier 67-frame
|
||||
comparison in `diagnostics/pop-v2-cold-frame-comparison-20261003.json` uses
|
||||
independent cold inference and a duplicated narrow input. It cannot establish
|
||||
better road performance or authorize laneless control. The default driving
|
||||
launcher still selects the original model.
|
||||
|
||||
Pop evidence recording now uses a bounded background writer with eight queued
|
||||
jobs. A full queue drops evidence instead of blocking inference; attempted
|
||||
sequence gaps and drop ranges are explicit. Shutdown drains accepted jobs and
|
||||
records final counts, flush state and any writer error in `writer-status.json`
|
||||
and `writer-events.jsonl`. A recording is complete only when final status
|
||||
confirms full flush, zero drops and no writer error. Rows now retain the full
|
||||
modern motion plan, model actions, trajectory assessment and actual context
|
||||
coverage. Recorded drops are evidence gaps, not interpolated camera frames.
|
||||
|
||||
The October 3 Pop moving preview captured 1,019 moving frames over about 87
|
||||
seconds at 2.2–24.7 MPH. Of these, 933 passed the basic trajectory geometry
|
||||
checks; 47 exceeded the lateral bound and 39 had nonmonotonic forward geometry.
|
||||
These checks do not establish road safety or confidence. The run had a capture
|
||||
gap and a median cadence near 13 Hz, below the expected 20 Hz. Controls remained
|
||||
off throughout; the camera/model control calibration remains unvalidated.
|
||||
See `diagnostics/pop-v2-wide-moving-drive-audit-20261003.json` for paired evidence.
|
||||
|
||||
Auxiliary runtime capture now reads the exact 512x256 inset directly after
|
||||
checking the ATS client resolution and rectangle, instead of copying the entire
|
||||
2560x1440 client. Full-client capture remains available for diagnostic callers.
|
||||
Pixel equality, window offsets, changed resolution, and unavailable camera
|
||||
rejection are tested. A ten-frame parked profile of the installed asymmetric
|
||||
view measured median capture 15.55 ms and inference 20.73 ms in
|
||||
`diagnostics/pop-v2-rectified-preview-performance-20261003.json`. It excludes
|
||||
actual display/event-pump and disk writer costs, and does not establish moving
|
||||
performance or upstream 20 Hz cadence.
|
||||
The passive Pop panel redraws at 5 Hz while its input events are handled with
|
||||
nonblocking `pollKey` every loop and model capture targets 20 Hz. Actual inference timestamps and context
|
||||
coverage remain authoritative; the panel's loop FPS is not a cadence proof.
|
||||
|
||||
Pop path preview now uses `control/pop_trajectory.py` rather than the unfiltered
|
||||
trajectory steering calculation. It assesses only the ascending near-path
|
||||
prefix covering the steering horizon, checks predicted path and road-edge
|
||||
uncertainty, requires actual complete temporal context and distinct fresh
|
||||
frames, and warms stable observations before producing capped, rate-limited
|
||||
steering. Painted lane probabilities are not an admission requirement. Missing
|
||||
or uncertain evidence resets tracking; no previous command is held through it.
|
||||
The current preview implementation uses the modern yaw-derived model action
|
||||
for curvature after these admission checks. Geometric point-tracking remains available for
|
||||
explicit historical replay. Curve-speed advice and desired acceleration/stop
|
||||
intent are advisory only and do not command the pedals.
|
||||
|
||||
The existing Pop preview launcher records paired decisions and the full motion
|
||||
plan. The dashboard displays readiness, steering, acceleration/stop previews
|
||||
and path uncertainty. Every controller decision explicitly keeps
|
||||
`control_eligible=false` and `controls_applied=false`; active Pop invocation
|
||||
continues to be rejected before model/controller acquisition.
|
||||
|
||||
`Run-Pop-v2-Steering-Trial.bat` is a separate supervised simulator experiment:
|
||||
three distinct fresh parked-neutral snapshots arm the launcher, then one user
|
||||
F8 press can request at most 15 seconds of steering at 24–28 MPH (target
|
||||
25–27 MPH) with manual pedals. An unready F8 press shows its refusal reason
|
||||
and leaves the panel in standby without acquiring controls or consuming the
|
||||
single admitted attempt; a later attempt requires another human F8 press.
|
||||
Standby expires after five minutes. It uses the pinned asymmetric 579
|
||||
camera. Read-only vJoy capability queries are warmed before model history
|
||||
starts; the retained DLL is revalidated and acquired only after a ready human
|
||||
F8 press. It uses real paired temporal coverage, modern yaw actions and the
|
||||
existing uncertainty/road-envelope checks. Edge uncertainty must be at most
|
||||
1.5m to engage; only this active experiment allows a continuation band up to
|
||||
1.75m, while every frame still passes the unchanged uncertainty-adjusted
|
||||
corridor and other quality checks. The descriptive local steering gain is
|
||||
0.1254; requests outside normalized steering [-0.05, +0.03] (right/left)
|
||||
are rejected, and output changes are limited
|
||||
to 0.1 axis units/s. F8, Escape, manual steering, focus loss or any failed active
|
||||
guard ends the attempt and releases vJoy ownership. Records distinguish queued
|
||||
commands, successful worker writes and independent SDK observations;
|
||||
`trial-status.json` records final release even when the last image row was
|
||||
active. After release, the panel stays open with the stop reason and an explicit
|
||||
frozen-snapshot label; controls and recording are already closed. Escape or the
|
||||
window's X closes it. This launcher does not grant physical camera calibration, validated
|
||||
model delays, production eligibility, pedal control or junction competence.
|
||||
`python tools/run_pop_steering_trial.py --diagnose --no-hud` checks assets and
|
||||
parked startup without acquiring controls or creating a keyboard hook.
|
||||
|
||||
Historical geometric replay of the captured drive accepted only 76/1,019 moving
|
||||
frames, with a longest accepted interval of 1.53 seconds. Most denials were predicted path or
|
||||
road-edge uncertainty. This is insufficient for sustained driving; thresholds
|
||||
have not been relaxed to make the recording pass. The replay preserves actual
|
||||
timestamps/context, reports missing historical velocity as unavailable, and
|
||||
does not reconstruct missing modern actions or simulate steering feedback.
|
||||
These counts do not validate the newly installed asymmetric camera or modern
|
||||
yaw-action strategy. Delay assumptions, final camera pose, moving live cadence
|
||||
and closed-loop vehicle response remain unvalidated. Report:
|
||||
`diagnostics/pop-v2-trajectory-controller-replay-20261003.json`. Reproduce with
|
||||
`python tools/replay_pop_trajectory.py diagnostics/inset-cal-20261003-123419-822490`.
|
||||
|
||||
After the asymmetric camera installation, the completed manual drive in
|
||||
`diagnostics/inset-cal-20261003-130507-234700` produced 2,091 moving observations
|
||||
over 120 seconds. The modern yaw-action preview accepted 1,299/1,948 observations
|
||||
within its supported speed range (66.7%); 143 exceeded the 30 MPH preview limit.
|
||||
Its longest uninterrupted accepted preview lasted 44.4 seconds. Median actual
|
||||
inference cadence was 17.3 Hz, with complete context on 95.3% of moving rows.
|
||||
All 2,095 evidence rows flushed with zero writer drops/errors; 1,880 rows include
|
||||
camera image pairs at the configured maximum save frequency. Controls stayed
|
||||
off. Camera, controller strategy and route conditions differ from the earlier
|
||||
drive, so this is not a controlled comparison or physical calibration proof.
|
||||
See `diagnostics/pop-v2-rectified-live-audit-20261003.json`.
|
||||
The subsequent bounded, panel-free timing run recorded 403 moving observations
|
||||
at median 19.89 Hz with zero writer drops/errors. This isolates a feasible
|
||||
model-loop budget, not sustained panel-inclusive cadence or control validation;
|
||||
the nonblocking panel event change still needs live timing verification.
|
||||
See `diagnostics/pop-v2-rectified-no-hud-timing-audit-20261003.json`.
|
||||
|
||||
A subsequent short parked run with the nonblocking panel recorded 160 frames
|
||||
at median 19.83 Hz. Three intervals exceeded 150 ms (maximum 512 ms), so this
|
||||
does not establish sustained moving cadence. Final evidence flushed without
|
||||
writer drops/errors. See `diagnostics/pop-v2-panel-poll-parked-audit-20261003.json`.
|
||||
|
||||
`tools/measure_stationary_steering_response.py` performs only small parked
|
||||
steering steps with neutral between them. It requires distinct fresh SDK
|
||||
samples, neutral gear, the parking brake, foreground ATS and released manual
|
||||
inputs before acquiring vJoy; guard failures release and close the device.
|
||||
The October 3 run reached 90% of the +/-0.1 SDK steering targets within observed
|
||||
41-61 ms brackets and verified neutral after shutdown. This includes feeder,
|
||||
game and SDK observation latency; it is not a moving yaw-delay measurement.
|
||||
See `diagnostics/stationary-steering-response-20261003.json`.
|
||||
Older 579 highway recordings independently suggest local left-positive
|
||||
curvature approximately equals 0.1254 times normalized SDK steering, over the
|
||||
observed small steering/speed range. These estimates do not grant camera or
|
||||
full-range steering calibration. New active command records timestamp command
|
||||
enqueue separately from loop start; neither timestamp is a driver acknowledgment.
|
||||
See `diagnostics/579-steering-response-existing-evidence-20261003.json`.
|
||||
|
||||
The model hash and tensor layout are pinned in `models/manifest.json`. Its original training/export version is unrecorded. The matching historical 6409 decoder includes five trajectory hypotheses, odd-index lane probabilities, five lead hypotheses, separate lead probabilities, and 512 recurrent-state floats. Plan selection weights are not treated as road-view confidence.
|
||||
|
||||
Telemetry opens an existing `Local\\SCSTelemetry` mapping and requires revision 12 / ATS, active SDK, unpaused state, and changing timestamps. Missing telemetry blocks engagement. Speed, gear, steering, pedals, engine/parking state, and head orientation use the versioned layout.
|
||||
|
||||
- [RenCloud v1.12.1 layout](https://github.com/RenCloud/scs-sdk-plugin/blob/V.1.12.1/scs-telemetry/inc/scs-telemetry-common.hpp)
|
||||
- [Historical output decoder](https://github.com/commaai/openpilot/blob/v0.8.5/selfdrive/modeld/models/driving.cc)
|
||||
- [Lane coordinate convention](https://github.com/commaai/openpilot/blob/v0.8.5/selfdrive/controls/lib/lane_planner.py)
|
||||
- [YUV packing](https://github.com/commaai/openpilot/blob/v0.8.5/selfdrive/modeld/transforms/loadyuv.cl)
|
||||
- [Historical MED projection and camera height](https://github.com/commaai/openpilot/blob/v0.8.5/common/transformations/model.py)
|
||||
- [Runtime use of the MED ground transform](https://github.com/commaai/openpilot/blob/v0.8.5/selfdrive/modeld/modeld.cc)
|
||||
- [Windows input contract](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendinput)
|
||||
|
||||
## Files
|
||||
|
||||
The October 3 Tesla Semi shoulder departure is addressed by
|
||||
`control/gameplay_road_tracking.py`. It confirms an ego-containing observed
|
||||
lane over three frames, compares its identity using SDK vehicle motion, and
|
||||
tracks its near center with a 12–25 m lookahead. Validated GPS/signal maneuver
|
||||
paths retain precedence. Paint gaps propagate the observed corridor for up
|
||||
to one second. A further bounded recovery is allowed only when fresh matching
|
||||
GPS and current model geometry agree with the motion-projected acquired lane,
|
||||
the truck stays near its center, and observed lane coverage remains. It expires
|
||||
after two seconds, inhibits acceleration, and gently reduces the speed target.
|
||||
Longer or contradictory loss brakes and fades steering toward neutral instead
|
||||
of following an uncertain off-road forecast. Model-only laneless following
|
||||
remains available before a lane is acquired. A large uncertain local forecast
|
||||
also requests braking. F8 and manual takeover still release all controls.
|
||||
|
||||
Tesla Semi gameplay uses descriptive steering gain 0.1535, estimated from
|
||||
195 moving SDK samples in `diagnostics/tesla-steering-response-20261003.json`;
|
||||
the 579 retains 0.1254. Neither is physical calibration. Reproduce the saved
|
||||
failure-frame decision comparison with `python tools/replay_gameplay_road_tracking.py
|
||||
diagnostics/pop-gameplay-20261003-165000-855391 --output diagnostics/wmi-road-tracking-replay-20261003.json`.
|
||||
This replay preserves the original truck trajectory and images, so it does
|
||||
not prove the outcome of a changed closed-loop drive. Independent kinematic
|
||||
tests cover delayed steering on a curve, short marking gaps, lane identity
|
||||
jumps, validated lane changes, and braking after a prolonged road loss.
|
||||
|
||||
`tools/build_tesla_screen_addon.py` prepares a separate companion `.scs`
|
||||
for the installed Tesla Semi mod. The left screen keeps native imperial truck
|
||||
instruments (speed, gear, limit, ATS cruise, clock, signals and parking brake)
|
||||
above an independent live app tile showing Autopilot state/release reason,
|
||||
MAX, pedals, following distance, trailer state, lights and SDK warning flags.
|
||||
The right 1024×512 screen has a legible road/traffic scene beside an active GPS
|
||||
route map, next verified route bend, remaining miles and ATS-clock arrival time.
|
||||
The ego tractor uses a Tesla Semi cab-over mesh, with actual trailer attachment
|
||||
and articulation retained. Camera input remains hidden unless requested in the
|
||||
desktop panel. `ui/dashboard_stream.py` publishes both display-only BGRA streams.
|
||||
The Tesla mod reflects the right surface vertically; both placeholder and
|
||||
live uploads reverse their image rows so the cabin display reads upright.
|
||||
Missing or failed display publishing cannot interrupt gameplay controls.
|
||||
The native texture consumer and add-on must be installed and enabled before
|
||||
the screens can show live app data. Original mod files are preserved. The
|
||||
earlier right display was observed upright on 2026-10-03. On 2026-10-04 the
|
||||
corrected dual-stream build reached a powered, parked cabin without repeating
|
||||
the entry crash; the right road/map panel was visibly upright and native logs
|
||||
reported two marked textures with fresh left/right frames. The left physical
|
||||
screen originally sampled separate UV regions. A source-pinned companion mesh
|
||||
override remaps only those display vertices to one continuous native dashboard;
|
||||
the powered cabin then showed the new speed/gear layout and removed the baked
|
||||
truck artwork. The status-image cursor/tint/layer fix was then observed in the
|
||||
powered cabin: native speed/gear/clock/cruise fields and the live Autopilot
|
||||
status/indicators/warnings tile are upright and visible across the full left
|
||||
surface, alongside the upright right panel. No repeat entry crash was observed.
|
||||
Moving display stability remains unverified; see
|
||||
`diagnostics/ats-crash-20261004-220212/verification.json` and its cabin screenshot.
|
||||
The gear instrument uses native transmission mode (ID 1380): D/N/R/M, rather
|
||||
than the gear-number field that emits A5 and similar automatic gear labels.
|
||||
The native bridge retains its last valid texture through short producer gaps,
|
||||
handles both UNORM/sRGB views and uses cached replacements during contention.
|
||||
After two seconds without valid frames the right view dims and says DISPLAY
|
||||
OFFLINE, while the left app tile returns to APP OFFLINE with native instruments
|
||||
still updating. Fresh producer frames restore both streams independently.
|
||||
With ATS closed, `Install-Tesla-Screens.bat` installs the companion and the
|
||||
enabled display prototype (both its own flag and SPF's TruckScreen flag).
|
||||
Activate "ATS OP Tesla screens" above the original
|
||||
Tesla Semi in Mod Manager. The native `TruckScreen` log must show marked
|
||||
textures, fresh HUD frames, and replacement binds before live integration can
|
||||
be claimed. This display prototype requires a normal game restart for updates;
|
||||
see `native/truck_screen/README.md` for supported texture scope and rollback.
|
||||
|
||||
`ui/map_background.py` expands only display road references from mounted game
|
||||
archives on a bounded background worker (36 sectors by default). The blue GPS
|
||||
route comes from the native route graph, not a fabricated ego connector; map
|
||||
references are not control lanes. Heading-up and overview displays share
|
||||
smoothed visual pose/zoom, while control uses original telemetry. R in the
|
||||
desktop panel toggles route overview. Unknown street names, exit numbers and
|
||||
destinations are not invented. `tools/preview_cab_screens.py` renders a labeled
|
||||
offline preview from a saved drive; `tools/expand_display_map.py` prepares the
|
||||
display cache without changing installed game files or steering map caches.
|
||||
When the stable native route array agrees with the SDK trip but the truck's
|
||||
approach to its first node cannot be qualified, the map shows only the actual
|
||||
route nodes with a connection-unverified label. It adds no approach connector
|
||||
or turn instruction, and GPS control still receives an unavailable route.
|
||||
That display-only geometry expires on stale telemetry or a destination change.
|
||||
|
||||
Gameplay speed holding now brakes gently for small overspeed when ATS coast
|
||||
drag is absent, releases early using measured deceleration, and uses separate
|
||||
braking-entry/release thresholds to reduce pedal cycling. SDK-observed native
|
||||
ATS cruise produces an explicit conflict instead of trying a guessed cancel
|
||||
key. Lead emergency braking remains independent of confidence recovery.
|
||||
Native live signal phases and authored stop points are now decoded and joined
|
||||
to selected prefab paths. Restrictive stopping has a separate native planner;
|
||||
green alone does not establish intersection priority or authorize entry.
|
||||
|
||||
The active development goal is an ATS-native navigation planner. The separate
|
||||
native launcher operates without openpilot or Pop/WMI inference. The earlier
|
||||
model launcher and assets remain available for development rollback while the
|
||||
native backend is validated on representative roads.
|
||||
|
||||
The implementation order is:
|
||||
|
||||
1. Repair the recorded trailer-chain traffic failure, exhausted-lane tracking,
|
||||
and stopped-queue GPS short-horizon disengagement; replay the saved failures
|
||||
before another ordinary drive.
|
||||
2. Separate shared geometry types from model inference. Build a timestamped
|
||||
driving scene and connected lane graph from mounted road definitions and
|
||||
prefab navigation curves, with actual lane placement, drivable boundaries,
|
||||
directed connectivity, vehicle pose and attached-trailer geometry. GPS road
|
||||
references and display-only curves must not be substituted for lane centers.
|
||||
3. Give that planner smooth traffic following, stopped-queue holding/restart,
|
||||
curve and route speed targets, and an adjustable maximum in imperial units.
|
||||
4. Plan turn-signal lane changes, GPS exits and intersection turns using the
|
||||
connected lanes and observed clearance. Live light phases and authored stop
|
||||
points are joined by exact prefab/curve identity; complete stop-line spans,
|
||||
protected phase arbitration and unsignalized right-of-way remain unfinished.
|
||||
5. Render the same selected lane, route, maneuver, target speed and stop reason
|
||||
on both Tesla Semi screens. Retire inference from the driving runtime once
|
||||
the native planner has demonstrated replacement coverage.
|
||||
|
||||
Completion requires representative mixed-road driving with lane holding,
|
||||
smooth traffic stops/restarts, correct GPS maneuvers and traffic-rule stops,
|
||||
stable screens, and explicit handling of genuinely missing data. Passing unit
|
||||
tests, a model change or a short straight drive alone is not completion. Keep
|
||||
archived model assets available for rollback; they are not required inputs to
|
||||
the target native planner.
|
||||
|
||||
`main.py` orchestrates readiness, F8, takeover, perception, controls, HUD, and logs. `runtime_checks.py` contains readiness checks. `control/windows_input.py` owns correctly sized Win32 input, ATS discovery, and the takeover hook. `control/fsd_controller.py` tracks paths and modulates keyboard controls with feedback and a watchdog. `telemetry/ats_telemetry.py` reads the versioned plugin mapping. `vision/screen_capture.py` captures the ATS client area and packs two-frame YUV. `model/openpilot_brain.py` executes and decodes the pinned model. `ui/tesla_fsd_hud.py` shows real telemetry and health.
|
||||
|
||||
## ATS-native experimental driving backend
|
||||
|
||||
`Run-Native-Drive.bat` starts `tools/run_native_gameplay.py` without loading
|
||||
openpilot, ONNX, Pop/WMI inference, camera tensors, or temporal model history.
|
||||
F8 still owns engagement and release; Home/End adjusts MAX in MPH. Controls
|
||||
follow the selected directed native GPS lane, measure actor/trailer contact
|
||||
along that same path, and use SDK speed for smooth following and queue restart.
|
||||
The screens and evidence recorder receive the actual commanded trajectory.
|
||||
Native evidence explicitly has no camera or inference outputs.
|
||||
Use `--cab-only` to keep both live cabin displays without rendering a separate
|
||||
desktop window. The default launcher retains the optional desktop panel.
|
||||
|
||||
The local mounted-map cache covers nine sectors: 2,549 road-lane candidates,
|
||||
2,061 prefab paths, and 4,739 directed connections. Full quaternion placement
|
||||
now resolves graded prefabs. Independently measured spans qualify only their
|
||||
observed intervals. The native launcher additionally opts into complete PPD
|
||||
curves derived from the published SCS stored-length cubic and verified asset
|
||||
placement, plus 2,483 ordinary road primitives from a pinned reverse-engineered
|
||||
stored-length/full-quaternion formula and measured cross-sections. These are
|
||||
experimental source qualifications, not empirical tests of every curve.
|
||||
Fifty-eight banked lanes and eight profile transitions remain excluded, and
|
||||
the speed planner stops before qualified coverage ends. Ordered arc-distance
|
||||
trajectories retain sharp turns without sorting or extrapolating a path.
|
||||
|
||||
The native graph is now a persistent cache rather than a one-shot artifact.
|
||||
`NativeLaneGraphManager` keeps the last verified graph, watches the current
|
||||
pose and the live GPS route, and launches the bounded extractor in a separate
|
||||
process before the route reaches an uncached sector. Completed sectors are
|
||||
deduplicated by stable lane identity and atomically merged; a changed ATS or
|
||||
mod archive starts a new graph instead of mixing incompatible geometry. The
|
||||
control loop never waits for extraction and never engages without current
|
||||
route coverage, so a rebuild no longer requires restarting ATS or manually
|
||||
replacing the graph.
|
||||
|
||||
Setting or changing the ATS GPS route now starts a background **whole-trip
|
||||
lane plan** in `control/native_trip_planner.py`. The cache manager preloads
|
||||
every route sector, including intermediate sectors on long GPS edges. The
|
||||
planner works backwards from the destination over actual lane connections,
|
||||
so an earlier fork uses the lane needed by a later exit. It records required
|
||||
road lane changes and looks for connected truck-compatible detours around
|
||||
unsupported GPS segments. Off-route detours require positive player-truck
|
||||
access metadata; NPC geometry alone cannot authorize a shortcut through a
|
||||
yellow X barrier or inaccessible scenery. Live lane changes still require exact mounted
|
||||
boundary permission and fresh vehicle/trailer clearance; a planned maneuver
|
||||
does not authorize a lateral jump. Route preparation takes priority over
|
||||
passing and does not depend on finding a slower lead vehicle.
|
||||
|
||||
Plans are bound to the GPS revision and verified mounted graph. GPS changes
|
||||
invalidate old policies; compatible cache extensions keep serving the previous
|
||||
policy while a worker refreshes it. Full reports are saved under
|
||||
`diagnostics/native-lanes/trips/`, and the right navigation screen shows loading
|
||||
or upcoming gaps and displays generated truck detours. Missing geometry,
|
||||
unconnected lanes and truck-restricted paths remain explicit gaps, rather than
|
||||
being labelled a complete route. This is a trip lane plan, not a promise that
|
||||
traffic, signals or temporary roadwork will be clear when the truck arrives.
|
||||
SCS prefab allowed-vehicle flags describe NPC preferences, rather than player
|
||||
access restrictions. A source-qualified small-vehicle variant can be used as
|
||||
a fallback only for the exact node pair requested by the live game GPS, while
|
||||
truck-preferred variants retain a routing advantage. Explicit mounted player
|
||||
access switches override this fallback. Legacy zero access masks are unknown;
|
||||
the access decoder does not claim complete coverage of invisible collision
|
||||
walls or dynamic closures. See the [SCS prefab locator documentation](https://modding.scssoft.com/wiki/Documentation/Tools/SCS_Blender_Tools/Locators/Prefab_Locators)
|
||||
and `telemetry/native_player_access.py` for the separate contracts.
|
||||
`python -B tools/check_native_trip.py` reads the live trip without actuation;
|
||||
`--route <saved JSON>` checks an offline route or SDK capture.
|
||||
|
||||
`control/native_signal_planner.py` joins authored cross-line start points to the
|
||||
first actual governing semaphore by exact prefab/curve identity. The native
|
||||
controller can restrict speed and hold the brake for that point. Experimental
|
||||
green entry requires supported absolute authored priority, fresh measured
|
||||
traffic motion, complete observed traversal and coverage through the prefab
|
||||
exit. This is a permissive observed-gap policy, not protected-phase proof or
|
||||
exhaustive clearance; permissions expire after 0.2 seconds and cap entry speed
|
||||
at 8 m/s (about 18 MPH). Unknowns and conflicts retain a hold. Unsignalized
|
||||
priority and native turn-signal lane changes remain unfinished. Retain model
|
||||
assets for rollback until representative mixed-road drives pass.
|
||||
|
||||
The right-screen traffic scene draws the actual selected solid blue driving
|
||||
path. The separate dashed GPS chord and its debug legend are removed; active
|
||||
navigation stays on the map. Dashboard addon 0.2.2 suppresses six duplicate ATS
|
||||
symbol quads where custom indications are mapped, preserving unmapped native
|
||||
warning/service/differential-lock indicators and the native speed/gear display.
|
||||
|
||||
The native runner now watches the Tesla Semi's battery estimate (the mod's
|
||||
SDK fuel amount divided by capacity). At **20% or below**, it plans a detour
|
||||
to the nearest reachable mapped fuel service. Exact mounted PPD gas spawn
|
||||
points identify service locations; directed, qualified lanes and existing
|
||||
lane-change permissions determine reachability. Station search and asset
|
||||
decoding run on a background worker. A charging detour never acquires F8 or
|
||||
grants traffic clearance, and blocked/unqualified paths remain excluded.
|
||||
|
||||
The custom screen shows the charging route and retains the ATS GPS/job
|
||||
destination. The game GPS itself is not rewritten. The controller approaches
|
||||
the supported pump path, holds the brake, and leaves the game's refuelling
|
||||
interaction to the driver. At **90% or above**, it restores the original route;
|
||||
the detour stays active throughout charging below that target. Distances
|
||||
to the stop are estimates from the map's local scale. If no supported
|
||||
connection reaches a station, the panel reports that limitation and leaves
|
||||
the existing route intact. Some station approaches still need native map
|
||||
connection coverage before automatic detours work there.
|
||||
|
||||
Banked ordinary roads use an experimental linear endpoint-roll surface model
|
||||
up to six degrees. This rotates the measured lane offset in height as well as
|
||||
laterally, reconstructs source coordinates before qualification, and checks
|
||||
connections again. The original unmodelled geometry retains its three-degree
|
||||
bound. Truck heading, height and lane-membership gates are unchanged; this
|
||||
surface approximation still requires live driving validation.
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
"C:\Python314\python.exe" tools\run_native_gameplay.py %*
|
||||
pause
|
||||
@@ -0,0 +1,12 @@
|
||||
@echo off
|
||||
title ATS - Continuous Pop v2 Gameplay
|
||||
cd /d "%~dp0"
|
||||
echo Continuous experimental gameplay with live model panel.
|
||||
echo Warm up the camera, then F8 toggles driving. Home/End adjust speed by 5 MPH.
|
||||
echo Your speed target is saved. First launch defaults to 35 MPH. Range: 5-80 MPH.
|
||||
echo Manual steering or braking releases. Camera looks remain available.
|
||||
echo Disengagement returns to live passive view. F8 can engage again when ready.
|
||||
echo Escape releases controls and keeps the panel open. Close the panel or press Q in it to exit.
|
||||
echo Keep ATS foreground while engaged.
|
||||
python tools\run_pop_gameplay.py
|
||||
pause
|
||||
@@ -0,0 +1,9 @@
|
||||
@echo off
|
||||
title ATS - Pop v2 Preview
|
||||
cd /d "%~dp0"
|
||||
echo Pop v2 trajectory preview. Manual driving; F8 cannot apply controls.
|
||||
echo Steering assessment uses the local path, uncertainty, and estimated road edges.
|
||||
echo Use the Pop wide-camera profile for distinct wide and narrow inputs.
|
||||
echo Waits for forward motion, then records two minutes at the available capture rate.
|
||||
python main.py --camera auxiliary --model pop-v2 --dry-run --path-preview --record-calibration --record-image-hz 20 --navigation-preview --inference-provider cpu --speed 25 --duration 120 --duration-after-motion
|
||||
pause
|
||||
@@ -0,0 +1,12 @@
|
||||
@echo off
|
||||
title ATS - Experimental Pop Steering Trial
|
||||
cd /d "%~dp0"
|
||||
echo Experimental one-shot 15-second steering test. MANUAL PEDALS.
|
||||
echo Start parked in neutral with parking brake on and inputs released.
|
||||
echo After the panel is ready, drive centered at 25-27 MPH, then press F8 once.
|
||||
echo The permitted speed band is 24-28 MPH; leaving it releases steering.
|
||||
echo F8 again, Escape, manual steering, focus loss or failed model guard ends the test.
|
||||
echo No automatic engagement, throttle or brake control. Five-minute standby maximum.
|
||||
echo A blocked F8 leaves standby running; wait for ready, then press F8 again.
|
||||
python tools\run_pop_steering_trial.py
|
||||
pause
|
||||
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
echo Supervised inset Chill cruise test: 15 MPH target, 2 minute limit.
|
||||
echo Keep ATS widgets hidden with F3 and use a marked lane.
|
||||
echo Release manual pedals before F8. F8 again or driving keys take over.
|
||||
python main.py --camera auxiliary --backend vjoy --inference-provider cpu --inset-cruise-test --driving-mode chill --speed 15 --duration 120
|
||||
pause
|
||||
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
echo Passive model-path and turn-signal evaluation. You control the truck.
|
||||
echo Keep ATS widgets hidden with F3 so popups cannot cover the road inset.
|
||||
echo Model-intent previews do not steer or press pedals.
|
||||
python main.py --camera auxiliary --dry-run --record-calibration --inference-provider cpu --path-preview --signal-preview --signal-delay 1 --driving-mode manual
|
||||
pause
|
||||
@@ -0,0 +1,9 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
echo GPS-assisted simulator driving trial: 12 MPH Chill cruise, 2 minute limit.
|
||||
echo Keep ATS widgets hidden with F3. Start centered in a marked lane.
|
||||
echo Select Drive, release the parking brake and pedals, then press F8 once.
|
||||
echo F8 again or physical steering/pedal keys take over.
|
||||
echo GPS guides camera-supported steering; complex intersections still need manual driving.
|
||||
python main.py --camera auxiliary --backend vjoy --inference-provider cpu --navigation-driving-test --driving-mode chill --speed 12 --duration 120
|
||||
pause
|
||||
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
echo Live ATS GPS route and road model preview. You control the truck.
|
||||
echo Keep ATS widgets hidden with F3 and leave F8 off.
|
||||
echo The original dashboard shows the road camera, model and route map.
|
||||
python main.py --camera auxiliary --dry-run --record-calibration --inference-provider cpu --navigation-preview --driving-mode manual
|
||||
pause
|
||||
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
title Tesla Semi FSD - Passive Model View
|
||||
cd /d "%~dp0"
|
||||
echo Passive road, nearby traffic, model camera and GPS view. F8 driving is disabled.
|
||||
python main.py --camera auxiliary --dry-run --record-calibration --navigation-preview --inference-provider cpu --driving-mode manual --speed 12
|
||||
pause
|
||||
@@ -0,0 +1,9 @@
|
||||
@echo off
|
||||
title Tesla Semi FSD - Native ATS Autopilot
|
||||
cd /d "%~dp0"
|
||||
echo Starting ATS-native GPS/lane/traffic autopilot with the Tesla Semi screens...
|
||||
echo Openpilot and camera inference are not used for control in this launcher.
|
||||
echo F8 engages/releases; Home/End adjusts the MAX speed in MPH.
|
||||
echo Input auto prefers the ETS2LA semantic controller and falls back to vJoy.
|
||||
python tools\run_native_gameplay.py --input auto %*
|
||||
pause
|
||||
@@ -0,0 +1,8 @@
|
||||
@echo off
|
||||
title ATS - WMI Driving
|
||||
cd /d "%~dp0"
|
||||
echo WMI 0.11 driving model. F8 toggles driving after the camera warms up.
|
||||
echo Home/End adjust MAX by 5 MPH. Higher navigation limits can raise MAX.
|
||||
echo Escape releases controls. Panel V toggles the camera; panel Q exits.
|
||||
python tools\run_pop_gameplay.py --model wmi-v0.11.0
|
||||
pause
|
||||
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
Tesla FSD Audio Chimes Player
|
||||
Plays authentic synthesized Tesla Full Self-Driving auditory alerts asynchronously.
|
||||
"""
|
||||
|
||||
import os
|
||||
import winsound
|
||||
|
||||
class TeslaChimes:
|
||||
def __init__(self, sounds_dir="sounds"):
|
||||
self.sounds_dir = os.path.abspath(sounds_dir)
|
||||
self.engage_path = os.path.join(self.sounds_dir, "engage.wav")
|
||||
self.disengage_path = os.path.join(self.sounds_dir, "disengage.wav")
|
||||
self.prompt_path = os.path.join(self.sounds_dir, "prompt.wav")
|
||||
|
||||
def play_engage(self):
|
||||
"""Plays rising double ding when FSD activates."""
|
||||
if os.path.exists(self.engage_path):
|
||||
winsound.PlaySound(self.engage_path, winsound.SND_FILENAME | winsound.SND_ASYNC)
|
||||
|
||||
def play_disengage(self):
|
||||
"""Plays descending tone when FSD deactivates."""
|
||||
if os.path.exists(self.disengage_path):
|
||||
winsound.PlaySound(self.disengage_path, winsound.SND_FILENAME | winsound.SND_ASYNC)
|
||||
|
||||
def play_takeover_prompt(self):
|
||||
"""Plays urgent takeover warning chime."""
|
||||
if os.path.exists(self.prompt_path):
|
||||
winsound.PlaySound(self.prompt_path, winsound.SND_FILENAME | winsound.SND_ASYNC)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Move one vJoy axis for ATS's axis-binding dialog, while the game is paused."""
|
||||
import argparse
|
||||
import time
|
||||
|
||||
from control.virtual_joystick import VirtualJoystick
|
||||
from control.windows_input import ATSWindow, TakeoverMonitor
|
||||
from telemetry.ats_telemetry import ATSTelemetry
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("axis", choices=("steering", "throttle", "brake"))
|
||||
args = parser.parse_args()
|
||||
window = ATSWindow()
|
||||
telemetry = ATSTelemetry()
|
||||
monitor = TakeoverMonitor()
|
||||
joystick = None
|
||||
|
||||
def require_menu():
|
||||
if window.find():
|
||||
data = telemetry.get_data()
|
||||
if not data.get("plugin_active") or not data.get("paused"):
|
||||
raise RuntimeError("Open ATS Controls with the telemetry plugin installed; axis binding requires a paused game")
|
||||
|
||||
try:
|
||||
require_menu()
|
||||
joystick = VirtualJoystick()
|
||||
print(f"Select the ATS {args.axis} axis binding within 5 seconds. Escape cancels.")
|
||||
deadline = time.monotonic() + 5
|
||||
while time.monotonic() < deadline:
|
||||
require_menu()
|
||||
if monitor.consume()[1]:
|
||||
return
|
||||
time.sleep(0.05)
|
||||
started = time.monotonic()
|
||||
while time.monotonic() - started < 12:
|
||||
require_menu()
|
||||
if monitor.consume()[1]:
|
||||
return
|
||||
high = int((time.monotonic() - started) / 1.5) % 2
|
||||
if args.axis == "steering":
|
||||
joystick.apply(1.0 if high else -1.0, "coast", 0)
|
||||
else:
|
||||
joystick.apply(0, args.axis, float(high))
|
||||
time.sleep(0.05)
|
||||
print("Finished; steering centered and pedals released.")
|
||||
finally:
|
||||
try:
|
||||
if joystick:
|
||||
joystick.close()
|
||||
finally:
|
||||
monitor.close()
|
||||
telemetry.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Speed control tuned for ATS's strong brake response, independent of model lanes."""
|
||||
import math
|
||||
import time
|
||||
|
||||
|
||||
class ComfortCruise:
|
||||
def __init__(self, mode="cruise", clock=time.monotonic):
|
||||
if mode not in ("cruise", "chill"):
|
||||
raise ValueError("Cruise mode must be cruise or chill")
|
||||
self.mode, self.clock = mode, clock
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.previous = None
|
||||
self.previous_target = None
|
||||
self.acceleration = 0.0
|
||||
self.load_compensation = 0.0
|
||||
self.action, self.intensity = "coast", 0.0
|
||||
|
||||
def compute(self, target_mph, speed_mph, lead):
|
||||
if not all(math.isfinite(v) and v >= 0 for v in (target_mph, speed_mph)):
|
||||
self.reset()
|
||||
raise ValueError("Invalid cruise speed")
|
||||
now = self.clock()
|
||||
dt = 0.05
|
||||
recent_sample = False
|
||||
if self.previous is not None:
|
||||
old_time, old_speed = self.previous
|
||||
elapsed = now - old_time
|
||||
if 0.001 <= elapsed <= 0.5:
|
||||
dt = elapsed
|
||||
recent_sample = True
|
||||
observed = max(-8.0, min(3.0, (speed_mph-old_speed)/dt))
|
||||
alpha = dt / (0.2 + dt)
|
||||
self.acceleration += alpha * (observed-self.acceleration)
|
||||
else:
|
||||
self.acceleration = 0.0
|
||||
self.load_compensation = 0.0
|
||||
if self.previous_target is not None and target_mph < self.previous_target:
|
||||
self.load_compensation = 0.0
|
||||
self.previous_target = target_mph
|
||||
self.previous = now, speed_mph
|
||||
# Lead braking bypasses the comfort ramp. It must never be weakened
|
||||
# merely because a relaxed driving mode was selected.
|
||||
gap = max(20.0 if self.mode == "chill" else 15.0,
|
||||
speed_mph * 0.44704 * (3.5 if self.mode == "chill" else 2.5))
|
||||
if lead.detected:
|
||||
# Speed lost while following traffic is not evidence of hill load.
|
||||
self.load_compensation = 0.0
|
||||
if not math.isfinite(lead.distance) or lead.distance < 0:
|
||||
self.reset()
|
||||
raise ValueError("Invalid lead distance")
|
||||
if lead.distance < gap:
|
||||
self.action = "brake"
|
||||
self.intensity = min(0.8, max(0.2, (gap-lead.distance)/15.0))
|
||||
return self.action, self.intensity
|
||||
# Anticipate another half second of measured speed change. This
|
||||
# releases braking before the target and avoids accelerating into it.
|
||||
error = target_mph - max(0.0, speed_mph + 0.5*self.acceleration)
|
||||
if speed_mph > target_mph or error < 0:
|
||||
self.load_compensation = 0.0
|
||||
if error > 1.0:
|
||||
action = "throttle"
|
||||
limit = 0.25 if self.mode == "chill" else 0.45
|
||||
proportional = max(0.05, error/15.0)
|
||||
# A pure proportional controller settles below target under load.
|
||||
# Learn a small addition only during fresh, below-target throttle
|
||||
# samples. Stop learning at saturation instead of winding up.
|
||||
if recent_sample and not lead.detected and proportional+self.load_compensation < limit:
|
||||
self.load_compensation = min(0.15, max(0.0, limit-proportional),
|
||||
self.load_compensation + .02*error*dt)
|
||||
duty = min(limit, proportional+self.load_compensation)
|
||||
ramp = 0.18 if self.mode == "chill" else 0.35
|
||||
elif error < -1.0:
|
||||
action = "brake"
|
||||
duty = min(0.08 if self.mode == "chill" else 0.12, (-error-0.5)/60.0)
|
||||
ramp = 0.05 if self.mode == "chill" else 0.08
|
||||
else:
|
||||
self.load_compensation = max(0.0, self.load_compensation-.04*dt)
|
||||
self.action, self.intensity = "coast", 0.0
|
||||
return self.action, self.intensity
|
||||
previous = self.intensity if self.action == action else 0.0
|
||||
self.action, self.intensity = action, min(duty, previous+ramp*dt)
|
||||
return self.action, self.intensity
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Configure an ATS profile for vJoy using SCS's documented input format.
|
||||
|
||||
Run while ATS is closed. A timestamped backup preserves existing bindings.
|
||||
"""
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
|
||||
from control.windows_input import ATSWindow
|
||||
|
||||
|
||||
def configured_text(text, device_id):
|
||||
if not re.fullmatch(r'\{[0-9A-Fa-f-]{36}\}\|\{[0-9A-Fa-f-]{36}\}', device_id):
|
||||
raise ValueError("Invalid DirectInput device identification")
|
||||
replacements = {
|
||||
"device joy": f"device joy `di8.'{device_id}'`",
|
||||
"input j_steer": "input j_steer `joy.x`",
|
||||
"input j_throttle": "input j_throttle `joy.y`",
|
||||
"input j_brake": "input j_brake `joy.z`",
|
||||
"constant c_steer_func": "constant c_steer_func 0.000000",
|
||||
"constant c_steer_dz": "constant c_steer_dz 0.000000",
|
||||
"constant c_throt_dz": "constant c_throt_dz 0.000000",
|
||||
"constant c_brake_dz": "constant c_brake_dz 0.000000",
|
||||
"constant c_jzthrottle": "constant c_jzthrottle 1.000000",
|
||||
"constant c_jithrottle": "constant c_jithrottle 0.000000",
|
||||
"constant c_jzbrake": "constant c_jzbrake 1.000000",
|
||||
"constant c_jibrake": "constant c_jibrake 0.000000",
|
||||
"constant c_jisteer": "constant c_jisteer 0.000000",
|
||||
"constant c_relatsteer": "constant c_relatsteer 0.000000",
|
||||
"constant c_mousesteer": "constant c_mousesteer 0.000000",
|
||||
"constant c_ff_enabled": "constant c_ff_enabled 0.000000",
|
||||
}
|
||||
for key, replacement in replacements.items():
|
||||
pattern = r'(?m)(^\s*config_lines\[\d+\]: ")' + re.escape(key) + r' [^"\r\n]*(")'
|
||||
text, count = re.subn(pattern, lambda m: m[1] + replacement + m[2], text)
|
||||
if count != 1:
|
||||
raise ValueError(f"Expected one {key} entry, found {count}; no file was changed")
|
||||
return text
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("profile", type=Path, help="Profile directory containing controls.sii")
|
||||
parser.add_argument("--log", type=Path, default=Path.home() / "Documents/American Truck Simulator/game.log.txt")
|
||||
parser.add_argument("--apply", action="store_true", help="Back up and save bindings; default only previews")
|
||||
args = parser.parse_args()
|
||||
log = args.log.read_text(encoding="utf-8", errors="replace")
|
||||
devices = re.findall(r"\[di8\] Initializing device 'vJoy Device' as '([^']+)'", log)
|
||||
if len(set(devices)) != 1:
|
||||
raise RuntimeError("Launch ATS once with vJoy enabled; expected exactly one vJoy device in its log")
|
||||
path = args.profile.resolve() / "controls.sii"
|
||||
original = path.read_bytes()
|
||||
text = original.decode("utf-8")
|
||||
updated = configured_text(text, devices[-1])
|
||||
print(f"Profile: {path}\nvJoy: {devices[-1]}\nX steering, Y throttle, Z brake; linear wheel, centered pedals")
|
||||
if args.apply:
|
||||
if ATSWindow().find():
|
||||
raise RuntimeError("Close ATS before changing profile bindings")
|
||||
if updated.encode("utf-8") == original:
|
||||
print("Bindings already configured")
|
||||
return
|
||||
backup = path.with_name("controls.sii.pre-vjoy-" + datetime.now().strftime("%Y%m%d-%H%M%S-%f") + ".bak")
|
||||
shutil.copy2(path, backup)
|
||||
path.write_bytes(updated.encode("utf-8"))
|
||||
print(f"Saved bindings; backup: {backup}")
|
||||
else:
|
||||
print("Preview only; use --apply with ATS closed to save")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,215 @@
|
||||
"""Small ATS input client for ETS2LA's semantic controller plugin.
|
||||
|
||||
The native launcher can use this backend when ``ets2la_controller.dll`` is
|
||||
installed in ATS. It writes only the documented shared-memory input protocol;
|
||||
it does not inject code, acquire vJoy, or depend on a camera/model process.
|
||||
The vJoy backend remains available as an explicit fallback for older installs.
|
||||
"""
|
||||
import ctypes
|
||||
import math
|
||||
import os
|
||||
import struct
|
||||
import time
|
||||
|
||||
|
||||
CONTROL_BYTES = 4096
|
||||
INPUT_BYTES = 4096
|
||||
TOTAL_BYTES = CONTROL_BYTES + INPUT_BYTES
|
||||
MAX_INPUTS = 400
|
||||
MAX_CLIENTS = 32
|
||||
CLIENT_TIMEOUT_MS = 3000
|
||||
HEARTBEAT_INTERVAL_S = .25
|
||||
MAGIC = 0x434C5445 # ETLC
|
||||
PROTOCOL_VERSION = 1
|
||||
MAPPING_NAME = r"Local\ETS2LA_Controller"
|
||||
|
||||
INPUT_VALUES = 64
|
||||
INPUT_PULSES = INPUT_VALUES + MAX_INPUTS * 4
|
||||
AXIS_STEERING = 79
|
||||
AXIS_THROTTLE = 80
|
||||
AXIS_BRAKE = 81
|
||||
BUTTON_BLINKER_LEFT = 150
|
||||
BUTTON_BLINKER_RIGHT = 152
|
||||
|
||||
|
||||
def _clip(value, low, high):
|
||||
value = float(value)
|
||||
if not math.isfinite(value):
|
||||
raise ValueError("Non-finite ETS2LA input")
|
||||
return max(low, min(high, value))
|
||||
|
||||
|
||||
def command_axes(steering, action, intensity):
|
||||
"""Translate the native command into ETS2LA semantic axes.
|
||||
|
||||
The native planner uses positive steering for left, while the ATS
|
||||
semantic input uses -1 for left and +1 for right. Pedals are direct
|
||||
0..1 values and the unused pedal is always released.
|
||||
"""
|
||||
if action not in ("throttle", "brake", "coast"):
|
||||
raise ValueError("Unknown ETS2LA pedal action")
|
||||
steering = _clip(steering, -1., 1.)
|
||||
intensity = _clip(intensity, 0., 1.)
|
||||
throttle = intensity if action == "throttle" else 0.
|
||||
brake = intensity if action == "brake" else 0.
|
||||
return -steering, throttle, brake
|
||||
|
||||
|
||||
class ETS2LAController:
|
||||
"""Lock-free writer for the installed ETS2LA controller plugin."""
|
||||
|
||||
def __init__(self, mapping_name=MAPPING_NAME):
|
||||
if os.name != "nt":
|
||||
raise OSError("ETS2LA controller requires Windows")
|
||||
self.mapping_name = mapping_name
|
||||
self.address = 0
|
||||
self.mapping = None
|
||||
self.client_address = 0
|
||||
self.client_id = 0
|
||||
self.last_error = ""
|
||||
self._last_heartbeat = 0.
|
||||
self._counter = int(time.monotonic_ns() & 0xffffffff)
|
||||
self._kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
self._configure_api()
|
||||
self._connect()
|
||||
|
||||
def _configure_api(self):
|
||||
kernel = self._kernel
|
||||
kernel.OpenFileMappingW.argtypes = [ctypes.c_uint32, ctypes.c_int,
|
||||
ctypes.c_wchar_p]
|
||||
kernel.OpenFileMappingW.restype = ctypes.c_void_p
|
||||
kernel.MapViewOfFile.argtypes = [ctypes.c_void_p, ctypes.c_uint32,
|
||||
ctypes.c_uint32, ctypes.c_uint32,
|
||||
ctypes.c_size_t]
|
||||
kernel.MapViewOfFile.restype = ctypes.c_void_p
|
||||
kernel.UnmapViewOfFile.argtypes = [ctypes.c_void_p]
|
||||
kernel.UnmapViewOfFile.restype = ctypes.c_int
|
||||
kernel.CloseHandle.argtypes = [ctypes.c_void_p]
|
||||
kernel.CloseHandle.restype = ctypes.c_int
|
||||
kernel.GetCurrentProcessId.argtypes = []
|
||||
kernel.GetCurrentProcessId.restype = ctypes.c_uint32
|
||||
kernel.GetTickCount64.argtypes = []
|
||||
kernel.GetTickCount64.restype = ctypes.c_uint64
|
||||
kernel.QueryPerformanceCounter.argtypes = [ctypes.POINTER(ctypes.c_int64)]
|
||||
kernel.QueryPerformanceCounter.restype = ctypes.c_int
|
||||
|
||||
def _connect(self):
|
||||
# FILE_MAP_READ | FILE_MAP_WRITE.
|
||||
access = 0x0002 | 0x0004
|
||||
mapping = self._kernel.OpenFileMappingW(access, 0, self.mapping_name)
|
||||
if not mapping:
|
||||
raise RuntimeError(
|
||||
"ETS2LA controller is unavailable; install/load ets2la_controller.dll "
|
||||
"or select the vJoy fallback")
|
||||
address = self._kernel.MapViewOfFile(mapping, access, 0, 0, TOTAL_BYTES)
|
||||
if not address:
|
||||
self._kernel.CloseHandle(mapping)
|
||||
raise RuntimeError("ETS2LA controller mapping could not be mapped")
|
||||
self.mapping, self.address = mapping, int(address)
|
||||
try:
|
||||
magic = ctypes.c_uint32.from_address(self.address).value
|
||||
version = ctypes.c_uint32.from_address(self.address + 4).value
|
||||
if magic != MAGIC or version != PROTOCOL_VERSION:
|
||||
raise RuntimeError("ETS2LA controller protocol version mismatch")
|
||||
self.input_address = self.address + CONTROL_BYTES
|
||||
self.values = (ctypes.c_uint32 * MAX_INPUTS).from_address(
|
||||
self.input_address + INPUT_VALUES)
|
||||
self.pulses = (ctypes.c_uint32 * MAX_INPUTS).from_address(
|
||||
self.input_address + INPUT_PULSES)
|
||||
self.write_qpc = ctypes.c_uint64.from_address(self.input_address)
|
||||
self.write_seq = ctypes.c_uint64.from_address(self.input_address + 8)
|
||||
self.qpc_frequency = ctypes.c_uint64.from_address(self.address + 16).value
|
||||
self._register_client()
|
||||
except Exception:
|
||||
self._disconnect()
|
||||
raise
|
||||
|
||||
def _register_client(self):
|
||||
process_id = int(self._kernel.GetCurrentProcessId())
|
||||
self._counter = (self._counter + 1) & 0xffffffff
|
||||
self.client_id = (process_id << 32) | self._counter
|
||||
now_ms = int(self._kernel.GetTickCount64())
|
||||
start = process_id % MAX_CLIENTS
|
||||
for offset in range(MAX_CLIENTS):
|
||||
index = (start + offset) % MAX_CLIENTS
|
||||
address = self.address + 256 + index * 64
|
||||
identifier = ctypes.c_uint64.from_address(address)
|
||||
heartbeat = ctypes.c_uint64.from_address(address + 8)
|
||||
if identifier.value == 0 or now_ms - heartbeat.value > CLIENT_TIMEOUT_MS * 2:
|
||||
identifier.value = self.client_id
|
||||
heartbeat.value = now_ms
|
||||
self.client_address = address
|
||||
self._last_heartbeat = time.monotonic()
|
||||
return
|
||||
raise RuntimeError("ETS2LA controller has no free client slots")
|
||||
|
||||
def _beat(self, force=False):
|
||||
if not self.client_address:
|
||||
return
|
||||
now = time.monotonic()
|
||||
if not force and now - self._last_heartbeat < HEARTBEAT_INTERVAL_S:
|
||||
return
|
||||
ctypes.c_uint64.from_address(self.client_address + 8).value = int(
|
||||
self._kernel.GetTickCount64())
|
||||
self._last_heartbeat = now
|
||||
|
||||
def _commit(self):
|
||||
counter = ctypes.c_int64()
|
||||
self._kernel.QueryPerformanceCounter(ctypes.byref(counter))
|
||||
self.write_qpc.value = counter.value & 0xffffffffffffffff
|
||||
self.write_seq.value = (self.write_seq.value + 1) & 0xffffffffffffffff
|
||||
self._beat()
|
||||
|
||||
@staticmethod
|
||||
def _float_bits(value):
|
||||
return struct.unpack("<I", struct.pack("<f", float(value)))[0]
|
||||
|
||||
def _set_axis(self, index, value):
|
||||
self.values[index] = self._float_bits(value)
|
||||
|
||||
def apply(self, steering, action, intensity):
|
||||
steering, throttle, brake = command_axes(steering, action, intensity)
|
||||
self._set_axis(AXIS_STEERING, steering)
|
||||
self._set_axis(AXIS_THROTTLE, throttle)
|
||||
self._set_axis(AXIS_BRAKE, brake)
|
||||
self._commit()
|
||||
|
||||
def neutral(self):
|
||||
if not self.address:
|
||||
return
|
||||
self._set_axis(AXIS_STEERING, 0.)
|
||||
self._set_axis(AXIS_THROTTLE, 0.)
|
||||
self._set_axis(AXIS_BRAKE, 0.)
|
||||
self._commit()
|
||||
|
||||
def pulse_signal(self, direction):
|
||||
index = {"left": BUTTON_BLINKER_LEFT, "right": BUTTON_BLINKER_RIGHT}.get(direction)
|
||||
if index is None:
|
||||
raise ValueError("Signal direction must be left or right")
|
||||
self.pulses[index] = (self.pulses[index] + 1) & 0xffffffff
|
||||
self._commit()
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
self.neutral()
|
||||
finally:
|
||||
self._disconnect()
|
||||
|
||||
def _disconnect(self):
|
||||
if self.client_address:
|
||||
identifier = ctypes.c_uint64.from_address(self.client_address)
|
||||
heartbeat = ctypes.c_uint64.from_address(self.client_address + 8)
|
||||
if identifier.value == self.client_id:
|
||||
heartbeat.value = 0
|
||||
identifier.value = 0
|
||||
self.client_address = 0
|
||||
if self.address:
|
||||
self._kernel.UnmapViewOfFile(self.address)
|
||||
self.address = 0
|
||||
if self.mapping:
|
||||
self._kernel.CloseHandle(self.mapping)
|
||||
self.mapping = None
|
||||
|
||||
@property
|
||||
def connected(self):
|
||||
return bool(self.address and self.client_address)
|
||||
@@ -0,0 +1,304 @@
|
||||
"""Bounded lane tracking with analog or telemetry-feedback keyboard actuation."""
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
import numpy as np
|
||||
|
||||
from control.windows_input import KeyboardInput
|
||||
from control.virtual_joystick import VirtualJoystick
|
||||
from control.comfort_cruise import ComfortCruise
|
||||
|
||||
DIK_1, DIK_W, DIK_A, DIK_S, DIK_D = 0x02, 0x11, 0x1E, 0x1F, 0x20
|
||||
DIK_NUMPAD5 = 0x4C
|
||||
DIK_6 = 0x07
|
||||
DIK_LBRACKET = 0x1A
|
||||
DIK_RBRACKET = 0x1B
|
||||
|
||||
|
||||
class FSDController:
|
||||
def __init__(self, mode="keyboard", keyboard=None, start_worker=True, clock=time.monotonic,
|
||||
joystick=None, camera_view="bumper", driving_mode="cruise", owns_joystick=True,
|
||||
focus_confirm_s=0., max_steer_norm=.35):
|
||||
if mode not in ("keyboard", "vjoy", "ets2la", "spf"):
|
||||
raise ValueError("Backend must be keyboard, vjoy, ets2la, or spf")
|
||||
self.mode = mode
|
||||
if not math.isfinite(max_steer_norm) or not .35 <= max_steer_norm <= 1.:
|
||||
raise ValueError('Steering authority must be within 0.35..1.0')
|
||||
self.max_steer_norm = float(max_steer_norm)
|
||||
# DirectML/ATS capture can share the renderer's GPU. Bound an analog
|
||||
# position's lifetime to 500 ms; the continuous WMI runner may opt into
|
||||
# its own bounded host-spike profile. Focus loss still releases at once.
|
||||
self.command_timeout = 0.5 if mode in ("vjoy", "ets2la", "spf") else 0.25
|
||||
if not math.isfinite(focus_confirm_s) or not 0. <= focus_confirm_s <= .15:
|
||||
raise ValueError('Focus confirmation must be within 0..150 ms')
|
||||
self.focus_confirm_s = float(focus_confirm_s)
|
||||
self._focus_missing_since = None
|
||||
self._focus_interruptions = 0
|
||||
self._last_focus_interruption = None
|
||||
if camera_view not in ("bumper", "cabin", "auxiliary"):
|
||||
raise ValueError("Camera must be bumper, cabin, or auxiliary")
|
||||
self.camera_view = camera_view
|
||||
# A native runtime can keep one verified vJoy lease across F8
|
||||
# engagements. Releasing and reacquiring the same device for every
|
||||
# toggle creates a short BUSY window that looks like an autopilot
|
||||
# standby/fault cycle. The default remains owning for existing
|
||||
# callers and tests.
|
||||
self.owns_joystick = bool(owns_joystick)
|
||||
self.kb = keyboard or KeyboardInput()
|
||||
if mode == "vjoy":
|
||||
self.joystick = joystick or VirtualJoystick()
|
||||
elif mode in ("ets2la", "spf"):
|
||||
if joystick is None:
|
||||
if mode == "ets2la":
|
||||
from control.ets2la_controller import ETS2LAController
|
||||
joystick = ETS2LAController()
|
||||
else:
|
||||
from control.spf_native_input import SPFNativeController
|
||||
joystick = SPFNativeController()
|
||||
self.joystick = joystick
|
||||
else:
|
||||
self.joystick = None
|
||||
self.clock = clock
|
||||
self.set_driving_mode(driving_mode)
|
||||
self.wheelbase = 4.5
|
||||
self.max_wheel_angle = math.radians(35)
|
||||
self.max_steer_rate = 0.45
|
||||
self.current_steer = 0.0
|
||||
self.cruise_set_speed = 15.0
|
||||
self.target_time_headway = 2.5
|
||||
self.min_follow_dist = 15.0
|
||||
self.inertial_hold_active = False
|
||||
self.fault = None
|
||||
self._command = None
|
||||
self._last_actuation = None
|
||||
self._last_lateral = self.clock()
|
||||
self._lock = threading.RLock()
|
||||
# Device/Win32 calls may block. They must serialize with neutral, but
|
||||
# must not hold the command mailbox and stall the planner's updates.
|
||||
self._actuator_lock = threading.RLock()
|
||||
self._stop = threading.Event()
|
||||
self._worker = None
|
||||
if start_worker:
|
||||
self._worker = threading.Thread(target=self._run, name="ATS actuators", daemon=True)
|
||||
self._worker.start()
|
||||
|
||||
def reset(self):
|
||||
self.release_all_controls()
|
||||
self.current_steer = 0.0
|
||||
self._last_lateral = self.clock()
|
||||
self.fault = None
|
||||
self.kb.tap_key(DIK_6 if self.camera_view == "bumper" else DIK_1)
|
||||
self.kb.tap_key(DIK_NUMPAD5)
|
||||
|
||||
def pulse_signal(self, direction):
|
||||
"""Toggle the ATS left/right indicator through the verified bindings."""
|
||||
if self.joystick is not None and hasattr(self.joystick, 'pulse_signal'):
|
||||
self.joystick.pulse_signal(direction)
|
||||
return
|
||||
scan = {'left': DIK_LBRACKET, 'right': DIK_RBRACKET}.get(direction)
|
||||
if scan is None:
|
||||
raise ValueError('Signal direction must be left or right')
|
||||
self.kb.tap_key(scan)
|
||||
|
||||
def release_all_controls(self):
|
||||
with self._actuator_lock:
|
||||
with self._lock:
|
||||
self._command = None
|
||||
self._last_actuation = None
|
||||
self._focus_missing_since = None
|
||||
self.cruise.reset()
|
||||
try:
|
||||
self.kb.release_all()
|
||||
finally:
|
||||
if self.joystick:
|
||||
self.joystick.neutral()
|
||||
|
||||
def close(self):
|
||||
self._stop.set()
|
||||
if self._worker:
|
||||
self._worker.join(timeout=1.0)
|
||||
try:
|
||||
self.release_all_controls()
|
||||
finally:
|
||||
if self.joystick and self.owns_joystick:
|
||||
self.joystick.close()
|
||||
|
||||
def vision_reason(self, perception):
|
||||
lanes = perception.lanes
|
||||
if lanes.x is None or not all(np.all(np.isfinite(a)) for a in (lanes.x, lanes.left_y, lanes.right_y)):
|
||||
return "Invalid model lane geometry"
|
||||
if any(np.shape(a) != (33,) for a in (lanes.x, lanes.left_y, lanes.right_y)):
|
||||
return "Invalid model lane geometry"
|
||||
# Lane lines describe the road at known distances even when the model's
|
||||
# time-indexed travel prediction stops or switches hypotheses.
|
||||
width = lanes.right_y[:13] - lanes.left_y[:13]
|
||||
if np.median(width) < 2.2 or np.median(width) > 5.5:
|
||||
return "Lane geometry is not plausible"
|
||||
if lanes.x[0] != 0 or lanes.x[-1] < 25 or np.any(np.diff(lanes.x) <= 0):
|
||||
return "Model lanes have no usable forward extent"
|
||||
center = (lanes.left_y[:13] + lanes.right_y[:13]) * 0.5
|
||||
if np.max(np.abs(center)) > 5.0 or np.any(width <= 0):
|
||||
return "Model lanes leave the forward road"
|
||||
if not all(math.isfinite(v) for v in (lanes.left_prob, lanes.right_prob)):
|
||||
return "Invalid model lane confidence"
|
||||
if min(lanes.left_prob, lanes.right_prob) < 0.35:
|
||||
return "Forward lane markings are not clear"
|
||||
return ""
|
||||
|
||||
def is_vision_valid(self, perception):
|
||||
return not self.vision_reason(perception)
|
||||
|
||||
def engagement_reason(self, perception):
|
||||
reason = self.vision_reason(perception)
|
||||
if reason:
|
||||
return reason
|
||||
if min(perception.lanes.left_prob, perception.lanes.right_prob) < 0.55:
|
||||
return "Forward lane confidence is still stabilizing"
|
||||
return ""
|
||||
|
||||
def compute_lateral(self, perception, current_speed_mps):
|
||||
reason = self.vision_reason(perception)
|
||||
if reason:
|
||||
raise ValueError(reason)
|
||||
now = self.clock()
|
||||
dt = max(0.001, min(0.1, now - self._last_lateral))
|
||||
self._last_lateral = now
|
||||
lookahead = np.clip(current_speed_mps * 1.5, 8.0, 25.0)
|
||||
# Historical model y points right; SCS positive steering points left.
|
||||
lanes = perception.lanes
|
||||
center = (lanes.left_y + lanes.right_y) * 0.5
|
||||
y = -float(np.interp(lookahead, lanes.x, center))
|
||||
curvature = 2.0 * y / (lookahead * lookahead + y * y)
|
||||
target = float(np.clip(math.atan(curvature * self.wheelbase) / self.max_wheel_angle, -0.35, 0.35))
|
||||
self.current_steer += float(np.clip(target - self.current_steer, -self.max_steer_rate * dt, self.max_steer_rate * dt))
|
||||
return self.current_steer
|
||||
|
||||
def set_driving_mode(self, mode):
|
||||
if mode not in ("manual", "cruise", "chill"):
|
||||
raise ValueError("Unsupported driving mode")
|
||||
self.driving_mode = mode
|
||||
self.cruise = ComfortCruise("chill" if mode == "chill" else "cruise", self.clock)
|
||||
|
||||
def compute_longitudinal(self, perception, current_speed_mph):
|
||||
if self.driving_mode == "manual":
|
||||
return "coast", 0.0
|
||||
if not self.is_vision_valid(perception):
|
||||
self.cruise.reset()
|
||||
return "coast", 0.0
|
||||
return self.cruise.compute(self.cruise_set_speed, current_speed_mph, perception.lead)
|
||||
|
||||
def apply_controls(self, steer_norm, long_action, long_intensity, actual_steer=0.0):
|
||||
if not all(math.isfinite(v) for v in (steer_norm, long_intensity, actual_steer)):
|
||||
raise ValueError("Non-finite actuator command")
|
||||
if long_action not in ("throttle", "brake", "coast"):
|
||||
raise ValueError("Unknown pedal action")
|
||||
with self._lock:
|
||||
if self.fault:
|
||||
raise RuntimeError(self.fault)
|
||||
self._command = (float(np.clip(steer_norm, -self.max_steer_norm, self.max_steer_norm)), long_action,
|
||||
float(np.clip(long_intensity, 0.0, 1.0)), actual_steer, self.clock())
|
||||
|
||||
def _tick(self, now=None):
|
||||
now = self.clock() if now is None else now
|
||||
with self._actuator_lock:
|
||||
with self._lock:
|
||||
command = self._command
|
||||
if command is None:
|
||||
return
|
||||
foreground = self.kb.window.foreground()
|
||||
# Accept a newer queued command even if the OS focus query took
|
||||
# time. Evaluate real elapsed time, not the tick's entry time.
|
||||
now = max(now, self.clock())
|
||||
with self._lock:
|
||||
command = self._command
|
||||
if command is None:
|
||||
return
|
||||
age = now - command[4]
|
||||
if foreground:
|
||||
if self._focus_missing_since is not None:
|
||||
self._last_focus_interruption.update(recovered=True,
|
||||
duration_s=now-self._focus_missing_since)
|
||||
self._focus_missing_since = None
|
||||
elif self._focus_missing_since is None:
|
||||
self._focus_missing_since = now
|
||||
self._focus_interruptions += 1
|
||||
self._last_focus_interruption = dict(sampled_at=now, recovered=False, duration_s=0.)
|
||||
if not foreground:
|
||||
self._last_focus_interruption['duration_s'] = now-self._focus_missing_since
|
||||
focus_lost = (not foreground and
|
||||
now-self._focus_missing_since >= self.focus_confirm_s)
|
||||
expired = age > self.command_timeout or focus_lost
|
||||
if expired:
|
||||
self._command = None
|
||||
self.fault = ("Control watchdog: ATS lost focus" if focus_lost else
|
||||
f"Control watchdog: command stalled for {age * 1000:.0f} ms")
|
||||
if expired:
|
||||
self.release_all_controls()
|
||||
return
|
||||
if not foreground:
|
||||
# A single worker check can disagree with the control loop
|
||||
# during a window handoff. Neutralize immediately, preserve
|
||||
# only the existing lease for the bounded confirmation, and
|
||||
# never replay an expired command when focus returns.
|
||||
with self._lock:
|
||||
self._last_actuation = None
|
||||
try:
|
||||
self.kb.release_all()
|
||||
finally:
|
||||
if self.joystick:
|
||||
self.joystick.neutral()
|
||||
return
|
||||
target, action, intensity, actual, _ = command
|
||||
if self.joystick:
|
||||
self.joystick.apply(target, action, intensity)
|
||||
sent = self.clock()
|
||||
with self._lock:
|
||||
first_sent = (self._last_actuation['first_sent_monotonic']
|
||||
if self._last_actuation is not None
|
||||
and self._last_actuation['queued_monotonic'] == command[4] else sent)
|
||||
self._last_actuation = dict(steering=target, action=action, intensity=intensity,
|
||||
queued_monotonic=command[4], first_sent_monotonic=first_sent, sent_monotonic=sent,
|
||||
timing_source='host after successful vJoy write; not SDK acknowledgment')
|
||||
return
|
||||
error = target - actual
|
||||
# SCS steering is positive left. Drive A/D toward measured game steering.
|
||||
phase = (now % 0.1) / 0.1
|
||||
steer_on = abs(error) > 0.012 and phase < min(1.0, abs(error) * 8.0)
|
||||
desired = {DIK_A: steer_on and error > 0, DIK_D: steer_on and error < 0,
|
||||
DIK_W: action == "throttle" and phase < intensity,
|
||||
DIK_S: action == "brake" and phase < intensity}
|
||||
for scan, pressed in desired.items():
|
||||
if not pressed:
|
||||
self.kb.send_key(scan, False)
|
||||
for scan, pressed in desired.items():
|
||||
if pressed:
|
||||
self.kb.send_key(scan, True)
|
||||
|
||||
def actuation_snapshot(self):
|
||||
"""Read-only timing of the last successful write for this command."""
|
||||
with self._lock:
|
||||
if (self._command is None or self._last_actuation is None
|
||||
or self._last_actuation['queued_monotonic'] != self._command[4]):
|
||||
return None
|
||||
return dict(self._last_actuation)
|
||||
|
||||
def focus_status(self):
|
||||
with self._lock:
|
||||
return dict(confirmation_s=self.focus_confirm_s,
|
||||
pending_since=self._focus_missing_since,
|
||||
interruption_count=self._focus_interruptions,
|
||||
last_interruption=(dict(self._last_focus_interruption)
|
||||
if self._last_focus_interruption else None))
|
||||
|
||||
def _run(self):
|
||||
while not self._stop.wait(0.01):
|
||||
try:
|
||||
self._tick()
|
||||
except Exception as exc:
|
||||
with self._lock:
|
||||
self._command = None
|
||||
self.fault = "Actuator failure: " + str(exc)
|
||||
try:
|
||||
self.release_all_controls()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Simulator speed hold and traffic braking; no inference dependency."""
|
||||
import math
|
||||
import numbers
|
||||
|
||||
def _number(value):
|
||||
if isinstance(value, bool) or not isinstance(value, numbers.Real):
|
||||
return None
|
||||
value = float(value)
|
||||
return value if math.isfinite(value) else None
|
||||
|
||||
|
||||
class GameplayCruise:
|
||||
"""Gameplay speed hold with stopping-distance based obstacle braking."""
|
||||
MAX_THROTTLE = 1.
|
||||
MAX_LOAD_INTEGRAL = .65
|
||||
|
||||
def __init__(self, clock):
|
||||
self.clock = clock
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.previous = None
|
||||
self.previous_target = None
|
||||
self.acceleration = self.integral = 0.
|
||||
self.action, self.intensity = 'coast', 0.
|
||||
self.following=None
|
||||
self._slowing = False
|
||||
self.pedal_feedback = None
|
||||
|
||||
def compute(self, target_mph, speed_mph, lead,curve_limited=False, pedal_feedback=None,
|
||||
throttle_ramp_scale=1.0):
|
||||
if any(_number(v) is None or v < 0 for v in (target_mph, speed_mph)):
|
||||
self.reset()
|
||||
raise ValueError('Finite nonnegative gameplay cruise speeds required')
|
||||
now = self.clock()
|
||||
dt = .05
|
||||
if self.previous is not None:
|
||||
elapsed = now-self.previous[0]
|
||||
if 0 < elapsed <= .35:
|
||||
dt = elapsed
|
||||
observed = max(-10., min(5., (speed_mph-self.previous[1])/dt))
|
||||
self.acceleration += dt/(.25+dt)*(observed-self.acceleration)
|
||||
else:
|
||||
self.reset()
|
||||
self.previous = now, speed_mph
|
||||
# Keep tiny curvature jitter from discarding useful hill effort, but
|
||||
# a deliberate lower target must release it even for a sub-mph change.
|
||||
if self.previous_target is not None and target_mph < self.previous_target-.15:
|
||||
self.integral = 0.
|
||||
self.previous_target = target_mph
|
||||
feedback = pedal_feedback if isinstance(pedal_feedback, dict) else {}
|
||||
self.pedal_feedback = {key: _number(feedback.get(key)) for key in
|
||||
('throttle', 'brake', 'user_throttle', 'user_brake')}
|
||||
self.following=None
|
||||
if lead is not None:
|
||||
relative=lead['relative_forward_mps']
|
||||
closing = max(0., -relative)
|
||||
speed=speed_mph*.44704
|
||||
verified=lead.get('motion_verified_for_following') is True
|
||||
lead_speed=max(0.,speed+relative)
|
||||
moving_queue=verified and speed_mph<10. and lead_speed>.5
|
||||
departing=moving_queue and relative>.5
|
||||
standstill_gap=5. if moving_queue else 8.
|
||||
gap=max(standstill_gap,speed*2.5)+closing*.5
|
||||
distance=lead['distance_m']
|
||||
# Relative stopping distance includes response time and leaves the
|
||||
# selected queue buffer. This is a simulator heuristic, not a measured
|
||||
# guarantee of truck braking performance.
|
||||
remaining=max(.1,distance-standstill_gap-closing*.5)
|
||||
required_decel=closing*closing/(2.*remaining)
|
||||
ttc=distance/closing if closing>.1 else None
|
||||
emergency=(distance<=3. or (ttc is not None and ttc<2.) or required_decel>=5.)
|
||||
self.following=dict(gap_m=distance,desired_gap_m=gap,closing_mps=closing,
|
||||
time_to_contact_s=ttc,required_deceleration_mps2=required_decel,
|
||||
emergency=emergency,source=lead.get('source'),
|
||||
departing_lead=departing,lead_speed_mps=lead_speed if verified else None)
|
||||
if emergency or distance < gap or required_decel>1.:
|
||||
self.integral = 0.
|
||||
if emergency or closing > .5 or distance < 8.:
|
||||
self.action = 'brake'
|
||||
self.intensity = (1. if emergency else min(.65,max(.08,
|
||||
required_decel/6.,(gap-distance)*.015)))
|
||||
return self.action, self.intensity
|
||||
self.action, self.intensity = 'coast', 0.
|
||||
return self.action, self.intensity
|
||||
if verified:
|
||||
# Follow the measured vehicle's pace rather than accelerate
|
||||
# toward highway MAX immediately after an eight-metre gap opens.
|
||||
follow_mps=max(0.,lead_speed+(distance-gap)/2.5)
|
||||
target_mph=min(target_mph,follow_mps*2.2369362921)
|
||||
self.following['following_target_mph']=target_mph
|
||||
# Keep the learned load at the target instead of dropping to coast at
|
||||
# a fixed speed-error boundary. Integral action uses actual speed error;
|
||||
# measured acceleration tapers the proportional request in advance.
|
||||
actual_error = target_mph-speed_mph
|
||||
error = target_mph-max(0., speed_mph+.7*self.acceleration)
|
||||
proportional = error/12.
|
||||
raw = proportional+self.integral
|
||||
# Coasting is not a guaranteed deceleration: the Tesla mod can have
|
||||
# very little drag. Enter controlled slowing for actual overspeed,
|
||||
# then release the brake early if measured deceleration will reach the
|
||||
# target. Separate entry/exit bands prevent noisy pedal reversals.
|
||||
if actual_error < -.20 and error < -.08 and (raw <= .025 or error < -1.):
|
||||
self._slowing = True
|
||||
elif actual_error >= -.05:
|
||||
self._slowing = False
|
||||
if self._slowing:
|
||||
self.integral = 0.
|
||||
# Actual pedals can lag a request; a rejected request must not be
|
||||
# mistaken for extra road load and wind up the holding effort.
|
||||
actual_throttle = self.pedal_feedback['throttle']
|
||||
actual_brake = self.pedal_feedback['brake']
|
||||
pedals_tracking = ((actual_throttle is None or self.action != 'throttle'
|
||||
or actual_throttle >= self.intensity-.15)
|
||||
and (actual_brake is None or actual_brake <= .05))
|
||||
# Conditional integration prevents windup at either output limit.
|
||||
if (not self._slowing and pedals_tracking and abs(actual_error) > .08 and
|
||||
((actual_error > 0 and raw < self.MAX_THROTTLE)
|
||||
or (actual_error < 0 and raw > 0))):
|
||||
self.integral = max(0., min(self.MAX_LOAD_INTEGRAL,
|
||||
self.integral+.02*actual_error*dt))
|
||||
braking = (self._slowing and error < -.05) or error < -1.
|
||||
if braking:
|
||||
cap,ramp=(.20,.25) if curve_limited else (.08,.08)
|
||||
duty = min(cap, max(0., (-error-.05)/35.))
|
||||
previous = self.intensity if self.action == 'brake' else 0.
|
||||
self.action, self.intensity = 'brake', min(duty, previous+ramp*dt)
|
||||
elif self._slowing:
|
||||
self.action, self.intensity = 'coast', 0.
|
||||
else:
|
||||
throttle_ramp_scale = max(.25, min(3., _number(throttle_ramp_scale) or 1.))
|
||||
duty = max(0., min(self.MAX_THROTTLE, proportional+self.integral))
|
||||
# Only a tiny requested duty changes pedal mode; this hysteresis
|
||||
# avoids noise toggling throttle/coast while retaining load holding.
|
||||
threshold = .008 if self.action == 'throttle' else .025
|
||||
if duty > threshold:
|
||||
previous = self.intensity if self.action == 'throttle' else 0.
|
||||
ramp = (.5 if duty >= previous else .75) * throttle_ramp_scale
|
||||
self.action, self.intensity = 'throttle', max(previous-ramp*dt,
|
||||
min(duty, previous+ramp*dt))
|
||||
else:
|
||||
self.action, self.intensity = 'coast', 0.
|
||||
return self.action, self.intensity
|
||||
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
"""Signal-requested observed-corridor changes for experimental ATS gameplay.
|
||||
|
||||
No actuator access. Model coordinates are forward/right/down; native actors
|
||||
are forward/left. Empty loaded-actor reports are not a coverage guarantee.
|
||||
Travel identity requires map-count support or a measured same-direction actor,
|
||||
and target truck-footprint clearance inside the estimated physical road edge.
|
||||
"""
|
||||
import math
|
||||
import numbers
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def _finite(value):
|
||||
if isinstance(value, bool) or not isinstance(value, numbers.Real) or not math.isfinite(value):
|
||||
raise ValueError('Finite numeric measurement required')
|
||||
return float(value)
|
||||
|
||||
|
||||
class GameplayLaneChange:
|
||||
SIGNAL_DELAY_S = .5
|
||||
MAX_MANEUVER_S = 8.
|
||||
MAX_AGE_S = .3
|
||||
|
||||
def __init__(self):
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.direction = 'none'
|
||||
self.state = 'idle'
|
||||
self.started = self.active_since = self.last_now = self.last_stamp = None
|
||||
self.used = False
|
||||
self.target = self.previous = None
|
||||
self.centered_since = None
|
||||
self.centered_frames = 0
|
||||
self.cancel_reason = ''
|
||||
|
||||
def cancel(self,reason):
|
||||
"""Caller rejects this admitted path (for example GPS disagreement)."""
|
||||
self.state='cancelled'
|
||||
self.used=True
|
||||
self.cancel_reason=str(reason) or 'Lane change cancelled'
|
||||
return self._report(self.cancel_reason)
|
||||
|
||||
def _report(self, reason='', allowed=False, **extra):
|
||||
report=dict(state=self.state, status=reason or self.state, direction=self.direction,
|
||||
active=self.state == 'changing' and allowed, blocked=bool(reason),
|
||||
allowed_for_gameplay=allowed, reason=reason, path_override=None,
|
||||
desiredpulse='none', completed_corridor=None,
|
||||
require_manual=self.state=='cancelled',
|
||||
source='observed four camera boundaries + measured native actors',
|
||||
experimental=True, production_eligible=False, control_eligible=False,
|
||||
controls_applied=False, physical_calibration_validated=False,
|
||||
clearance_verified=False, lane_identity_verified=False)
|
||||
report.update(extra)
|
||||
return report
|
||||
|
||||
@staticmethod
|
||||
def _geometry(perception, data, now):
|
||||
if (data.get('valid') is not True or data.get('paused') is not False
|
||||
or data.get('model_inferred_this_frame') is not True
|
||||
or data.get('model_obstructed') is not False or data.get('model_geometry_stale') is not False):
|
||||
raise ValueError('Fresh unobstructed camera and SDK required')
|
||||
stamp = _finite(data.get('model_input_monotonic'))
|
||||
if not 0 <= _finite(data.get('model_age_s')) <= .3 or not -.02 <= now-stamp <= .3:
|
||||
raise ValueError('Lane-change camera frame stale')
|
||||
if not 0 <= _finite(data.get('age')) <= .3:
|
||||
raise ValueError('Lane-change SDK stale')
|
||||
speed = _finite(data.get('speed_mps'))
|
||||
if speed < 1 or data.get('park_brake') is not False or data.get('gear', 0) <= 0:
|
||||
raise ValueError('Moving forward gear required for lane change')
|
||||
lanes = perception.lanes
|
||||
x, ys, zs, ps = (np.asarray(getattr(lanes, k), float)
|
||||
for k in ('x', 'all_y', 'all_z', 'probabilities'))
|
||||
if (x.shape != (33,) or ys.shape != (4,33) or zs.shape != (4,33) or ps.shape != (4,)
|
||||
or not all(np.isfinite(a).all() for a in (x,ys,zs,ps))
|
||||
or np.any(np.diff(x)<=0) or x[0] > 0 or x[-1] < 25
|
||||
or np.any((ps<0)|(ps>1))):
|
||||
raise ValueError('Four finite ordered camera boundaries required')
|
||||
position, rotation = (np.asarray(data.get(k),float) for k in ('world_position','world_rotation'))
|
||||
if any(a.shape != (3,) or not np.isfinite(a).all() for a in (position,rotation)):
|
||||
raise ValueError('Finite SDK pose required for corridor continuity')
|
||||
return x,ys,zs,ps,speed,stamp,position,float(rotation[0])*2*math.pi
|
||||
|
||||
@staticmethod
|
||||
def _corridor(x,ys,zs,ps,key,horizon):
|
||||
a,b=key
|
||||
grid=np.unique(np.r_[0.,x[(x>0)&(x<horizon)],horizon])
|
||||
if len(grid)>33:grid=np.linspace(0.,horizon,33)
|
||||
low,high=np.interp(grid,x,ys[a]),np.interp(grid,x,ys[b])
|
||||
width=high-low
|
||||
if min(ps[a],ps[b]) < .6 or np.any(width<2.6) or np.any(width>4.8) or np.ptp(width)>1.2:
|
||||
raise ValueError('Adjacent travel corridor markings or width ambiguous')
|
||||
return dict(key=tuple(key),grid=grid,low=low,high=high,center=(low+high)*.5,
|
||||
z=(np.interp(grid,x,zs[a])+np.interp(grid,x,zs[b]))*.5)
|
||||
|
||||
@staticmethod
|
||||
def _edge(perception,corridor,x):
|
||||
grid=corridor['grid']
|
||||
ex=np.asarray(getattr(perception,'road_edge_x',x),float)
|
||||
edges=np.asarray(perception.road_edges,float)
|
||||
std=np.asarray(perception.road_edge_std,float)
|
||||
if (ex.shape!=(33,) or edges.shape!=(2,33,2) or std.shape!=edges.shape
|
||||
or not all(np.isfinite(a).all() for a in (ex,edges,std))
|
||||
or np.any(np.diff(ex)<=0) or np.any(std<0) or ex[0]>grid[0] or ex[-1]<grid[-1]):
|
||||
raise ValueError('Physical road-edge evidence unavailable')
|
||||
low,high=(np.interp(grid,ex,edges[i,:,0]) for i in (0,1))
|
||||
uncertainty=np.maximum(np.interp(grid,ex,std[0,:,0]),np.interp(grid,ex,std[1,:,0]))
|
||||
margin=np.minimum(corridor['center']-low,high-corridor['center'])-uncertainty
|
||||
if np.any(high<=low) or uncertainty.max()>.75 or margin.min()<1.5:
|
||||
raise ValueError('Shoulder or road-edge corridor ambiguous')
|
||||
return float(margin.min())
|
||||
|
||||
@staticmethod
|
||||
def _traffic(data,now,corridor,speed):
|
||||
report=data.get('nearby_traffic')
|
||||
if not isinstance(report,dict) or report.get('available') is not True:
|
||||
raise ValueError('Fresh all-around native traffic required')
|
||||
age=max(_finite(report.get('age_s')),now-_finite(report.get('sampled_at')))
|
||||
if not 0 <= age <= .3 or report.get('latest_read_failed') is True:
|
||||
raise ValueError('Native traffic verification stale or failed')
|
||||
if (report.get('trailer_chain_traversal_complete') is False
|
||||
or report.get('truncated_trailer_chains')):
|
||||
raise ValueError('Native trailer traversal incomplete; adjacent clearance unknown')
|
||||
actors=report.get('actors')
|
||||
if not isinstance(actors,list) or len(actors)>500:
|
||||
raise ValueError('Native actor list invalid')
|
||||
direction_evidence=False
|
||||
assessments=[]
|
||||
for actor in actors:
|
||||
f,left,length,width,heading=(_finite(actor.get(k)) for k in
|
||||
('forward_m','left_m','length_m','width_m','heading_delta_rad'))
|
||||
if not .2<=length<=60 or not .2<=width<=8:
|
||||
raise ValueError('Native actor footprint invalid')
|
||||
c,s=abs(math.cos(heading)),abs(math.sin(heading))
|
||||
half_f=c*length/2+s*width/2
|
||||
half_y=s*length/2+c*width/2
|
||||
y=-left
|
||||
probe=max(0.,min(float(corridor['grid'][-1]),f))
|
||||
low=np.interp(probe,corridor['grid'],corridor['low'])
|
||||
high=np.interp(probe,corridor['grid'],corridor['high'])
|
||||
rel_f=actor.get('relative_forward_mps')
|
||||
rel_y=actor.get('relative_left_mps')
|
||||
moving=actor.get('motion_available') is True
|
||||
if moving:
|
||||
rel_f=_finite(rel_f);rel_y=-_finite(rel_y)
|
||||
else:
|
||||
rel_f=rel_y=0.
|
||||
lateral_margin=.4+abs(rel_y)*3.
|
||||
overlap=(y+half_y+lateral_margin>=low and y-half_y-lateral_margin<=high)
|
||||
if not overlap:continue
|
||||
# A distant measured tractor/trailer on this corridor is direction
|
||||
# evidence, never an invented lane or a clearance certificate.
|
||||
actor_speed=actor.get('speed_mps')
|
||||
if (moving and actor.get('type') in ('ai','player','ai-trailer','player-trailer')
|
||||
and actor_speed is not None and _finite(actor_speed)>1.
|
||||
and abs(heading)<math.radians(20) and f>0):
|
||||
direction_evidence=True
|
||||
if abs(heading)>math.radians(35) and -60<f<max(50.,speed*4):
|
||||
raise ValueError('Adjacent actor travel direction conflicting')
|
||||
front_gap=f-half_f
|
||||
rear_gap=-f-half_f
|
||||
if f>=0:
|
||||
required=max(25.,speed*2.5)+max(0.,-rel_f)*4.
|
||||
blocked=front_gap<required
|
||||
else:
|
||||
required=35.+max(0.,rel_f)*5.
|
||||
blocked=rear_gap<required
|
||||
if not moving and -80<f<max(60.,speed*4):
|
||||
blocked=True
|
||||
assessments.append(dict(id=actor.get('id'),forward_m=f,footprint_half_forward_m=half_f,
|
||||
front_gap_m=front_gap,rear_gap_m=rear_gap,required_gap_m=required,
|
||||
motion_available=moving,blocked=blocked))
|
||||
if blocked:
|
||||
raise ValueError('Adjacent lane occupied or closing gap unknown: '+str(actor.get('id')))
|
||||
return direction_evidence,assessments,age
|
||||
|
||||
@staticmethod
|
||||
def _travel(data,direction_evidence):
|
||||
geometry=data.get('road_geometry') or data.get('lane_geometry')
|
||||
counts=geometry.get('lane_counts') if isinstance(geometry,dict) and geometry.get('available') is True else None
|
||||
if counts is not None:
|
||||
age=_finite(geometry.get('age_s'))
|
||||
count=counts.get('travel_direction')
|
||||
if not 0<=age<=.5 or type(count) is not int or not 1<=count<=12:
|
||||
raise ValueError('Native travel lane-count evidence stale or invalid')
|
||||
if count<2:
|
||||
raise ValueError('Native road has no adjacent travel lane')
|
||||
if counts.get('opposing_direction',0)>0 and not direction_evidence:
|
||||
raise ValueError('Adjacent travel direction ambiguous on two-way road')
|
||||
return 'native travel lane count + observed truck-footprint road-edge margin'
|
||||
if not direction_evidence:
|
||||
raise ValueError('Adjacent lane versus shoulder/travel direction unassessed')
|
||||
return 'measured same-direction actor + observed truck-footprint road-edge margin'
|
||||
|
||||
def _match_target(self,candidates,position,yaw):
|
||||
old=self.previous
|
||||
if old is None:return candidates[self.target[0]]
|
||||
grid,center,oldpos,oldyaw=old
|
||||
fx,fz=-math.sin(oldyaw),-math.cos(oldyaw)
|
||||
wx=oldpos[0]+grid*fx-center*fz
|
||||
wz=oldpos[2]+grid*fz+center*fx
|
||||
dx,dz=wx-position[0],wz-position[2]
|
||||
fx,fz=-math.sin(yaw),-math.cos(yaw)
|
||||
px,py=dx*fx+dz*fz,-(dx*fz-dz*fx)
|
||||
if np.any(np.diff(px)<=0) or px[-1]<12 or px[0]>12:
|
||||
raise ValueError('Observed target corridor continuity unavailable')
|
||||
expected=np.interp(12.,px,py)
|
||||
scores=sorted((abs(np.interp(12.,c['grid'],c['center'])-expected),i)
|
||||
for i,c in candidates.items())
|
||||
if not scores or scores[0][0]>.9 or (len(scores)>1 and scores[1][0]-scores[0][0]<1.):
|
||||
raise ValueError('Observed adjacent corridor changed ambiguously')
|
||||
return candidates[scores[0][1]]
|
||||
|
||||
def assess(self,perception,telemetry,now=None):
|
||||
now=time.monotonic() if now is None else now
|
||||
try:now=_finite(now)
|
||||
except ValueError:return self._report('Lane-change clock invalid')
|
||||
if self.last_now is not None and now<self.last_now:
|
||||
self.reset();return self._report('Lane-change clock regressed')
|
||||
self.last_now=now
|
||||
left,right=telemetry.get('blinker_left'),telemetry.get('blinker_right')
|
||||
if type(left) is not bool or type(right) is not bool:
|
||||
if self.state=='changing':self.state='cancelled';self.used=True
|
||||
return self._report('Actual SDK turn-signal flags unavailable')
|
||||
if not left and not right:
|
||||
self.reset();return self._report()
|
||||
if telemetry.get('hazards') is True or left and right:
|
||||
self.used=True;self.state='cancelled';return self._report('Hazards cancel lane change')
|
||||
direction='left' if left else 'right'
|
||||
if self.direction=='none':
|
||||
self.direction=direction;self.started=now;self.state='waiting'
|
||||
elif direction!=self.direction:
|
||||
self.used=True;self.state='cancelled';return self._report('Signal must turn off before another maneuver')
|
||||
if self.used and self.state!='changing':
|
||||
return self._report(self.cancel_reason or 'One maneuver consumed; turn signal off to rearm'
|
||||
if self.state!='complete' else '')
|
||||
if telemetry.get('gameplay_engaged') is not True:
|
||||
if self.state=='changing':
|
||||
self.state='cancelled';self.used=True
|
||||
return self._report('Gameplay disengaged; lane change cancelled')
|
||||
return self._report('Turn-signal request pending gameplay engagement')
|
||||
if now-self.started<self.SIGNAL_DELAY_S:
|
||||
return self._report('Waiting for 0.5-second turn-signal delay')
|
||||
try:
|
||||
x,ys,zs,ps,speed,stamp,position,yaw=self._geometry(perception,telemetry,now)
|
||||
if self.last_stamp is not None and stamp<=self.last_stamp:
|
||||
raise ValueError('Distinct fresh lane-change frame required')
|
||||
self.last_stamp=stamp
|
||||
horizon=min(float(x[-1]),max(30.,speed*4.))
|
||||
candidates={}
|
||||
for i in range(3):
|
||||
try:candidates[i]=self._corridor(x,ys,zs,ps,(i,i+1),horizon)
|
||||
except ValueError:pass
|
||||
if self.state!='changing':
|
||||
ego=candidates.get(1)
|
||||
if ego is None or not ego['low'][0]+.25<0<ego['high'][0]-.25:
|
||||
raise ValueError('Ego zero not inside observed central travel corridor')
|
||||
self.target=(0,1) if direction=='left' else (2,3)
|
||||
if self.target[0] not in candidates:
|
||||
raise ValueError('Adjacent observed travel corridor unavailable')
|
||||
target=self._match_target(candidates,position,yaw)
|
||||
edge_margin=self._edge(perception,target,x)
|
||||
direction_evidence,actors,traffic_age=self._traffic(telemetry,now,target,speed)
|
||||
travel_source=self._travel(telemetry,direction_evidence)
|
||||
pulse='none'
|
||||
if self.state!='changing':
|
||||
self.state='changing';self.used=True;self.active_since=now;pulse=direction
|
||||
if now-self.active_since>self.MAX_MANEUVER_S:
|
||||
raise ValueError('Lane-change timeout; manual completion required')
|
||||
self.target=target['key']
|
||||
self.previous=(target['grid'].copy(),target['center'].copy(),position.copy(),yaw)
|
||||
centered=(target['low'][0]+.35<0<target['high'][0]-.35 and abs(target['center'][0])<.45)
|
||||
if centered:
|
||||
if self.centered_since is None:self.centered_since=now;self.centered_frames=0
|
||||
self.centered_frames+=1
|
||||
if self.centered_frames>=3 and now-self.centered_since>=.2:
|
||||
self.state='complete'
|
||||
return self._report(completed_corridor=dict(boundary_indices=list(self.target)),
|
||||
travel_evidence_source=travel_source)
|
||||
else:self.centered_since=None;self.centered_frames=0
|
||||
# Use the observed curved target center throughout. The quintic
|
||||
# blend starts at truck ego zero and meets the measured corridor;
|
||||
# there is no GPS chord, extrapolation, or constant steering offset.
|
||||
distance=max(20.,speed*4.)
|
||||
grid=target['grid']
|
||||
u=np.clip(grid/distance,0.,1.)
|
||||
blend=10*u**3-15*u**4+6*u**5
|
||||
occupied=[c for c in candidates.values() if c['low'][0]<=0<=c['high'][0]]
|
||||
if not occupied:raise ValueError('Ego zero outside observed corridors during maneuver')
|
||||
source=min(occupied,key=lambda c:abs(c['center'][0]))
|
||||
source_curve=np.interp(grid,source['grid'],source['center'])-source['center'][0]
|
||||
selected=source_curve+blend*(target['center']-source_curve)
|
||||
override={axis:np.pad(values,(0,33-len(values)),mode='edge').tolist()
|
||||
for axis,values in zip(('x','y','z'),(grid,selected,target['z']))}
|
||||
return self._report(allowed=True) | dict(
|
||||
path_override=override,desiredpulse=pulse,target_corridor=dict(boundary_indices=list(self.target)),
|
||||
traffic_assessments=actors,traffic_age_s=traffic_age,
|
||||
road_edge_margin_m=edge_margin,travel_evidence_source=travel_source,
|
||||
continuity_reference='SDK pose reprojection of previous observed target center; nominal camera origin',
|
||||
rear_corridor_reference='near observed cross-section; rear road curvature unverified')
|
||||
except (AttributeError,KeyError,TypeError,ValueError,IndexError) as exc:
|
||||
if self.state=='changing':
|
||||
return self.cancel(str(exc))
|
||||
else:self.state='blocked'
|
||||
return self._report(str(exc))
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Simulator lead continuity and a persistent centered camera fallback."""
|
||||
import math
|
||||
|
||||
|
||||
class GameplayLeadGuard:
|
||||
def __init__(self):self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.last_lead=None
|
||||
self.visual=None
|
||||
|
||||
def assess(self,native,perception,data,now):
|
||||
report=data.get('nearby_traffic',{})
|
||||
if not isinstance(report,dict):report={}
|
||||
try:
|
||||
fresh=(report.get('available') is True and report.get('source')=='ATS simulator actors'
|
||||
and 0<=now-float(report['sampled_at'])<=.3 and 0<=float(report.get('age_s',0))<=.3)
|
||||
except (KeyError,TypeError,ValueError):fresh=False
|
||||
chosen=dict(native) if native is not None else None
|
||||
lead=getattr(perception,'lead',None)
|
||||
try:
|
||||
distance,probability,lateral=(float(getattr(lead,key)) for key in
|
||||
('distance','prob','lateral_offset'))
|
||||
speed=float(data['speed_mps'])
|
||||
if (lead.detected is not True or not all(math.isfinite(v) for v in
|
||||
(distance,probability,lateral,speed)) or not 0<distance<100
|
||||
or not .90<=probability<=1 or abs(lateral)>.8):
|
||||
raise ValueError('No confident centered camera lead')
|
||||
previous=self.visual
|
||||
consecutive=(previous is not None and 0<now-previous['at']<=.15
|
||||
and abs(distance-previous['distance'])<=5.+speed*(now-previous['at']))
|
||||
count=previous['count']+1 if consecutive else 1
|
||||
start=previous['start'] if consecutive else now
|
||||
closing=speed
|
||||
if consecutive:
|
||||
measured=max(0.,min(speed+15.,(previous['distance']-distance)/(now-previous['at'])))
|
||||
alpha=(now-previous['at'])/(.2+now-previous['at'])
|
||||
closing=previous['closing']+alpha*(measured-previous['closing'])
|
||||
self.visual=dict(at=now,start=start,distance=distance,count=count,closing=closing)
|
||||
if count>=3 and now-start>=.095:
|
||||
if chosen is None or distance<chosen['distance_m']:
|
||||
matched=(chosen is not None and fresh and chosen.get('motion_estimated') is False
|
||||
and abs(distance-chosen['distance_m'])<=max(5.,chosen['distance_m']*.25))
|
||||
if matched:
|
||||
# Keep measured signed motion when the camera rear agrees
|
||||
# with this actor. Clamping a receding lead to zero closing
|
||||
# loses the evidence needed to resume in a traffic queue.
|
||||
chosen=dict(chosen,distance_m=distance,
|
||||
source='native actor + persistent camera rear',
|
||||
camera_probability=probability,camera_frames=count)
|
||||
else:
|
||||
if chosen is not None:closing=max(closing,-chosen['relative_forward_mps'])
|
||||
chosen=dict(id=chosen.get('id') if chosen else 'camera-lead',distance_m=distance,
|
||||
relative_forward_mps=-closing,motion_estimated=True,
|
||||
source='native actor + persistent camera rear' if native else 'persistent centered camera estimate',
|
||||
lane_association_verified=False,camera_probability=probability,camera_frames=count)
|
||||
except (AttributeError,TypeError,ValueError):self.visual=None
|
||||
held=False
|
||||
if chosen is not None:
|
||||
self.last_lead=dict(chosen,observed_at=now)
|
||||
elif self.last_lead is not None and 0<=now-self.last_lead['observed_at']<=1.:
|
||||
elapsed=now-self.last_lead['observed_at']
|
||||
chosen=dict(self.last_lead,distance_m=max(.1,self.last_lead['distance_m']-
|
||||
max(0.,-self.last_lead['relative_forward_mps'])*elapsed),
|
||||
source='brief lead dropout: estimated gap',held_during_dropout=True)
|
||||
held=True
|
||||
else:self.last_lead=None
|
||||
if chosen is not None:
|
||||
chosen['motion_verified_for_following']=(fresh and not held
|
||||
and chosen.get('motion_estimated') is False)
|
||||
# A bounded foreign trailer walk can retain useful measured obstacle
|
||||
# boxes while omitting an unvisited tail. Freshness of those boxes is
|
||||
# not evidence that the missing tail leaves room to accelerate.
|
||||
truncated=(report.get('trailer_chain_traversal_complete') is False
|
||||
or bool(report.get('truncated_trailer_chains')))
|
||||
return chosen,dict(native_report_fresh=fresh,held_during_dropout=held,
|
||||
visual_frames=self.visual['count'] if self.visual else 0,
|
||||
source=chosen['source'] if chosen else None,lead=chosen,
|
||||
trailer_chain_incomplete=truncated,
|
||||
acceleration_inhibited=truncated or (not fresh and chosen is None))
|
||||
@@ -0,0 +1,541 @@
|
||||
"""Experimental route constraint on a current camera path, without actuators.
|
||||
|
||||
Native GPS graph points supply direction only. They are never lane centers.
|
||||
The only alternative trajectory is a measured, continuously committed camera
|
||||
corridor. This module does not choose another lane, prove clearance or decide
|
||||
intersection priority. The caller uses the same selected plan for steering,
|
||||
curve speed and collision assessment, and retains its existing control gates.
|
||||
"""
|
||||
import math
|
||||
import numbers
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
|
||||
from model.perception import X_IDXS
|
||||
|
||||
|
||||
def _number(value):
|
||||
if isinstance(value, bool) or not isinstance(value, numbers.Real):
|
||||
return None
|
||||
value = float(value)
|
||||
return value if math.isfinite(value) else None
|
||||
|
||||
|
||||
def _angle_error(a, b):
|
||||
return abs(math.atan2(math.sin(a-b), math.cos(a-b)))
|
||||
|
||||
|
||||
class GameplayNavigation:
|
||||
MAX_ROUTE_AGE_S = .5
|
||||
MAX_DIRECTION_HOLD_S = .45
|
||||
MAX_MODEL_AGE_S = .35
|
||||
# Pop's low-speed horizon contracts to roughly four metres. That is
|
||||
# expected while the truck is rolling to a stop, but GPS admission still
|
||||
# needs a small forward window to compare headings.
|
||||
LOW_SPEED_PLAN_EXTENSION_MPS = 7.0
|
||||
MIN_PLAN_COVERAGE_M = 3.0
|
||||
ROUTE_COMPARISON_HORIZON_M = 10.0
|
||||
ROUTE_APPROACH_DISTANCE_M = 120.0
|
||||
MANUAL_JUNCTION_DISTANCE_M = 45.0
|
||||
CORRIDOR_CONFIDENCE = .6
|
||||
MODEL_DIRECTION_LIMIT_RAD = math.radians(20.)
|
||||
CORRIDOR_DIRECTION_LIMIT_RAD = math.radians(8.)
|
||||
COMPLETION_HANDOFF_S = 1.
|
||||
|
||||
def __init__(self, clock=time.monotonic, model_age_s=None):
|
||||
self.clock = clock
|
||||
age = _number(model_age_s) if model_age_s is not None else self.MAX_MODEL_AGE_S
|
||||
if age is None or age <= 0:
|
||||
raise ValueError('Positive navigation model age limit required')
|
||||
self.model_age_limit_s = age
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self._last_now = None
|
||||
self._direction = None
|
||||
self._revision = None
|
||||
self._committed = None
|
||||
self._candidate_key = None
|
||||
self._candidate_since = None
|
||||
self._candidate_samples = 0
|
||||
self._last_input_stamp = None
|
||||
self._last_pose = None
|
||||
self._completion_handoff = None
|
||||
self._completed_key = None
|
||||
self._handoff_status = 'none'
|
||||
self._handoff_provisional = False
|
||||
|
||||
def adopt_committed_corridor(self, boundary_indices):
|
||||
"""Caller acknowledges a completed, explicitly validated lane maneuver.
|
||||
|
||||
Signals or an uncompleted maneuver must never call this method. This
|
||||
acknowledgement changes only the camera boundary identity, not GPS.
|
||||
"""
|
||||
if (not isinstance(boundary_indices, (list, tuple)) or len(boundary_indices) != 2
|
||||
or any(type(i) is not int for i in boundary_indices)
|
||||
or boundary_indices[0] not in (0, 1, 2)
|
||||
or boundary_indices[1] != boundary_indices[0]+1):
|
||||
raise ValueError('Adjacent observed boundary indices required')
|
||||
self._committed = tuple(boundary_indices)
|
||||
self._completed_key = self._committed
|
||||
self._completion_handoff = (dict(deadline=self._last_now+self.COMPLETION_HANDOFF_S,
|
||||
origin=self._last_pose) if self._last_now is not None and self._last_pose is not None else None)
|
||||
self._handoff_status = 'awaiting-renumber' if self._completion_handoff else 'pose-unavailable'
|
||||
self._candidate_key = None
|
||||
self._candidate_since = None
|
||||
self._candidate_samples = 0
|
||||
|
||||
@staticmethod
|
||||
def _report(reason='', **extra):
|
||||
return dict(available=False, allowed_for_gameplay=False, reason=reason,
|
||||
strategy='manual-required', path_override=None,
|
||||
require_manual=True, transient=False, route_revision=None,
|
||||
navigation_phase='route-uncertain', next_bend=None,
|
||||
route_speed_cap_mph=None,
|
||||
direction_evidence=None, committed_corridor=None,
|
||||
gps_direction_held=False, direction_age_s=None, gps_sampled_at=None,
|
||||
automatic_lane_change=False, lane_change_required=False,
|
||||
lane_association_verified=False, clearance_verified=False,
|
||||
intersection_priority_verified=False, experimental=True,
|
||||
production_eligible=False, route_competence_validated=False,
|
||||
**extra)
|
||||
|
||||
@staticmethod
|
||||
def _pose(telemetry):
|
||||
if (not isinstance(telemetry, dict) or telemetry.get('valid') is not True
|
||||
or telemetry.get('position_valid') is not True or telemetry.get('paused') is not False):
|
||||
raise ValueError('Fresh unpaused SDK pose required for route steering')
|
||||
age = _number(telemetry.get('age'))
|
||||
if age is None or not 0 <= age <= .35:
|
||||
raise ValueError('SDK pose is stale for route steering')
|
||||
position, rotation = (np.asarray(telemetry.get(k), float) for k in ('world_position', 'world_rotation'))
|
||||
if any(a.shape != (3,) or not np.isfinite(a).all() for a in (position, rotation)):
|
||||
raise ValueError('Finite SDK position and heading required')
|
||||
yaw = float(rotation[0])*2*math.pi
|
||||
return position, yaw, -math.sin(yaw), -math.cos(yaw)
|
||||
|
||||
def _plan(self, perception, telemetry, now):
|
||||
if (telemetry.get('model_obstructed') is not False or telemetry.get('model_geometry_stale') is not False
|
||||
or telemetry.get('model_inferred_this_frame') is not True):
|
||||
raise ValueError('Fresh unobstructed model geometry required for route steering')
|
||||
age, stamp = _number(telemetry.get('model_age_s')), _number(telemetry.get('model_input_monotonic'))
|
||||
if (age is None or not 0 <= age <= self.model_age_limit_s or stamp is None
|
||||
or not -.05 <= now-stamp <= self.model_age_limit_s):
|
||||
raise ValueError('Model camera geometry is stale for route steering')
|
||||
arrays = [np.asarray(getattr(perception.plan, axis), float) for axis in ('x', 'y', 'z')]
|
||||
if any(a.shape != (33,) or not np.isfinite(a).all() for a in arrays):
|
||||
raise ValueError('Finite current Pop trajectory required')
|
||||
x, y, z = arrays
|
||||
end = 1
|
||||
while end < len(x) and x[end] > x[end-1]+1e-4:
|
||||
end += 1
|
||||
speed = _number(telemetry.get('speed_mps'))
|
||||
if speed is None or speed < -.02:
|
||||
raise ValueError('Finite forward speed required for route steering')
|
||||
coverage = float(x[end-1])
|
||||
if x[0] < 0 or x[0] > 5 or end < 3 or coverage < self.MIN_PLAN_COVERAGE_M:
|
||||
raise ValueError('Current trajectory lacks near-to-forward route comparison')
|
||||
distance = min(max(18., min(45., max(0., speed)*2.5)), coverage)
|
||||
if coverage < self.ROUTE_COMPARISON_HORIZON_M:
|
||||
if speed > self.LOW_SPEED_PLAN_EXTENSION_MPS:
|
||||
raise ValueError('Current trajectory lacks near-to-forward route comparison')
|
||||
# At queue speed Pop intentionally predicts only a short distance.
|
||||
# Extend that measured tangent for GPS admission only; the padded
|
||||
# path is never sent to the actuator as a replacement model path.
|
||||
dx = float(x[end-1]-x[end-2])
|
||||
if not math.isfinite(dx) or dx <= 1e-4:
|
||||
raise ValueError('Current trajectory lacks near-to-forward route comparison')
|
||||
extension = self.ROUTE_COMPARISON_HORIZON_M-coverage
|
||||
slope_y = float((y[end-1]-y[end-2])/dx)
|
||||
slope_z = float((z[end-1]-z[end-2])/dx)
|
||||
x = np.r_[x[:end], self.ROUTE_COMPARISON_HORIZON_M]
|
||||
y = np.r_[y[:end], y[end-1]+slope_y*extension]
|
||||
z = np.r_[z[:end], z[end-1]+slope_z*extension]
|
||||
distance = self.ROUTE_COMPARISON_HORIZON_M
|
||||
return x, y, z, distance, stamp
|
||||
|
||||
@classmethod
|
||||
def _route_state(cls, preview):
|
||||
"""Classify the next graph bend for speed advice and UI state.
|
||||
|
||||
A native GPS node is still not a lane center or a right-of-way signal.
|
||||
This state deliberately stops at an approach/hand-off boundary; it is
|
||||
useful for slowing early and telling the driver what will happen next,
|
||||
but it never creates a turn trajectory.
|
||||
"""
|
||||
state = dict(navigation_phase='route-cruise', next_bend=None,
|
||||
route_speed_cap_mph=None)
|
||||
if not isinstance(preview, dict):
|
||||
return state
|
||||
bend = preview.get('next_bend')
|
||||
if bend is None:
|
||||
return state
|
||||
if not isinstance(bend, dict):
|
||||
return dict(state, navigation_phase='route-uncertain')
|
||||
distance = _number(bend.get('distance_m'))
|
||||
angle = _number(bend.get('angle_deg'))
|
||||
direction = bend.get('direction')
|
||||
if (distance is None or angle is None or distance < 0 or
|
||||
direction not in ('left', 'right')):
|
||||
return dict(state, navigation_phase='route-uncertain')
|
||||
turn = dict(direction=direction, distance_m=distance, angle_deg=angle,
|
||||
distance_units=bend.get('distance_units', 'ATS advisor metres'))
|
||||
magnitude = abs(angle)
|
||||
if distance <= cls.MANUAL_JUNCTION_DISTANCE_M:
|
||||
return dict(state, navigation_phase='manual-junction', next_bend=turn,
|
||||
route_speed_cap_mph=15.0)
|
||||
if distance <= cls.ROUTE_APPROACH_DISTANCE_M or magnitude >= 45.0:
|
||||
# Advisory cap only. It eases speed before the handoff without
|
||||
# pretending the graph supplies a safe intersection trajectory.
|
||||
cap = 50.0 - .35*max(0., magnitude-25.)
|
||||
cap -= .25*max(0., cls.ROUTE_APPROACH_DISTANCE_M-distance)
|
||||
cap = max(15.0, min(45.0, cap))
|
||||
return dict(state, navigation_phase='approach-turn', next_bend=turn,
|
||||
route_speed_cap_mph=cap)
|
||||
return dict(state, next_bend=turn)
|
||||
|
||||
def validate_maneuver_path(self, path, navreport, now=None):
|
||||
"""Route check an independently validated explicit lane-change path.
|
||||
|
||||
This does not validate traffic clearance or generate a maneuver. Only
|
||||
current-corridor selection failures can be waived; GPS/camera failures
|
||||
cannot. The caller retains its lane-change and native collision gates.
|
||||
"""
|
||||
reject=lambda reason:dict(allowed=False,reason=reason)
|
||||
now=_number(self.clock() if now is None else now)
|
||||
if now is None or not isinstance(navreport,dict) or navreport.get('available') is not True:
|
||||
return reject('Valid current GPS direction assessment required')
|
||||
assessed=_number(navreport.get('assessed_at'));sampled=_number(navreport.get('gps_sampled_at'))
|
||||
if (assessed is None or not -.05<=now-assessed<=.15 or sampled is None
|
||||
or not -.05<=now-sampled<=self.MAX_DIRECTION_HOLD_S):
|
||||
return reject('GPS maneuver direction timestamp is stale')
|
||||
waivable=('Model crosses occupied corridor and GPS does not support retaining it',
|
||||
'GPS branch requires a different observed corridor; automatic lane changes unavailable',
|
||||
'GPS and model diverge without a stable aligned committed lane')
|
||||
if navreport.get('allowed_for_gameplay') is not True and navreport.get('reason') not in waivable:
|
||||
return reject('Current GPS/camera admission failure cannot be waived by a signal')
|
||||
try:
|
||||
evidence=navreport['direction_evidence'];horizon=evidence['measured_horizon_m']
|
||||
distance=float(horizon[1]);gps=math.radians(float(evidence['gps_right_heading_deg']))
|
||||
arrays=[np.asarray(path[k] if isinstance(path,dict) else getattr(path,k),float)for k in ('x','y','z')]
|
||||
if any(a.shape!=(33,)or not np.isfinite(a).all()for a in arrays):
|
||||
return reject('Finite measured maneuver path required')
|
||||
x,y,z=arrays;end=1
|
||||
while end<len(x)and x[end]>x[end-1]+1e-4:end+=1
|
||||
x,y,z=x[:end],y[:end],z[:end]
|
||||
if x[0]>5 or x[0]<0 or x[-1]<distance or distance<10:
|
||||
return reject('Maneuver path lacks measured route comparison coverage')
|
||||
heading=math.atan2(float(np.interp(distance,x,y)-np.interp(5.,x,y)),distance-5.)
|
||||
error=_angle_error(heading,gps)
|
||||
if error>self.MODEL_DIRECTION_LIMIT_RAD:
|
||||
return reject('Requested lane-change path conflicts with the GPS branch')
|
||||
return dict(allowed=True,reason='',gps_direction_age_s=max(0.,now-sampled),
|
||||
gps_sampled_at=sampled,heading_error_deg=math.degrees(error),
|
||||
current_corridor_guard_waived=navreport.get('allowed_for_gameplay') is not True,
|
||||
clearance_verified=False)
|
||||
except (ValueError,KeyError,TypeError,AttributeError,IndexError,OverflowError):
|
||||
return reject('Malformed GPS maneuver direction or path')
|
||||
|
||||
def _fresh_direction(self, route, preview, telemetry, position, fx, fz, distance, now):
|
||||
if telemetry.get('navigation_valid') is not True:
|
||||
raise ValueError('Native GPS telemetry unavailable')
|
||||
if not isinstance(route, dict) or route.get('available') is not True:
|
||||
raise ValueError('Native GPS route unavailable')
|
||||
if (route.get('geometry_kind') != 'native-route-node-array'
|
||||
or route.get('lead_in') is not None or not isinstance(preview, dict)
|
||||
or preview.get('lead_in_estimated') or preview.get('segment_kind') != 'native-node-pair'):
|
||||
raise ValueError('Estimated GPS lead-in or unverified route geometry cannot guide steering')
|
||||
age, sampled = _number(route.get('age_s')), _number(route.get('sampled_at'))
|
||||
if (age is None or not 0 <= age <= self.MAX_ROUTE_AGE_S or sampled is None
|
||||
or not -.05 <= now-sampled <= self.MAX_ROUTE_AGE_S):
|
||||
raise ValueError('Native GPS route is stale')
|
||||
if preview.get('available') is not True or preview.get('reason'):
|
||||
raise ValueError(preview.get('reason') or 'Native GPS route matching unavailable')
|
||||
if preview.get('revision') != route.get('revision') or not route.get('revision'):
|
||||
raise ValueError('GPS route revision and match disagree')
|
||||
nodes, segment = route.get('nodes'), preview.get('segment')
|
||||
if (not isinstance(nodes, list) or not 2 <= len(nodes) <= 1024
|
||||
or type(segment) is not int or not 0 <= segment < len(nodes)-1):
|
||||
raise ValueError('Invalid directed native GPS route segment')
|
||||
points = []
|
||||
for node in nodes:
|
||||
point = np.asarray(node.get('position'), float)
|
||||
if point.shape != (3,) or not np.isfinite(point).all() or node.get('uid') is None:
|
||||
raise ValueError('Invalid native GPS endpoint identity/position')
|
||||
points.append(point)
|
||||
a, b = points[segment:segment+2]
|
||||
delta = b-a; length2 = delta[0]**2+delta[2]**2
|
||||
if length2 < 1 or str(nodes[segment]['uid']) == str(nodes[segment+1]['uid']):
|
||||
raise ValueError('Directed native GPS pair has no usable extent')
|
||||
t = float(np.clip(((position[0]-a[0])*delta[0]+(position[2]-a[2])*delta[2])/length2, 0, 1))
|
||||
projection = a+t*delta
|
||||
error = float(np.linalg.norm((projection-position)[[0, 2]]))
|
||||
heading = float((fx*delta[0]+fz*delta[2])/math.sqrt(length2))
|
||||
progress = _number(preview.get('progress_error_m'))
|
||||
if error > 18 or abs(projection[1]-position[1]) > 4 or heading < .5 or progress is None or not 0 <= progress <= 500:
|
||||
raise ValueError('Truck does not match the directed GPS route')
|
||||
# Keep the actual projected graph point, including its lateral offset.
|
||||
# The offset cancels in the tangent calculation; no synthetic (0,0)
|
||||
# graph lead-in or graph-center lateral steering term is introduced.
|
||||
ego = []
|
||||
for point in [projection]+points[segment+1:]:
|
||||
dx, dz = point[0]-position[0], point[2]-position[2]
|
||||
sample = [dx*fx+dz*fz, dx*fz-dz*fx]
|
||||
if ego and abs(sample[0]-ego[-1][0]) < 1e-5 and abs(sample[1]-ego[-1][1]) < 1e-5:
|
||||
continue
|
||||
if ego and sample[0] <= ego[-1][0]+1e-5:
|
||||
break
|
||||
ego.append(sample)
|
||||
if sample[0] >= distance:
|
||||
break
|
||||
curve = np.asarray(ego, float)
|
||||
if len(curve) < 2 or curve[0, 0] > 5 or curve[-1, 0] < distance:
|
||||
raise ValueError('Native GPS direction has insufficient forward coverage')
|
||||
lateral_change = float(np.interp(distance, curve[:,0],curve[:,1])-np.interp(5.,curve[:,0],curve[:,1]))
|
||||
slope_left = lateral_change/(distance-5.)
|
||||
angle = -math.atan(slope_left) # model right-positive; GPS left-positive.
|
||||
if abs(angle) > math.radians(45):
|
||||
raise ValueError('Sharp route turn requires manual junction handling')
|
||||
# Save a world-space direction. Brief holds rotate it with the current
|
||||
# truck heading instead of pretending an old relative angle is fresh.
|
||||
world = np.array([fx+fz*slope_left, fz-fx*slope_left])
|
||||
world /= np.linalg.norm(world)
|
||||
return dict(right_heading_rad=angle, world_direction=world.tolist(),
|
||||
sampled_at=sampled, revision=route['revision'],
|
||||
pair_uids=[str(nodes[segment]['uid']),str(nodes[segment+1]['uid'])],
|
||||
measured_horizon_m=[5.,distance], graph_offset_world_m=error,
|
||||
graph_offset_used_for_steering=False)
|
||||
|
||||
@staticmethod
|
||||
def _corridors(perception, x, y, distance):
|
||||
lanes = getattr(perception,'lanes',None)
|
||||
try:
|
||||
lx=np.asarray(getattr(lanes,'x',None),float)
|
||||
ys=np.asarray(getattr(lanes,'all_y',None),float)
|
||||
ps=np.asarray(getattr(lanes,'probabilities',None),float)
|
||||
except (TypeError,ValueError):
|
||||
return []
|
||||
if (lx.shape!=(33,) or ys.shape!=(4,33) or ps.shape!=(4,) or not np.isfinite(lx).all()
|
||||
or not np.isfinite(ys).all() or not np.isfinite(ps).all() or np.any(np.diff(lx)<=0)
|
||||
or np.any((ps<0)|(ps>1)) or lx[0]>5 or lx[-1]<distance):
|
||||
return []
|
||||
grid=np.unique(np.r_[5.,lx[(lx>5.)&(lx<distance)],distance])
|
||||
# Ego zero identifies the occupied corridor. A wandering network plan
|
||||
# is not evidence that the truck has already changed lanes.
|
||||
near=float(np.clip(np.interp(5.,x,y), -.5, .5));candidates=[]
|
||||
for left in range(3):
|
||||
right=left+1
|
||||
confidence=float(min(ps[left],ps[right]))
|
||||
if confidence<.6:continue
|
||||
low=np.interp(grid,lx,ys[left]);high=np.interp(grid,lx,ys[right]);width=high-low
|
||||
if np.any(width<2.3) or np.any(width>5.5) or np.ptp(width)>1.5 or np.any(np.abs(low)>25) or np.any(np.abs(high)>25):continue
|
||||
center=(low+high)*.5
|
||||
if not low[0]+.3<0.<high[0]-.3:continue
|
||||
near=float(np.clip(near, low[0]+.35, high[0]-.35))
|
||||
offset=near-center[0]
|
||||
selected=center+offset
|
||||
if np.any(np.minimum(selected-low,high-selected)<.3):continue
|
||||
heading=math.atan2(float(center[-1]-center[0]),distance-5.)
|
||||
candidates.append(dict(key=(left,right),confidence=confidence,lane_x=lx,
|
||||
center=(ys[left]+ys[right])*.5,offset=float(offset),heading=heading,
|
||||
low=low,high=high,grid=grid,near_anchor=near))
|
||||
return candidates
|
||||
|
||||
@staticmethod
|
||||
def _edge_evidence(perception, grid, selected):
|
||||
"""Predicted edge proximity is caution, not proof of painted-lane type."""
|
||||
try:
|
||||
ex=np.asarray(getattr(perception,'road_edge_x',X_IDXS),float)
|
||||
edges=np.asarray(perception.road_edges,float)
|
||||
std=np.asarray(perception.road_edge_std,float)
|
||||
except (AttributeError,TypeError,ValueError):
|
||||
return dict(available=False,reason='Predicted road-edge evidence unavailable')
|
||||
if (ex.shape!=(33,) or edges.shape!=(2,33,2) or std.shape!=(2,33,2)
|
||||
or not all(np.isfinite(a).all() for a in (ex,edges,std))
|
||||
or np.any(np.diff(ex)<=0) or np.any(std<0) or ex[0]>grid[0] or ex[-1]<grid[-1]):
|
||||
return dict(available=False,reason='Predicted road-edge evidence malformed')
|
||||
lo=np.interp(grid,ex,edges[0,:,0]);hi=np.interp(grid,ex,edges[1,:,0])
|
||||
sigma=np.maximum(np.interp(grid,ex,std[0,:,0]),np.interp(grid,ex,std[1,:,0]))
|
||||
if np.any(hi<=lo) or np.max(sigma)>1.:
|
||||
return dict(available=False,reason='Predicted road edges uncertain or crossed')
|
||||
clearance=float(np.min(np.minimum(selected-lo,hi-selected)-sigma))
|
||||
return dict(available=True,minimum_predicted_edge_margin_m=clearance,
|
||||
near_edge=clearance<.65,road_edge_identity_verified=False)
|
||||
|
||||
def _commit(self, candidates, stamp, now):
|
||||
self._handoff_provisional=False
|
||||
handoff=self._completion_handoff
|
||||
if handoff is not None:
|
||||
origin_position,origin_yaw=handoff['origin']
|
||||
position,yaw=self._last_pose
|
||||
continuous=(float(np.linalg.norm((position-origin_position)[[0,2]]))<=30.
|
||||
and abs(float(position[1]-origin_position[1]))<=1.5
|
||||
and _angle_error(yaw,origin_yaw)<=math.radians(12.))
|
||||
if now>handoff['deadline'] or not continuous:
|
||||
self._handoff_status='expired' if now>handoff['deadline'] else 'pose-discontinuous'
|
||||
self._completion_handoff=None;handoff=None
|
||||
self._candidate_key=None;self._candidate_since=None;self._candidate_samples=0
|
||||
if len(candidates)!=1:
|
||||
self._candidate_key=None;self._candidate_since=None;self._candidate_samples=0
|
||||
return None
|
||||
candidate=candidates[0];key=candidate['key']
|
||||
if self._committed is not None:
|
||||
if key==self._committed:return candidate
|
||||
if handoff is None:return None
|
||||
# A validated completion can be followed by camera index
|
||||
# renumbering. Rewarm the one measured ego-containing corridor
|
||||
# within a short, pose-continuous window. Its boundary guard stays
|
||||
# active provisionally; persistent identity changes only after
|
||||
# three distinct observations, not from a signal or stale frame.
|
||||
self._handoff_provisional=True
|
||||
self._handoff_status='renumber-warming'
|
||||
if key!=self._candidate_key:
|
||||
self._candidate_key=key;self._candidate_since=now;self._candidate_samples=0
|
||||
if self._last_input_stamp is None or stamp>self._last_input_stamp:
|
||||
self._candidate_samples+=1
|
||||
if self._candidate_samples>=3 and now-self._candidate_since>=.1:
|
||||
self._committed=key
|
||||
if handoff is not None:
|
||||
self._completion_handoff=None;self._handoff_status='renumbered'
|
||||
self._handoff_provisional=False
|
||||
return candidate
|
||||
if handoff is not None:return candidate
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _override(x,y,z,corridor,distance):
|
||||
selected_x=np.r_[x[x<distance],distance]
|
||||
if len(selected_x)>33:
|
||||
selected_x=selected_x[:32];selected_x=np.r_[selected_x,distance]
|
||||
center=np.interp(selected_x,corridor['lane_x'],corridor['center'])+corridor['offset']
|
||||
near=selected_x<5.
|
||||
# Do not preserve an already wandering near-model anchor during a
|
||||
# boundary intervention. Bound it to the ego vicinity and measured
|
||||
# corridor rather than creating an early shoulder excursion.
|
||||
center[near]=np.clip(np.interp(selected_x[near],x,y),-.5,.5)
|
||||
# Candidate bounds were evaluated on the measured grid; use them only
|
||||
# at/after5m, never extrapolate a road boundary toward the truck.
|
||||
far=selected_x>=5.
|
||||
center[far]=np.clip(center[far],np.interp(selected_x[far],corridor['grid'],corridor['low'])+.3,
|
||||
np.interp(selected_x[far],corridor['grid'],corridor['high'])-.3)
|
||||
selected_z=np.interp(selected_x,x,z)
|
||||
# Pad with an exact repeated endpoint. Existing steering/collision
|
||||
# geometry stops at the first non-increasing x; no inferred continuation
|
||||
# beyond the observed, validated corridor is supplied.
|
||||
return {axis:np.pad(values,(0,33-len(values)),mode='edge').tolist()
|
||||
for axis,values in zip(('x','y','z'),(selected_x,center,selected_z))}
|
||||
|
||||
def assess(self, perception, telemetry, route, preview, now=None):
|
||||
now=_number(self.clock() if now is None else now)
|
||||
if now is None or (self._last_now is not None and now<self._last_now):
|
||||
self.reset();return self._report('Navigation clock unavailable or regressed')
|
||||
self._last_now=now
|
||||
route_state=self._route_state(preview)
|
||||
try:
|
||||
position,yaw,fx,fz=self._pose(telemetry)
|
||||
x,y,z,distance,stamp=self._plan(perception,telemetry,now)
|
||||
self._last_pose=(position.copy(),yaw)
|
||||
route_revision=route.get('revision') if isinstance(route,dict) else None
|
||||
if route_revision and route_revision!=self._revision:
|
||||
self._direction=None;self._committed=None;self._candidate_key=None
|
||||
self._candidate_since=None;self._candidate_samples=0;self._revision=route_revision
|
||||
self._completion_handoff=None;self._completed_key=None;self._handoff_status='none'
|
||||
held=False;route_reason=''
|
||||
try:
|
||||
direction=self._fresh_direction(route,preview,telemetry,position,fx,fz,distance,now)
|
||||
self._direction=direction
|
||||
except (ValueError,KeyError,TypeError,IndexError) as exc:
|
||||
route_reason=str(exc)
|
||||
# A changed/estimated representation must never inherit the
|
||||
# previous native route. Holds cover only short unavailable or
|
||||
# stale reader samples on the same route/unknown revision.
|
||||
incompatible=(isinstance(route,dict) and (route.get('lead_in') is not None
|
||||
or route.get('geometry_kind') not in (None,'native-route-node-array')))
|
||||
incompatible=incompatible or (isinstance(preview,dict) and (preview.get('lead_in_estimated')
|
||||
or preview.get('segment_kind') not in (None,'native-node-pair')))
|
||||
# Definitive geometric disagreement is not a dropped sample.
|
||||
incompatible=incompatible or route_reason in (
|
||||
'Truck does not match the directed GPS route',
|
||||
'Sharp route turn requires manual junction handling',
|
||||
'GPS route revision and match disagree')
|
||||
if (incompatible or self._direction is None
|
||||
or not 0<=now-self._direction['sampled_at']<=self.MAX_DIRECTION_HOLD_S):
|
||||
result=self._report(route_reason)
|
||||
result.update(route_state)
|
||||
if self._direction is not None:
|
||||
result.update(gps_hold_expired=now-self._direction['sampled_at']>self.MAX_DIRECTION_HOLD_S,
|
||||
direction_age_s=max(0.,now-self._direction['sampled_at']),
|
||||
gps_sampled_at=self._direction['sampled_at'],
|
||||
hold_deadline_monotonic=self._direction['sampled_at']+self.MAX_DIRECTION_HOLD_S)
|
||||
return result
|
||||
direction=dict(self._direction);world=direction['world_direction']
|
||||
forward=world[0]*fx+world[1]*fz;left=world[0]*fz-world[1]*fx
|
||||
if forward<.7:return self._report('Held GPS direction no longer agrees with truck heading')
|
||||
direction['right_heading_rad']=-math.atan2(left,forward);held=True
|
||||
candidates=self._corridors(perception,x,y,distance)
|
||||
corridor=self._commit(candidates,stamp,now)
|
||||
self._last_input_stamp=stamp
|
||||
model_heading=math.atan2(float(np.interp(distance,x,y)-np.interp(5.,x,y)),distance-5.)
|
||||
gps_heading=direction['right_heading_rad'];model_error=_angle_error(model_heading,gps_heading)
|
||||
result=self._report()
|
||||
result.update(route_state,available=True,allowed_for_gameplay=True,require_manual=False,
|
||||
assessed_at=now,
|
||||
strategy='camera-path-follows-gps',reason='',route_revision=direction['revision'],
|
||||
gps_direction_held=held,direction_age_s=max(0.,now-direction['sampled_at']),
|
||||
gps_sampled_at=direction['sampled_at'],
|
||||
completed_corridor_boundary_indices=list(self._completed_key) if self._completed_key else None,
|
||||
corridor_identity_handoff=self._handoff_status,
|
||||
direction_evidence=dict(model_right_heading_deg=math.degrees(model_heading),
|
||||
gps_right_heading_deg=math.degrees(gps_heading),model_error_deg=math.degrees(model_error),
|
||||
measured_horizon_m=[5.,distance],native_pair_uids=direction['pair_uids'],
|
||||
graph_offset_world_m=direction['graph_offset_world_m'],graph_offset_used_for_steering=False,
|
||||
held_reader_reason=route_reason if held else ''))
|
||||
if (self._committed is not None and corridor is None and len(candidates)==1
|
||||
and candidates[0]['key']!=self._committed):
|
||||
result.update(allowed_for_gameplay=False,require_manual=True,lane_change_required=True,
|
||||
strategy='manual-required',
|
||||
reason='GPS branch requires a different observed corridor; automatic lane changes unavailable')
|
||||
return result
|
||||
if corridor is not None:
|
||||
result['committed_corridor']=dict(boundary_indices=list(corridor['key']),confidence=corridor['confidence'],
|
||||
identity_handoff_pending=self._handoff_provisional)
|
||||
corridor_error=_angle_error(corridor['heading'],gps_heading)
|
||||
result['direction_evidence']['corridor_error_deg']=math.degrees(corridor_error)
|
||||
plan=np.interp(corridor['grid'],x,y)
|
||||
inside=np.minimum(plan-corridor['low'],corridor['high']-plan)
|
||||
crossed_boundary=float(np.min(inside))<.25
|
||||
result['committed_corridor'].update(estimated=True,travel_lane_identity_verified=False,
|
||||
minimum_model_boundary_margin_m=float(np.min(inside)))
|
||||
selected=np.interp(corridor['grid'],corridor['lane_x'],corridor['center'])+corridor['offset']
|
||||
edge=self._edge_evidence(perception,corridor['grid'],selected)
|
||||
result['road_edge_caution']=edge
|
||||
if edge.get('near_edge'):
|
||||
result.update(allowed_for_gameplay=False,require_manual=True,strategy='manual-required',
|
||||
reason='Occupied observed corridor approaches an uncertain road edge or shoulder')
|
||||
return result
|
||||
if corridor_error<=self.CORRIDOR_DIRECTION_LIMIT_RAD and (crossed_boundary or model_error>self.MODEL_DIRECTION_LIMIT_RAD):
|
||||
if corridor['key']!=(1,2) and not edge.get('available'):
|
||||
result.update(allowed_for_gameplay=False,require_manual=True,strategy='manual-required',
|
||||
reason='Outer observed corridor lacks road-edge evidence; travel lane versus shoulder unknown')
|
||||
return result
|
||||
result.update(strategy='gps-committed-camera-corridor',
|
||||
path_override=self._override(x,y,z,corridor,distance),
|
||||
reason='Retaining the occupied observed corridor against a predicted boundary crossing')
|
||||
return result
|
||||
if crossed_boundary:
|
||||
result.update(allowed_for_gameplay=False,require_manual=True,strategy='manual-required',
|
||||
reason='Model crosses occupied corridor and GPS does not support retaining it')
|
||||
return result
|
||||
if model_error<=self.MODEL_DIRECTION_LIMIT_RAD:
|
||||
return result
|
||||
other_aligned=any(_angle_error(candidate['heading'],gps_heading)<=self.CORRIDOR_DIRECTION_LIMIT_RAD
|
||||
for candidate in candidates)
|
||||
result.update(allowed_for_gameplay=False,require_manual=True,strategy='manual-required',
|
||||
transient=self._committed is None and other_aligned,
|
||||
lane_change_required=self._committed is not None and other_aligned,
|
||||
reason=('GPS branch requires a different observed corridor; automatic lane changes unavailable' if self._committed is not None and other_aligned
|
||||
else 'GPS and model diverge without a stable aligned committed lane'))
|
||||
return result
|
||||
except (ValueError,KeyError,TypeError,AttributeError,IndexError,OverflowError) as exc:
|
||||
return self._report(str(exc))
|
||||
@@ -0,0 +1,425 @@
|
||||
"""Track an observed ego lane, including brief paint gaps, without actuators.
|
||||
|
||||
The model's four line slots are candidates, not permanent lane identities.
|
||||
A committed lane is compared in world space so an adjacent line pair cannot
|
||||
silently become the steering target. Explicit validated maneuvers own their path.
|
||||
"""
|
||||
import copy
|
||||
import math
|
||||
import numpy as np
|
||||
|
||||
from model.perception import X_IDXS
|
||||
|
||||
|
||||
class GameplayRoadTracking:
|
||||
HOLD_S = 1.
|
||||
ROUTE_RECOVERY_S = 2.
|
||||
# A paint dropout should not turn a valid, route-aligned model path into
|
||||
# an emergency stop. This is deliberately a bounded laneless recovery:
|
||||
# it is only available at moderate speed, with a fresh route admission,
|
||||
# low predicted lateral uncertainty, and a path that remains close to the
|
||||
# current lane. At higher speed or near a junction the existing braking
|
||||
# handoff remains the safer behaviour.
|
||||
LANELESS_MAX_SPEED_MPS = 18.0
|
||||
LANELESS_MAX_PATH_STD_M = 1.0
|
||||
LANELESS_MAX_HEADING_ERROR_DEG = 6.0
|
||||
LANELESS_CRAWL_HEADING_ERROR_DEG = 12.0
|
||||
|
||||
def __init__(self):
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.world = self.seen = self.candidate = self.candidate_since = None
|
||||
self.count = 0
|
||||
self.lost = False
|
||||
self.verified_route_revision = None
|
||||
self.observed_speed_mph = None
|
||||
self.reacquire_world = self.reacquire_since = self.reacquire_at = None
|
||||
self.reacquire_count = 0
|
||||
|
||||
@staticmethod
|
||||
def pose(data):
|
||||
try:
|
||||
p = np.asarray(data['world_position'], float)[[0, 2]]
|
||||
yaw = float(data['world_rotation'][0])*2*math.pi
|
||||
if data.get('position_valid') is not True or not np.isfinite(p).all() or not math.isfinite(yaw):
|
||||
return None
|
||||
# Model coordinates are forward/right; SDK horizontal axes are X/Z.
|
||||
basis = np.array([[-math.sin(yaw), -math.cos(yaw)],
|
||||
[math.cos(yaw), -math.sin(yaw)]])
|
||||
return p, basis
|
||||
except (KeyError, TypeError, ValueError, IndexError):
|
||||
return None
|
||||
|
||||
def projected(self, pose):
|
||||
if pose is None or self.world is None:
|
||||
return None
|
||||
p, basis = pose
|
||||
points = (self.world-p)@basis.T
|
||||
if not np.isfinite(points).all() or np.any(np.diff(points[:, 0]) <= 0):
|
||||
return None
|
||||
return points
|
||||
|
||||
@staticmethod
|
||||
def candidates(perception):
|
||||
try:
|
||||
lanes = perception.lanes
|
||||
x, ys, probs = (np.asarray(getattr(lanes, k), float) for k in ('x', 'all_y', 'probabilities'))
|
||||
if (x.shape != (33,) or ys.shape != (4, 33) or probs.shape != (4,)
|
||||
or not all(np.isfinite(a).all() for a in (x, ys, probs))
|
||||
or np.any(np.diff(x) <= 0) or x[0] > 3 or x[-1] < 30
|
||||
or np.any((probs < 0) | (probs > 1))):
|
||||
return []
|
||||
grid = np.unique(np.r_[3., x[(x > 3) & (x < 30)], 30.])
|
||||
result = []
|
||||
for i in range(3):
|
||||
if min(probs[i:i+2]) < .65:
|
||||
continue
|
||||
left, right = (np.interp(grid, x, ys[j]) for j in (i, i+1))
|
||||
width = right-left
|
||||
if (np.any((width < 2.8) | (width > 4.5)) or np.ptp(width) > .8
|
||||
or not left[0]+.2 < 0 < right[0]-.2):
|
||||
continue
|
||||
# Keep more observed coverage for motion propagation, but do
|
||||
# not use the far forecast for the lane-centering controller.
|
||||
keep = x <= 60.
|
||||
result.append((i, np.column_stack((x[keep], ((ys[i]+ys[i+1])*.5)[keep]))))
|
||||
return result
|
||||
except (AttributeError, TypeError, ValueError, IndexError):
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def selected(perception, points):
|
||||
selected = copy.copy(perception)
|
||||
selected.plan = copy.copy(perception.plan)
|
||||
old_x = np.asarray(perception.plan.x)
|
||||
# Never extend a held corridor beyond the road that was observed.
|
||||
x = np.linspace(max(0., float(points[0, 0])), min(30., float(points[-1, 0])), 33)
|
||||
selected.plan.x = x
|
||||
selected.plan.y = np.interp(x, points[:, 0], points[:, 1])
|
||||
if hasattr(perception.plan, 'z'):
|
||||
selected.plan.z = np.interp(x, old_x, perception.plan.z)
|
||||
return selected
|
||||
|
||||
@staticmethod
|
||||
def _fresh_route(data, now):
|
||||
navigation = data.get('navigation_driver') or {}
|
||||
if (not isinstance(navigation, dict) or navigation.get('allowed_for_gameplay') is not True
|
||||
or navigation.get('require_manual') is True
|
||||
or navigation.get('navigation_phase') in ('manual-junction', 'route-uncertain')
|
||||
or not navigation.get('route_revision')):
|
||||
return None
|
||||
try:
|
||||
assessed, sampled = (float(navigation[key]) for key in ('assessed_at', 'gps_sampled_at'))
|
||||
error = float(navigation['direction_evidence']['model_error_deg'])
|
||||
if (not all(math.isfinite(v) for v in (assessed, sampled, error))
|
||||
or not -.05 <= now-assessed <= .35
|
||||
or not -.05 <= now-sampled <= .45 or abs(error) > 6.):
|
||||
return None
|
||||
return navigation['route_revision']
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
|
||||
def _temporary_recovery(self, perception, data, now, old, candidates):
|
||||
"""Use only the remaining observed lane through a short confidence dip.
|
||||
|
||||
GPS cannot supply lane geometry. A matching route must have been fresh
|
||||
when the lane was actually observed, and remain fresh now. Neither
|
||||
repeated uncertain frames nor route updates extend that observation's
|
||||
deadline. Current model/ego disagreement revokes the hold immediately.
|
||||
"""
|
||||
age = now-self.seen if self.seen is not None else math.inf
|
||||
if (not .35 < age <= self.ROUTE_RECOVERY_S or old is None or candidates
|
||||
or self.verified_route_revision is None or self.observed_speed_mph is None
|
||||
or self._fresh_route(data, now) != self.verified_route_revision):
|
||||
return None
|
||||
try:
|
||||
speed = float(data['speed_mps'])
|
||||
x, y = (np.asarray(getattr(perception.plan, key), float) for key in ('x', 'y'))
|
||||
std = np.asarray(perception.plan_std, float)
|
||||
if (not math.isfinite(speed) or speed < 0
|
||||
or x.shape != (33,) or y.shape != (33,) or std.shape != (33, 15)
|
||||
or not np.isfinite(x).all() or not np.isfinite(y).all()
|
||||
or not np.isfinite(std).all() or np.any(std < 0)):
|
||||
return None
|
||||
end = 1
|
||||
while end < len(x) and x[end] > x[end-1]+1e-4:
|
||||
end += 1
|
||||
x, y, std = x[:end], y[:end], std[:end]
|
||||
horizon = max(8., min(18., speed))
|
||||
# Retained geometry is finite coverage, not a extrapolated road.
|
||||
if (x[0] > 3. or x[-1] < horizon or old[0, 0] > 3.
|
||||
or old[-1, 0] < max(15., speed)
|
||||
or abs(float(np.interp(3., old[:, 0], old[:, 1]))) > .9):
|
||||
return None
|
||||
grid = np.linspace(3., horizon, 8)
|
||||
delta = np.interp(grid, x, y)-np.interp(grid, old[:, 0], old[:, 1])
|
||||
uncertainty = np.interp(grid, x, std[:, 1])
|
||||
if np.max(np.abs(delta)) > .75 or np.max(uncertainty) > 4.:
|
||||
return None
|
||||
# A confident current road edge contradicting the saved corridor
|
||||
# revokes recovery. Uncertain edges cannot generate a new lane.
|
||||
if hasattr(perception, 'road_edges'):
|
||||
ex=np.asarray(getattr(perception,'road_edge_x',X_IDXS),float)
|
||||
edges=np.asarray(perception.road_edges,float)
|
||||
edge_std=np.asarray(perception.road_edge_std,float)
|
||||
if (ex.shape!=(33,) or edges.shape!=(2,33,2) or edge_std.shape!=(2,33,2)
|
||||
or not all(np.isfinite(v).all() for v in (ex,edges,edge_std))
|
||||
or np.any(np.diff(ex)<=0) or np.any(edge_std<0)
|
||||
or ex[0]>grid[0] or ex[-1]<grid[-1]):
|
||||
return None
|
||||
lo,hi=(np.interp(grid,ex,edges[i,:,0]) for i in range(2))
|
||||
sigma=np.maximum(*(np.interp(grid,ex,edge_std[i,:,0]) for i in range(2)))
|
||||
saved=np.interp(grid,old[:,0],old[:,1])
|
||||
if (np.max(sigma)<=1. and
|
||||
(np.any(hi<=lo) or np.any(np.minimum(saved-lo,hi-saved)-sigma<.2))):
|
||||
return None
|
||||
cap = max(5., self.observed_speed_mph-min(4., 2.*age))
|
||||
return dict(strategy='route-verified-observed-lane-recovery',
|
||||
lane_tracking=True, brake_required=False, road_lost=False,
|
||||
corridor_age_s=age, temporary_recovery=True,
|
||||
recovery_deadline_monotonic=self.seen+self.ROUTE_RECOVERY_S,
|
||||
recovery_speed_cap_mph=cap,
|
||||
recovery_remaining_observed_m=float(old[-1, 0]),
|
||||
recovery_model_offset_m=float(np.max(np.abs(delta))))
|
||||
except (KeyError, AttributeError, TypeError, ValueError, IndexError):
|
||||
return None
|
||||
|
||||
def _reacquire_consumed_lane(self, perception, data, now, pose, old, points):
|
||||
"""Reobserve a lane after driving beyond the old finite corridor.
|
||||
|
||||
An exhausted world-space segment can no longer prove continuity, but
|
||||
must not permanently prevent acquisition of fresh road at a queue.
|
||||
This permits only a nearly stopped truck and several stable, confident
|
||||
current lane observations that agree with the current model path.
|
||||
It does not reset a conflicting corridor still visible ahead.
|
||||
"""
|
||||
try:
|
||||
speed = float(data['speed_mps'])
|
||||
x, y = (np.asarray(getattr(perception.plan, key), float) for key in ('x', 'y'))
|
||||
std = np.asarray(perception.plan_std, float)
|
||||
navigation = data.get('navigation_driver') or {}
|
||||
if (old is None or old[-1, 0] >= 20. or self.seen is None
|
||||
or now-self.seen <= self.HOLD_S or not 0 <= speed <= 3.
|
||||
or (navigation.get('enabled') and navigation.get('allowed_for_gameplay') is not True)
|
||||
or x.shape != (33,) or y.shape != (33,) or std.shape != (33, 15)
|
||||
or not all(np.isfinite(v).all() for v in (x, y, std))):
|
||||
raise ValueError('No exhausted corridor reacquisition')
|
||||
end = 1
|
||||
while end < len(x) and x[end] > x[end-1]+1e-4:
|
||||
end += 1
|
||||
if x[0] > 3. or x[end-1] < 20.:
|
||||
raise ValueError('Short current path')
|
||||
grid = np.array([3., 10., 20.])
|
||||
center = np.interp(grid, points[:, 0], points[:, 1])
|
||||
if (abs(center[0]) > .65
|
||||
or np.max(np.abs(np.interp(grid, x[:end], y[:end])-center)) > .5
|
||||
or np.max(np.interp(grid, x[:end], std[:end, 1])) > .75):
|
||||
raise ValueError('Current path and lane disagree')
|
||||
if hasattr(perception, 'road_edges'):
|
||||
ex = np.asarray(getattr(perception, 'road_edge_x', X_IDXS), float)
|
||||
edges, sigma = (np.asarray(getattr(perception, k), float)
|
||||
for k in ('road_edges', 'road_edge_std'))
|
||||
if (ex.shape != (33,) or edges.shape != (2, 33, 2) or sigma.shape != (2, 33, 2)
|
||||
or not all(np.isfinite(v).all() for v in (ex, edges, sigma))
|
||||
or np.any(np.diff(ex) <= 0) or np.any(sigma < 0)):
|
||||
raise ValueError('Invalid road edge evidence')
|
||||
lo, hi = (np.interp(grid, ex, edges[i, :, 0]) for i in range(2))
|
||||
uncertainty = np.maximum(*(np.interp(grid, ex, sigma[i, :, 0]) for i in range(2)))
|
||||
if np.max(uncertainty) <= 1. and np.any(np.minimum(center-lo, hi-center)-uncertainty < .2):
|
||||
raise ValueError('Current lane approaches a confident road edge')
|
||||
p, basis = pose
|
||||
world = points@basis+p
|
||||
stable = (self.reacquire_at is not None and 0 < now-self.reacquire_at <= .5
|
||||
and self.reacquire_world.shape == world.shape
|
||||
and np.max(np.linalg.norm(world-self.reacquire_world, axis=1)) <= .35)
|
||||
if not stable:
|
||||
self.reacquire_since, self.reacquire_count = now, 0
|
||||
self.reacquire_world, self.reacquire_at = world, now
|
||||
self.reacquire_count += 1
|
||||
return self.reacquire_count >= 3 and now-self.reacquire_since >= .3
|
||||
except (KeyError, AttributeError, TypeError, ValueError, IndexError):
|
||||
self.reacquire_world = self.reacquire_since = self.reacquire_at = None
|
||||
self.reacquire_count = 0
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def _safe_laneless_fallback(cls, perception, data):
|
||||
"""Return evidence for continuing on a bounded model path.
|
||||
|
||||
Four line slots are useful when present, but they are not guaranteed
|
||||
to survive the Tesla Semi cabin projection or a bright/occluded
|
||||
frame. When GPS has already admitted the current road, a short,
|
||||
nearly centred Pop path is stronger evidence than a synthetic
|
||||
straight line. The returned path is still the model's measured path;
|
||||
this method never extrapolates it or creates a new corridor.
|
||||
"""
|
||||
navigation = data.get('navigation_driver') if isinstance(data, dict) else None
|
||||
if not isinstance(navigation, dict) or navigation.get('allowed_for_gameplay') is not True:
|
||||
return None
|
||||
if navigation.get('navigation_phase') in ('manual-junction', 'route-uncertain'):
|
||||
return None
|
||||
speed = data.get('speed_mps')
|
||||
if isinstance(speed, bool) or not isinstance(speed, (int, float)) or not np.isfinite(speed):
|
||||
return None
|
||||
if speed < 0 or speed > cls.LANELESS_MAX_SPEED_MPS:
|
||||
return None
|
||||
try:
|
||||
x = np.asarray(perception.plan.x, dtype=float)
|
||||
y = np.asarray(perception.plan.y, dtype=float)
|
||||
std = np.asarray(perception.plan_std, dtype=float)
|
||||
if (x.shape != (33,) or y.shape != (33,) or std.shape[0] != 33
|
||||
or std.shape[1] < 2 or not np.isfinite(x).all()
|
||||
or not np.isfinite(y).all() or not np.isfinite(std).all()):
|
||||
return None
|
||||
end = 1
|
||||
while end < len(x) and x[end] > x[end - 1] + 1e-4:
|
||||
end += 1
|
||||
x, y, std = x[:end], y[:end], std[:end]
|
||||
# Pop's forecast horizon contracts while the truck is slowing.
|
||||
# Requiring the full highway horizon at crawl speed creates a
|
||||
# feedback loop: a valid short path is rejected, braking starts,
|
||||
# the horizon contracts further, and the truck never pulls away.
|
||||
horizon = min(18., float(x[-1]))
|
||||
minimum_horizon = (18. if speed > 8. else
|
||||
8. if speed > 3. else 3.)
|
||||
if x[0] < 0 or horizon < minimum_horizon:
|
||||
return None
|
||||
sample = np.array([max(1., min(5., horizon*.33)),
|
||||
max(2., min(10., horizon*.66)), horizon])
|
||||
lateral = np.interp(sample, x, y)
|
||||
uncertainty = np.interp(sample, x, std[:, 1])
|
||||
# Once the truck is already below queue speed, the model's far
|
||||
# horizon is naturally noisier. A centred, GPS-agreed path may
|
||||
# continue at a crawl through that dropout; requiring the normal
|
||||
# highway uncertainty limit here was the feedback loop that drove
|
||||
# the previous implementation all the way to zero.
|
||||
uncertainty_limit = (2.0 if speed <= 12.0 else
|
||||
cls.LANELESS_MAX_PATH_STD_M)
|
||||
if (not np.isfinite(lateral).all() or not np.isfinite(uncertainty).all()
|
||||
or np.any(np.abs(lateral) > np.array([1.4, 1.7, 2.2]))
|
||||
or np.max(uncertainty) > uncertainty_limit):
|
||||
return None
|
||||
# Do not carry a path whose first 18 m already point across a
|
||||
# route branch. The navigation assessor supplies this error only
|
||||
# after checking the fresh native node pair.
|
||||
heading = math.degrees(math.atan2(float(lateral[-1] - lateral[0]), 13.))
|
||||
evidence = navigation.get('direction_evidence')
|
||||
route_error = evidence.get('model_error_deg') if isinstance(evidence, dict) else None
|
||||
route_limit = (cls.LANELESS_CRAWL_HEADING_ERROR_DEG if speed <= 3.
|
||||
else 8. if speed <= 8. else cls.LANELESS_MAX_HEADING_ERROR_DEG)
|
||||
if (not isinstance(route_error, (int, float)) or not np.isfinite(route_error)
|
||||
or abs(float(route_error)) > route_limit):
|
||||
return None
|
||||
if abs(heading) > cls.LANELESS_MAX_HEADING_ERROR_DEG:
|
||||
return None
|
||||
# Edges are a guard against silently treating a shoulder as a
|
||||
# lane. Missing edge telemetry is not promoted to a pass.
|
||||
edge_std = np.asarray(getattr(perception, 'road_edge_std', None), dtype=float)
|
||||
# Some replay frames and older WMI payloads carry edge confidence
|
||||
# without the matching coordinate vector. The edge tensor uses
|
||||
# the same fixed 33-point horizon as the model plan; using the
|
||||
# plan's truncated x array here can pair far-horizon coordinates
|
||||
# with near-horizon confidence and reject a valid path.
|
||||
edge_x = np.asarray(getattr(perception, 'road_edge_x', X_IDXS), dtype=float)
|
||||
if edge_std.shape != (2, 33, 2) or edge_x.shape != (33,):
|
||||
return None
|
||||
edge_window = edge_std[:, (edge_x >= 0) & (edge_x <= horizon), 0]
|
||||
edge_limit = 3.0 if speed <= 3. else 2.25
|
||||
if (not edge_window.size or not np.isfinite(edge_window).all()
|
||||
or float(np.max(edge_window)) > edge_limit):
|
||||
return None
|
||||
return dict(strategy='gps-guided-model-laneless', lane_tracking=False,
|
||||
brake_required=False, road_lost=False, corridor_age_s=None,
|
||||
laneless_fallback=True,
|
||||
laneless_evidence=dict(speed_mps=float(speed),
|
||||
max_path_std_m=float(np.max(uncertainty)),
|
||||
path_std_limit_m=float(uncertainty_limit),
|
||||
lateral_samples_m=lateral.tolist(),
|
||||
heading_deg=float(heading),
|
||||
route_error_deg=float(route_error),
|
||||
route_error_limit_deg=float(route_limit),
|
||||
edge_std_limit_m=float(edge_limit),
|
||||
horizon_m=float(horizon)))
|
||||
except (AttributeError, TypeError, ValueError, IndexError):
|
||||
return None
|
||||
|
||||
def assess(self, perception, data, now):
|
||||
navigation, change = data.get('navigation_driver') or {}, data.get('lane_change_driver') or {}
|
||||
if ((change.get('active') is True and change.get('allowed_for_gameplay') is True)
|
||||
or navigation.get('path_override') is not None):
|
||||
self.reset()
|
||||
return perception, dict(strategy='validated-selected-path', lane_tracking=False, brake_required=False)
|
||||
pose = self.pose(data)
|
||||
old = self.projected(pose)
|
||||
candidates = self.candidates(perception)
|
||||
accepted = None
|
||||
reacquired = False
|
||||
if pose is not None and len(candidates) == 1:
|
||||
key, points = candidates[0]
|
||||
continuous = True
|
||||
if self.world is not None:
|
||||
if old is None or old[0, 0] > 3 or old[-1, 0] < 20:
|
||||
continuous = False
|
||||
else:
|
||||
grid = np.array([3., 10., 20.])
|
||||
delta = np.interp(grid, points[:, 0], points[:, 1])-np.interp(grid, old[:, 0], old[:, 1])
|
||||
continuous = bool(np.max(np.abs(delta)) <= .65)
|
||||
if continuous:
|
||||
if self.world is not None:
|
||||
accepted = points
|
||||
else:
|
||||
if key != self.candidate:
|
||||
self.candidate, self.candidate_since, self.count = key, now, 0
|
||||
self.count += 1
|
||||
if self.count >= 3 and now-self.candidate_since >= .1:
|
||||
accepted = points
|
||||
else:
|
||||
self.candidate = None
|
||||
self.count = 0
|
||||
if self._reacquire_consumed_lane(perception, data, now, pose, old, points):
|
||||
accepted, reacquired = points, True
|
||||
else:
|
||||
self.candidate = None
|
||||
self.count = 0
|
||||
if accepted is not None:
|
||||
p, basis = pose
|
||||
self.world = accepted@basis+p
|
||||
self.seen, self.lost = now, False
|
||||
self.verified_route_revision = self._fresh_route(data, now)
|
||||
speed = data.get('speed_mps')
|
||||
self.observed_speed_mph = (float(speed)*2.2369362921 if isinstance(speed, (int, float))
|
||||
and np.isfinite(speed) and speed >= 0 else None)
|
||||
return self.selected(perception, accepted), dict(strategy='observed-ego-lane',
|
||||
lane_tracking=True, brake_required=False, corridor_age_s=0.,
|
||||
consumed_corridor_reacquired=reacquired,
|
||||
near_center_y_m=float(np.interp(3., accepted[:, 0], accepted[:, 1])))
|
||||
if self.seen is not None:
|
||||
age = now-self.seen
|
||||
recovery = self._temporary_recovery(perception, data, now, old, candidates)
|
||||
if recovery is not None:
|
||||
self.lost = False
|
||||
return self.selected(perception, old), recovery
|
||||
held = bool(old is not None and 0 <= age <= self.HOLD_S and old[0, 0] <= 3 and old[-1, 0] >= 15)
|
||||
self.lost = not held
|
||||
if not held:
|
||||
fallback = self._safe_laneless_fallback(perception, data)
|
||||
if fallback is not None:
|
||||
fallback['corridor_age_s'] = age
|
||||
return perception, fallback
|
||||
straight=np.array([[0.,0.],[30.,0.]])
|
||||
return self.selected(perception, old if held else straight), dict(
|
||||
strategy='motion-propagated-ego-lane' if held else 'road-lost-braking',
|
||||
lane_tracking=held, brake_required=age > .35 or not held,
|
||||
corridor_age_s=age, road_lost=not held)
|
||||
# Laneless model following remains available. Do not treat mere paint
|
||||
# loss as failure, but reject the large uncertain path seen off-road.
|
||||
implausible = False
|
||||
try:
|
||||
x, y = (np.asarray(getattr(perception.plan, k), float) for k in ('x', 'y'))
|
||||
std = np.asarray(perception.plan_std, float)
|
||||
implausible = bool(abs(np.interp(10., x, y)) > 2.5 and np.max(std[(x >= 0) & (x <= 20), 1]) > .5)
|
||||
except (AttributeError, TypeError, ValueError, IndexError):
|
||||
pass
|
||||
return (self.selected(perception,np.array([[0.,0.],[30.,0.]])) if implausible else perception), dict(strategy='road-lost-braking' if implausible else 'model-laneless',
|
||||
lane_tracking=False, brake_required=implausible, road_lost=implausible)
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Persist speed settings and follow higher navigation limits without actuators."""
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
TRAILER_SPEED_OFFSET_MPH = 5.
|
||||
BOBTAIL_SPEED_OFFSET_MPH = 10.
|
||||
|
||||
|
||||
def measured_trailer_attached(data):
|
||||
"""Return a verified own-trailer state, or None when it is unavailable."""
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
direct = data.get('trailer_attached')
|
||||
if type(direct) is bool:
|
||||
return direct
|
||||
traffic = data.get('nearby_traffic')
|
||||
if isinstance(traffic, dict):
|
||||
attached = traffic.get('ego_trailer_attached')
|
||||
if type(attached) is bool:
|
||||
return attached
|
||||
scene = data.get('driving_scene')
|
||||
if isinstance(scene, dict):
|
||||
vehicle = scene.get('vehicle')
|
||||
if isinstance(vehicle, dict):
|
||||
attached = vehicle.get('trailer_attached')
|
||||
if type(attached) is bool:
|
||||
return attached
|
||||
return None
|
||||
|
||||
|
||||
def navigation_speed_offset_mph(trailer_attached):
|
||||
"""Use a smaller posted-limit offset with a connected trailer."""
|
||||
return (TRAILER_SPEED_OFFSET_MPH if trailer_attached is not False
|
||||
else BOBTAIL_SPEED_OFFSET_MPH)
|
||||
|
||||
|
||||
class NavigationSpeedLimit:
|
||||
"""Confirm posted-limit changes; unchanged signs never undo manual input."""
|
||||
CONFIRM_S = .3
|
||||
MAX_SAMPLE_GAP_S = .35
|
||||
|
||||
def __init__(self):
|
||||
self.limit_mph = None
|
||||
self._pending = self._pending_since = self._last_sample = None
|
||||
|
||||
def observe(self, data, now):
|
||||
limit = data.get('speed_limit_mps')
|
||||
age = data.get('age')
|
||||
numeric = lambda value: (not isinstance(value, bool)
|
||||
and isinstance(value, (int, float)) and math.isfinite(value))
|
||||
if (data.get('valid') is not True or data.get('paused')
|
||||
or data.get('navigation_valid') is not True
|
||||
or not numeric(age) or not 0 <= age <= self.MAX_SAMPLE_GAP_S
|
||||
or not numeric(now) or not numeric(limit)
|
||||
or not 5 <= limit * 2.2369362921 <= 125):
|
||||
self._pending = self._pending_since = self._last_sample = None
|
||||
return None
|
||||
# SDK floats are m/s; compare whole MPH signs, not conversion noise.
|
||||
mph = int(round(limit * 2.2369362921))
|
||||
if (mph != self._pending or self._last_sample is None
|
||||
or not 0 <= now - self._last_sample <= self.MAX_SAMPLE_GAP_S):
|
||||
self._pending, self._pending_since = mph, now
|
||||
self._last_sample = now
|
||||
if now - self._pending_since < self.CONFIRM_S or mph == self.limit_mph:
|
||||
return None
|
||||
previous, self.limit_mph = self.limit_mph, mph
|
||||
return mph if previous is None or mph > previous else None
|
||||
|
||||
|
||||
def valid_speed(value):
|
||||
return (not isinstance(value,bool) and isinstance(value,(int,float))
|
||||
and math.isfinite(value) and 5<=value<=80)
|
||||
|
||||
|
||||
def load_speed(path, default=35.):
|
||||
try:
|
||||
value=json.loads(Path(path).read_text(encoding='utf-8'))['target_speed_mph']
|
||||
if valid_speed(value):return float(value)
|
||||
except (OSError,ValueError,KeyError,TypeError):pass
|
||||
return default
|
||||
|
||||
|
||||
def save_speed(path, value):
|
||||
if not valid_speed(value):raise ValueError('Invalid speed target')
|
||||
path=Path(path)
|
||||
path.parent.mkdir(parents=True,exist_ok=True)
|
||||
temporary=path.with_suffix('.tmp')
|
||||
temporary.write_text(json.dumps(dict(target_speed_mph=value))+'\n',encoding='utf-8')
|
||||
temporary.replace(path)
|
||||
@@ -0,0 +1,213 @@
|
||||
"""Passive authored-path/model-corridor comparison, never driving permission.
|
||||
|
||||
Authored prefab paths use forward/left/up; scene-aligned observations use
|
||||
forward/right/down. This comparison is estimated because the model boundaries
|
||||
and final camera extrinsics are unverified. No painted lane identity, right of
|
||||
way, signal state, obstacle clearance or actuator command is established here.
|
||||
"""
|
||||
import math
|
||||
import re
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
DECODER_COMMIT = 'e853797bec3620659f14811d70ceea213399b83d'
|
||||
HORIZON = (5., 30.)
|
||||
GRID = np.arange(5., 30.01, 1.)
|
||||
|
||||
|
||||
def _fresh(value):
|
||||
age = value.get('age_s') if isinstance(value, dict) else None
|
||||
return type(age) in (int, float) and math.isfinite(age) and 0 <= age <= .5
|
||||
|
||||
|
||||
def unavailable(reason):
|
||||
return dict(available=False, reason=reason, estimated=True, display_only=True,
|
||||
usable_for_control=False, matched_slot_id=None, candidates=[],
|
||||
ambiguity=False, route_revision=None, coverage_m=list(HORIZON),
|
||||
painted_lane_identity_verified=False, clear_lane_verified=False,
|
||||
traffic_rules_verified=False,
|
||||
source='directed GPS UID pair + authored AI center + observed model corridor',
|
||||
thresholds=dict(boundary_margin_m=.3, max_vertical_residual_m=.6,
|
||||
max_direction_difference_rad=.25,
|
||||
max_grade_difference=.06, max_sample_gap_m=12.),
|
||||
limitation='Estimated geometric association; final render extrinsics, paint identity and driving permission unverified')
|
||||
|
||||
|
||||
def junction_handling_preview(geometry):
|
||||
"""A nearby authored junction is a manual-handling requirement, not a rule."""
|
||||
nearby = (isinstance(geometry, dict) and geometry.get('context_available') is True
|
||||
and _fresh(geometry) and isinstance(geometry.get('junctions'), list)
|
||||
and bool(geometry['junctions']))
|
||||
return dict(available=bool(nearby), nearby_junction=bool(nearby),
|
||||
manual_required=True if nearby else None,
|
||||
status='manual-required' if nearby else 'junction-context-unavailable',
|
||||
reason=('Nearby map junction; autonomous junction handling unverified' if nearby
|
||||
else 'No fresh verified nearby junction context'),
|
||||
stop_requirement='unknown', right_of_way='unknown',
|
||||
traffic_rules_verified=False, clearance_verified=False,
|
||||
display_only=True, usable_for_control=False)
|
||||
|
||||
|
||||
def _validate_provenance(path):
|
||||
source = path.get('provenance')
|
||||
if not isinstance(source, dict):
|
||||
raise ValueError('Authored asset provenance unavailable')
|
||||
asset = source.get('asset_path')
|
||||
digest = source.get('asset_sha256')
|
||||
if (not isinstance(asset, str) or not asset.startswith('/prefab/') or not asset.endswith('.ppd')
|
||||
or not isinstance(digest, str) or not re.fullmatch('[0-9a-f]{64}', digest)
|
||||
or type(source.get('ppd_version')) is not int or source['ppd_version'] not in (24, 25)):
|
||||
raise ValueError('Unsupported authored asset provenance')
|
||||
for key, limit in (('attachment_error_m', .25), ('attachment_height_error_m', .5)):
|
||||
error = source.get(key)
|
||||
if type(error) not in (int, float) or not math.isfinite(error) or not 0 <= error <= limit:
|
||||
raise ValueError('Authored placement attachment error unverified')
|
||||
curves = path.get('curve_indices')
|
||||
lane = path.get('input_lane_index')
|
||||
if (type(lane) is not int or not 0 <= lane < 64 or not isinstance(curves, list)
|
||||
or not 1 <= len(curves) <= 128
|
||||
or any(type(index) is not int or not 0 <= index < 65536 for index in curves)):
|
||||
raise ValueError('Authored input lane/curve identity unavailable')
|
||||
|
||||
|
||||
def _path_samples(path):
|
||||
points = np.asarray(path.get('points'), dtype=float)
|
||||
if (points.ndim != 2 or points.shape[1] != 3 or not 6 <= len(points) <= 8192
|
||||
or not np.all(np.isfinite(points)) or np.any(np.abs(points) > 10000)):
|
||||
raise ValueError('Invalid authored path point array')
|
||||
# Adjacent authored curves repeat an identical join. Only that exact join
|
||||
# is removed; lateral/height jumps at equal forward position are rejected.
|
||||
points = points[np.r_[True, np.any(np.abs(np.diff(points, axis=0)) > 1e-6, axis=1)]]
|
||||
if len(points) < 6 or np.min(points[:, 0]) > HORIZON[0] or np.max(points[:, 0]) < HORIZON[1]:
|
||||
raise ValueError('Authored path lacks measured 5–30 m coverage')
|
||||
# A complete route can curve behind the truck outside our horizon. Use one
|
||||
# unique contiguous traversal of the measured span, never join separate
|
||||
# visits, or accept a reverse/sideways segment inside that span.
|
||||
segments = np.flatnonzero((np.maximum(points[:-1, 0], points[1:, 0]) > HORIZON[0])
|
||||
& (np.minimum(points[:-1, 0], points[1:, 0]) < HORIZON[1]))
|
||||
if (not len(segments) or np.any(np.diff(segments) != 1)
|
||||
or np.any(np.diff(points[:, 0])[segments] <= 1e-6)):
|
||||
raise ValueError('Authored path reverses, folds or revisits the comparison horizon')
|
||||
points = points[segments[0]:segments[-1]+2]
|
||||
if points[0, 0] > HORIZON[0] or points[-1, 0] < HORIZON[1]:
|
||||
raise ValueError('Authored path lacks contiguous measured 5–30 m coverage')
|
||||
# Include the two enclosing samples in the gap check, never extrapolate.
|
||||
first = max(0, int(np.searchsorted(points[:, 0], HORIZON[0], side='right'))-1)
|
||||
last = min(len(points)-1, int(np.searchsorted(points[:, 0], HORIZON[1])))
|
||||
if np.any(np.diff(points[first:last+1, 0]) > 12):
|
||||
raise ValueError('Authored path has a gap across the comparison horizon')
|
||||
# Coordinate conversion: authored left/up become model right/down.
|
||||
return np.array([np.interp(GRID, points[:, 0], -points[:, axis]) for axis in (1, 2)])
|
||||
|
||||
|
||||
def route_corridor_association(x, ys, zs, slots, route, paths, telemetry, geometry):
|
||||
"""Return candidate evidence; one match remains estimated and display-only."""
|
||||
result = unavailable('Fresh aligned, unobstructed model evidence required')
|
||||
if not (isinstance(telemetry, dict) and telemetry.get('valid') is True
|
||||
and not telemetry.get('paused') and telemetry.get('model_obstructed') is False
|
||||
and telemetry.get('model_geometry_stale') is not True
|
||||
and isinstance(telemetry.get('scene_alignment'), dict)
|
||||
and telemetry['scene_alignment'].get('available') is True
|
||||
and _fresh(dict(age_s=telemetry.get('model_age_s')))):
|
||||
return result
|
||||
obstruction = telemetry.get('camera_obstruction')
|
||||
if obstruction is not None and (not isinstance(obstruction, dict)
|
||||
or obstruction.get('checked') is not True or obstruction.get('blocked') is not False):
|
||||
return dict(result, reason='Camera obstruction gate not verified clear')
|
||||
if not (isinstance(route, dict) and route.get('available') is True and _fresh(route)
|
||||
and isinstance(geometry, dict) and geometry.get('route_context_verified') is True
|
||||
and geometry.get('context_available') is True and _fresh(geometry)):
|
||||
return dict(result, reason='Fresh verified directed GPS/map context required')
|
||||
if not (isinstance(paths, dict) and paths.get('available') is True and _fresh(paths)
|
||||
and paths.get('source') == 'ATS authored prefab AI paths'
|
||||
and paths.get('geometry_kind') == 'authored-ai-lane-centers'
|
||||
and paths.get('decoder_commit') == DECODER_COMMIT
|
||||
and paths.get('usable_for_control') is False):
|
||||
return dict(result, reason='Fresh pinned authored prefab path provenance required')
|
||||
try:
|
||||
nodes = route.get('nodes')
|
||||
if not isinstance(nodes, list) or not 2 <= len(nodes) <= 1024:
|
||||
raise ValueError('Invalid directed GPS endpoint list')
|
||||
for node in nodes:
|
||||
if (not isinstance(node.get('uid'), (str, int)) or not str(node['uid'])
|
||||
or len(node['position']) != 3
|
||||
or not all(type(v) in (int, float) and math.isfinite(v) for v in node['position'])):
|
||||
raise ValueError('Invalid directed GPS endpoint identity or position')
|
||||
pairs = {(str(a['uid']), str(b['uid'])) for a, b in zip(nodes, nodes[1:])}
|
||||
# Require the same explicit route pair in fresh map context too. The
|
||||
# path's cached route_match flag alone cannot survive a route revision.
|
||||
map_pairs = {(str(j['prefab_uid']), str(link['start_node_uid']), str(link['end_node_uid']))
|
||||
for j in geometry.get('junctions', [])[:4] for link in j.get('route_links', [])}
|
||||
result['route_revision'] = route.get('revision')
|
||||
if x[0] > HORIZON[0] or x[-1] < HORIZON[1]:
|
||||
return dict(result, reason='Observed boundaries lack measured 5–30 m coverage')
|
||||
first = max(0, int(np.searchsorted(x, 5., side='right'))-1)
|
||||
last = min(len(x)-1, int(np.searchsorted(x, 30.)))
|
||||
if np.any(np.diff(x[first:last+1]) > 12):
|
||||
return dict(result, reason='Observed boundary samples have an unsupported forward gap')
|
||||
raw = paths.get('paths')
|
||||
if not isinstance(raw, list) or len(raw) > 512:
|
||||
raise ValueError('Invalid bounded authored path list')
|
||||
matched = []
|
||||
seen = set()
|
||||
duplicate_identity = False
|
||||
for path in raw:
|
||||
if not isinstance(path, dict) or path.get('route_match') is not True:
|
||||
continue
|
||||
pair = (str(path.get('start_node_uid')), str(path.get('end_node_uid')))
|
||||
prefab = str(path.get('prefab_uid'))
|
||||
evidence = dict(prefab_uid=prefab, start_node_uid=pair[0], end_node_uid=pair[1],
|
||||
input_lane_index=path.get('input_lane_index'),
|
||||
curve_indices=path.get('curve_indices'), comparisons=[], fits=False, reason='')
|
||||
result['candidates'].append(evidence)
|
||||
try:
|
||||
if pair not in pairs or (prefab, *pair) not in map_pairs:
|
||||
raise ValueError('Authored path does not match current directed GPS/map UID pair')
|
||||
_validate_provenance(path)
|
||||
identity = (prefab, *pair, path['input_lane_index'], tuple(path['curve_indices']))
|
||||
if identity in seen:
|
||||
duplicate_identity = True
|
||||
raise ValueError('Duplicate authored path identity')
|
||||
seen.add(identity)
|
||||
sampled = _path_samples(path)
|
||||
for slot in slots:
|
||||
left, right = slot['left_boundary_index'], slot['right_boundary_index']
|
||||
low, high = np.interp(GRID, x, ys[left]), np.interp(GRID, x, ys[right])
|
||||
center = (low+high)*.5
|
||||
down = (np.interp(GRID, x, zs[left])+np.interp(GRID, x, zs[right]))*.5
|
||||
margin = np.minimum(sampled[0]-low, high-sampled[0])
|
||||
direction_error = np.abs(np.arctan(np.diff(sampled[0]))-np.arctan(np.diff(center)))
|
||||
grade_error = np.abs(np.diff(sampled[1])-np.diff(down))
|
||||
vertical_error = np.abs(sampled[1]-down)
|
||||
reasons = []
|
||||
if np.min(margin) < .3:
|
||||
reasons.append('Authored center crosses or approaches observed boundary')
|
||||
if np.max(direction_error) > .25 or np.max(np.abs(np.diff(sampled[0]))) > .65:
|
||||
reasons.append('Forward direction differs or path turn exceeds comparison range')
|
||||
if np.max(vertical_error) > .6 or np.max(grade_error) > .06:
|
||||
reasons.append('Road grade or height differs from observed corridor')
|
||||
comparison = dict(slot_id=slot['slot_id'], fits=not reasons, reason='; '.join(reasons),
|
||||
min_boundary_margin_m=float(np.min(margin)),
|
||||
max_center_residual_m=float(np.max(np.abs(sampled[0]-center))),
|
||||
max_vertical_residual_m=float(np.max(vertical_error)),
|
||||
max_direction_difference_rad=float(np.max(direction_error)),
|
||||
max_grade_difference=float(np.max(grade_error)),
|
||||
measured_coverage_m=list(HORIZON))
|
||||
evidence['comparisons'].append(comparison)
|
||||
if not reasons:
|
||||
matched.append((identity, slot['slot_id']))
|
||||
evidence['fits'] = any(item['fits'] for item in evidence['comparisons'])
|
||||
if not evidence['fits']:
|
||||
evidence['reason'] = 'No observed corridor fits throughout measured 5–30 m horizon'
|
||||
except (KeyError, TypeError, ValueError, OverflowError) as exc:
|
||||
evidence['reason'] = str(exc)
|
||||
if duplicate_identity:
|
||||
return dict(result, reason='Duplicate authored path identity; association ambiguous', ambiguity=True)
|
||||
if len(matched) == 1:
|
||||
return dict(result, available=True, reason='', matched_slot_id=matched[0][1])
|
||||
if len(matched) > 1:
|
||||
return dict(result, reason='Multiple authored paths/corridors fit; route association ambiguous', ambiguity=True)
|
||||
return dict(result, reason='No uniquely supported authored route/observed corridor association')
|
||||
except (KeyError, TypeError, ValueError, OverflowError, IndexError) as exc:
|
||||
return dict(result, reason=str(exc))
|
||||
@@ -0,0 +1,292 @@
|
||||
"""Observed model corridors, measured actor overlap and GPS attachment hints.
|
||||
|
||||
This module is display-only. A corridor between two observed lines is not a
|
||||
verified map lane, an empty actor list is not clearance, and a GPS attachment
|
||||
does not tell us which lane reaches it. No controller or input modules exist here.
|
||||
"""
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
from control.junction_association import (junction_handling_preview,
|
||||
route_corridor_association,
|
||||
unavailable as association_unavailable)
|
||||
|
||||
|
||||
def _get(value, key):
|
||||
return value.get(key) if isinstance(value, dict) else getattr(value, key, None)
|
||||
|
||||
|
||||
def _fresh(report):
|
||||
age = report.get('age_s') if isinstance(report, dict) else None
|
||||
return (isinstance(age, (int, float)) and math.isfinite(age) and 0 <= age <= .5)
|
||||
|
||||
|
||||
def _area(polygon):
|
||||
return abs(sum(a[0]*b[1]-b[0]*a[1] for a, b in
|
||||
zip(polygon, polygon[1:]+polygon[:1])))*.5 if len(polygon) >= 3 else 0.
|
||||
|
||||
|
||||
def _intersection(polygon, boundary):
|
||||
"""Clip a measured rectangle against one ordered lane trapezoid."""
|
||||
for a, b in zip(boundary, boundary[1:]+boundary[:1]):
|
||||
if not polygon:
|
||||
break
|
||||
def side(point):
|
||||
return (b[0]-a[0])*(point[1]-a[1])-(b[1]-a[1])*(point[0]-a[0])
|
||||
clipped = []
|
||||
for p, q in zip(polygon, polygon[1:]+polygon[:1]):
|
||||
sp, sq = side(p), side(q)
|
||||
if sp >= 0:
|
||||
clipped.append(p)
|
||||
if (sp >= 0) != (sq >= 0):
|
||||
fraction = sp/(sp-sq)
|
||||
clipped.append((p[0]+fraction*(q[0]-p[0]), p[1]+fraction*(q[1]-p[1])))
|
||||
polygon = clipped
|
||||
return polygon
|
||||
|
||||
|
||||
def _footprint(actor):
|
||||
values = [float(actor[key]) for key in
|
||||
('forward_m', 'left_m', 'length_m', 'width_m', 'heading_delta_rad')]
|
||||
forward, left, length, width, yaw = values
|
||||
if (not all(math.isfinite(value) for value in values) or
|
||||
not .2 <= length <= 60 or not .2 <= width <= 8):
|
||||
raise ValueError('Invalid measured actor footprint')
|
||||
cosine, sine = math.cos(yaw), math.sin(yaw)
|
||||
# Model coordinates are forward/right; actor coordinates are forward/left.
|
||||
return [(forward+cosine*f-sine*l, -(left+sine*f+cosine*l))
|
||||
for f, l in ((length/2, width/2), (length/2, -width/2),
|
||||
(-length/2, -width/2), (-length/2, width/2))]
|
||||
|
||||
|
||||
def _branch_hint(geometry, route):
|
||||
if not (isinstance(geometry, dict) and geometry.get('context_available')
|
||||
and geometry.get('route_context_verified') and isinstance(route, dict)
|
||||
and route.get('available') and _fresh(route)):
|
||||
return dict(available=False, reason='Fresh verified map/GPS attachment match unavailable')
|
||||
try:
|
||||
nodes = route['nodes']
|
||||
if not isinstance(nodes, list) or not 2 <= len(nodes) <= 1024:
|
||||
raise ValueError('Invalid GPS endpoint list')
|
||||
if any(len(node['position']) != 3 or not all(math.isfinite(value) for value in node['position'])
|
||||
for node in nodes):
|
||||
raise ValueError('Invalid GPS endpoint positions')
|
||||
if geometry.get('age_s') is not None and not _fresh(geometry):
|
||||
raise ValueError('Stale road geometry context')
|
||||
pairs = {(str(a['uid']), str(b['uid'])) for a, b in zip(nodes, nodes[1:])}
|
||||
hints = []
|
||||
for junction in geometry.get('junctions', []):
|
||||
attachments = junction.get('attachments', [])
|
||||
for link in junction.get('route_links', []):
|
||||
start, end = str(link['start_node_uid']), str(link['end_node_uid'])
|
||||
if (start, end) not in pairs:
|
||||
continue
|
||||
incoming = [a for a in attachments if str(a['node_uid']) == start and a['incoming_lanes'] > 0]
|
||||
outgoing = [a for a in attachments if str(a['node_uid']) == end and a['outgoing_lanes'] > 0]
|
||||
if not incoming or not outgoing:
|
||||
continue
|
||||
# Retain actual endpoints and counts, never connect unknown
|
||||
# prefab interior curves or infer a turn lane from lane counts.
|
||||
hints.append(dict(prefab_uid=junction['prefab_uid'], from_node_uid=start,
|
||||
to_node_uid=end, incoming_road_uids=[a['road_uid'] for a in incoming],
|
||||
outgoing_road_uids=[a['road_uid'] for a in outgoing],
|
||||
outgoing_lane_counts=[a['outgoing_lanes'] for a in outgoing],
|
||||
outgoing_endpoints=[a['endpoint'] for a in outgoing],
|
||||
route_revision=route.get('revision'), lane_mapping_verified=False))
|
||||
return dict(available=bool(hints), reason='' if hints else 'No exact directed GPS junction attachment pair',
|
||||
source='verified map attachments and directed GPS UID pairs',
|
||||
attachments=hints, interior_path_verified=False, usable_for_control=False)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return dict(available=False, reason='Invalid map/GPS junction attachment evidence')
|
||||
|
||||
|
||||
def _authored_route_lanes(paths, route):
|
||||
if not (isinstance(paths, dict) and paths.get('available') and isinstance(route, dict)
|
||||
and route.get('available') and _fresh(route)):
|
||||
return []
|
||||
if paths.get('age_s') is not None and not _fresh(paths):
|
||||
return []
|
||||
try:
|
||||
if (not isinstance(route.get('nodes'), list) or not 2 <= len(route['nodes']) <= 1024
|
||||
or any(len(node['position']) != 3 or not all(math.isfinite(value) for value in node['position'])
|
||||
for node in route['nodes'])):
|
||||
return []
|
||||
pairs = {(str(a['uid']), str(b['uid'])) for a, b in zip(route['nodes'], route['nodes'][1:])}
|
||||
result = []
|
||||
for item in paths.get('route_lanes', []):
|
||||
pair = str(item['start_node_uid']), str(item['target_node_uid'])
|
||||
indices = item['input_lane_indices']
|
||||
if (pair not in pairs or not isinstance(indices, list) or not indices
|
||||
or any(type(index) is not int or not 0 <= index < 64 for index in indices)):
|
||||
continue
|
||||
result.append(dict(prefab_uid=item['prefab_uid'], start_node_uid=pair[0],
|
||||
target_node_uid=pair[1], input_lane_indices=sorted(set(indices)),
|
||||
observed_corridor_alignment_verified=False))
|
||||
return result
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return []
|
||||
|
||||
|
||||
def lane_choice_preview(lanes, traffic, geometry, route=None, telemetry=None, junction_paths=None):
|
||||
"""Assess factual forward corridor occupancy; never recommend a driving lane."""
|
||||
result = dict(available=False, reason='', display_only=True, usable_for_control=False,
|
||||
complete_coverage=False, clear_lane_verified=False, observed_slots=[],
|
||||
current_slot=None, current_slot_available=False, route_lane_choice_available=False,
|
||||
current_slot_reference='zero lateral in near forward model samples; not map lane membership',
|
||||
route_lane_choice_reason='Exact route-to-observed-lane mapping is unavailable',
|
||||
recommended_slot=None, branch_hint=_branch_hint(geometry, route),
|
||||
authored_route_lanes=_authored_route_lanes(junction_paths, route),
|
||||
authored_route_lane_indices_available=False,
|
||||
route_corridor_association=association_unavailable('Observed corridor evidence unavailable'),
|
||||
junction_handling=junction_handling_preview(geometry),
|
||||
actor_assessments=[], traffic_assessment_available=False,
|
||||
traffic_reason='Fresh tracked simulator actor report required',
|
||||
source='forward model boundaries + measured ATS actors',
|
||||
map_lane_counts=(geometry.get('lane_counts') if isinstance(geometry, dict)
|
||||
and geometry.get('available')
|
||||
and (geometry.get('age_s') is None or _fresh(geometry)) else None),
|
||||
map_lane_membership_verified=False,
|
||||
actor_road_level_tolerance_m=2.,
|
||||
limitations=['Observed corridors have unverified travel direction and map lane identity',
|
||||
'Forward model geometry is never extrapolated behind the truck',
|
||||
'Missing loaded actors do not establish lane clearance',
|
||||
'Upright height approximation leaves substantial grades/overpasses unassessed',
|
||||
'GPS attachments do not establish route-to-lane connectivity'])
|
||||
if result['authored_route_lanes']:
|
||||
result['authored_route_lane_indices_available'] = True
|
||||
result['route_lane_choice_reason'] = 'Authored route lane indices available; model corridor alignment unverified'
|
||||
if telemetry is not None and (not telemetry.get('valid') or telemetry.get('paused')):
|
||||
return dict(result, reason='Fresh, unpaused perception context required',
|
||||
branch_hint=dict(available=False, reason='Truck telemetry unavailable'),
|
||||
authored_route_lanes=[], authored_route_lane_indices_available=False)
|
||||
if telemetry is not None and telemetry.get('model_age_s') is not None:
|
||||
age = telemetry['model_age_s']
|
||||
if not isinstance(age, (int, float)) or not math.isfinite(age) or not 0 <= age <= .5:
|
||||
return dict(result, reason='Model boundary sample stale')
|
||||
try:
|
||||
x = np.asarray(_get(lanes, 'x'), dtype=float)
|
||||
ys = np.asarray(_get(lanes, 'all_y'), dtype=float)
|
||||
zs = np.asarray(_get(lanes, 'all_z'), dtype=float)
|
||||
probabilities = np.asarray(_get(lanes, 'probabilities'), dtype=float)
|
||||
if (x.ndim != 1 or len(x) < 3 or ys.shape != (4, len(x)) or zs.shape != ys.shape
|
||||
or probabilities.shape != (4,) or not np.all(np.isfinite(x))
|
||||
or not np.all(np.isfinite(ys)) or not np.all(np.isfinite(zs))
|
||||
or not np.all(np.isfinite(probabilities)) or np.any(np.diff(x) <= 0)
|
||||
or np.any((probabilities < 0) | (probabilities > 1))):
|
||||
return dict(result, reason='Four-line model observations invalid or unavailable')
|
||||
start, end = max(3., float(x[0])), min(40., float(x[-1]))
|
||||
if start > 6 or end < 20 or sum((x >= start) & (x <= end)) < 3:
|
||||
return dict(result, reason='Model boundaries lack a useful near-to-forward horizon')
|
||||
grid = np.unique(np.r_[start, x[(x > start) & (x < end)], end])
|
||||
interpolated = [np.interp(grid, x, line) for line in ys]
|
||||
confident = np.flatnonzero(probabilities >= .55)
|
||||
if any(np.any(interpolated[a] >= interpolated[b]-.3)
|
||||
for a, b in zip(confident, confident[1:])):
|
||||
return dict(result, reason='Confident model boundaries cross or are out of order')
|
||||
slots = []
|
||||
rejected = []
|
||||
for left in range(3):
|
||||
right = left+1
|
||||
if min(probabilities[left], probabilities[right]) < .55:
|
||||
continue
|
||||
lo, hi = interpolated[left], interpolated[right]
|
||||
widths = hi-lo
|
||||
if (np.any(np.abs(lo) > 25) or np.any(np.abs(hi) > 25)
|
||||
or np.any(widths < 2.3) or np.any(widths > 5.5)
|
||||
or np.ptp(widths) > 1.5):
|
||||
rejected.append([left, right])
|
||||
continue
|
||||
near = grid <= 6
|
||||
contains_zero = bool(np.all(lo[near] < -.15) and np.all(hi[near] > .15))
|
||||
slots.append(dict(slot_id=f'model-{left}-{right}', left_boundary_index=left,
|
||||
right_boundary_index=right, confidence=float(min(probabilities[left], probabilities[right])),
|
||||
forward_range_m=[start, end], width_min_m=float(min(widths)),
|
||||
width_max_m=float(max(widths)), contains_ego_zero_nearby=contains_zero,
|
||||
map_lane_index=None, travel_direction_verified=False,
|
||||
boundaries=[dict(forward_m=float(g), left_y_m=float(l), right_y_m=float(h))
|
||||
for g, l, h in zip(grid, lo, hi)],
|
||||
observed_actor_ids=[], occupancy_status='unassessed',
|
||||
occupancy_complete=False, clear_lane_verified=False))
|
||||
result['rejected_boundary_pairs'] = rejected
|
||||
result['confident_boundary_indices'] = [int(i) for i in np.flatnonzero(probabilities >= .55)]
|
||||
result['observed_slots'] = slots
|
||||
if not slots:
|
||||
return dict(result, reason='No adjacent confident boundaries form a stable forward corridor')
|
||||
current = [slot['slot_id'] for slot in slots if slot['contains_ego_zero_nearby']]
|
||||
if len(current) == 1:
|
||||
result.update(current_slot=current[0], current_slot_available=True)
|
||||
result.update(available=True, reason='', forward_range_m=[start, end])
|
||||
result['route_corridor_association'] = route_corridor_association(
|
||||
x, ys, zs, slots, route, junction_paths, telemetry, geometry)
|
||||
if not (isinstance(traffic, dict) and traffic.get('available') and _fresh(traffic)
|
||||
and traffic.get('tracking') and isinstance(traffic.get('actors'), list)):
|
||||
return result
|
||||
result.update(traffic_assessment_available=True, traffic_reason='')
|
||||
for slot in slots:
|
||||
slot['occupancy_status'] = 'no observed overlap; coverage incomplete'
|
||||
for actor in traffic['actors'][:500]:
|
||||
if not isinstance(actor, dict):
|
||||
result['traffic_reason'] = 'Some actor footprint evidence unavailable'
|
||||
continue
|
||||
samples = actor.get('sample_count', 0)
|
||||
assessment = dict(id=actor.get('id'), observed_slot_ids=[], assessed=False,
|
||||
reason='', continuity_verified=isinstance(samples, int) and samples >= 2,
|
||||
motion_available=bool(actor.get('motion_available')))
|
||||
result['actor_assessments'].append(assessment)
|
||||
try:
|
||||
actor_age = actor.get('measured_age_s', traffic['age_s'])
|
||||
if not isinstance(actor_age, (int, float)) or not math.isfinite(actor_age) or not 0 <= actor_age <= .5:
|
||||
assessment['reason'] = 'Actor measurement stale'
|
||||
continue
|
||||
polygon = _footprint(actor)
|
||||
if float(actor['forward_m']) <= 0:
|
||||
assessment['reason'] = 'Rear actor: model lane geometry unavailable'
|
||||
continue
|
||||
if max(p[0] for p in polygon) < start or min(p[0] for p in polygon) > end:
|
||||
assessment['reason'] = 'Actor outside observed forward horizon'
|
||||
continue
|
||||
actor_position = actor.get('world_position')
|
||||
ego_position = telemetry.get('world_position') if isinstance(telemetry, dict) else None
|
||||
height = actor.get('height_m')
|
||||
if (not isinstance(actor_position, (list, tuple)) or len(actor_position) != 3
|
||||
or not isinstance(ego_position, (list, tuple)) or len(ego_position) != 3
|
||||
or not all(isinstance(v, (int, float)) and math.isfinite(v)
|
||||
for v in (*actor_position, *ego_position))
|
||||
or not isinstance(height, (int, float)) or not math.isfinite(height)
|
||||
or not .2 <= height <= 60):
|
||||
assessment['reason'] = 'Measured actor/ego road-height qualification unavailable'
|
||||
result['traffic_reason'] = 'Actor road-height qualification incomplete'
|
||||
for slot in slots:
|
||||
if not slot['observed_actor_ids']:
|
||||
slot['occupancy_status'] = 'unassessed actor road level; coverage incomplete'
|
||||
continue
|
||||
base_height = actor_position[1]-height*.5
|
||||
level_error = abs(base_height-ego_position[1])
|
||||
assessment.update(road_level_error_m=level_error,
|
||||
road_level_method='upright center minus half-height against SDK ego height')
|
||||
if level_error > 2:
|
||||
assessment['reason'] = 'Relative road level differs; grade/overpass occupancy unverified'
|
||||
continue
|
||||
assessment.update(assessed=True,
|
||||
coverage='partial' if min(p[0] for p in polygon) < start or max(p[0] for p in polygon) > end else 'forward footprint',
|
||||
reason='Measured footprint against forward model corridors; not map-lane assignment')
|
||||
for slot in slots:
|
||||
bounds = slot['boundaries']
|
||||
overlap = 0.
|
||||
for a, b in zip(bounds, bounds[1:]):
|
||||
if b['forward_m'] < min(p[0] for p in polygon) or a['forward_m'] > max(p[0] for p in polygon):
|
||||
continue
|
||||
trapezoid = [(a['forward_m'], a['left_y_m']), (b['forward_m'], b['left_y_m']),
|
||||
(b['forward_m'], b['right_y_m']), (a['forward_m'], a['right_y_m'])]
|
||||
overlap += _area(_intersection(polygon, trapezoid))
|
||||
if overlap > .02:
|
||||
slot['observed_actor_ids'].append(actor['id'])
|
||||
slot['occupancy_status'] = 'observed footprint overlap'
|
||||
assessment['observed_slot_ids'].append(slot['slot_id'])
|
||||
except (KeyError, TypeError, ValueError, OverflowError):
|
||||
assessment.update(assessed=False, reason='Invalid measured actor footprint')
|
||||
result['traffic_reason'] = 'Some actor footprint evidence unavailable'
|
||||
return result
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return dict(result, reason='Invalid forward corridor evidence')
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Observed actor footprints intersecting the truck's forward/model paths.
|
||||
|
||||
Uses only the covered model path. This is collision association, not a lane
|
||||
identity or clearance guarantee; the straight forward corridor remains checked.
|
||||
"""
|
||||
import math
|
||||
|
||||
|
||||
def _clip(polygon, axis, bound, upper):
|
||||
result=[]
|
||||
for a,b in zip(polygon,polygon[1:]+polygon[:1]):
|
||||
inside_a=a[axis]<=bound if upper else a[axis]>=bound
|
||||
inside_b=b[axis]<=bound if upper else b[axis]>=bound
|
||||
if inside_a:result.append(a)
|
||||
if inside_a != inside_b:
|
||||
t=(bound-a[axis])/(b[axis]-a[axis])
|
||||
result.append(tuple(a[i]+t*(b[i]-a[i]) for i in (0,1)))
|
||||
return result
|
||||
|
||||
|
||||
def collision_gap(actor,plan=None,own_front=0.,half_width=1.5):
|
||||
"""Nearest oriented-box contact along a swept path, in metres."""
|
||||
forward,left,length,width,heading=(actor[k] for k in
|
||||
('forward_m','left_m','length_m','width_m','heading_delta_rad'))
|
||||
if not all(math.isfinite(v) for v in (forward,left,length,width,heading,own_front,half_width)):
|
||||
return None
|
||||
c,s=math.cos(heading),math.sin(heading)
|
||||
box=[(forward+u*c-v*s,left+u*s+v*c)
|
||||
for u,v in ((-length/2,-width/2),(length/2,-width/2),
|
||||
(length/2,width/2),(-length/2,width/2))]
|
||||
paths=[('forward footprint',[(0.,0.),(100.,0.)])]
|
||||
try:
|
||||
x,y=list(plan.x),list(plan.y)
|
||||
if len(x)==len(y)==33 and all(math.isfinite(v) for v in x+y) and 0<=x[0]<=5:
|
||||
points=[(0.,0.)]
|
||||
for index,(px,py) in enumerate(zip(x,y)):
|
||||
if index and px<=x[index-1]+1e-4:break
|
||||
if px>100:break
|
||||
if px>0:points.append((float(px),-float(py)))
|
||||
if len(points)>1:paths.append(('covered model footprint',points))
|
||||
except (AttributeError,TypeError,ValueError):pass
|
||||
best=None
|
||||
for source,points in paths:
|
||||
travelled=0.
|
||||
for a,b in zip(points,points[1:]):
|
||||
dx,dy=b[0]-a[0],b[1]-a[1]
|
||||
segment=math.hypot(dx,dy)
|
||||
if segment<1e-6:continue
|
||||
ux,uy=dx/segment,dy/segment
|
||||
polygon=[((p[0]-a[0])*ux+(p[1]-a[1])*uy,
|
||||
-(p[0]-a[0])*uy+(p[1]-a[1])*ux) for p in box]
|
||||
for axis,bound,upper in ((0,0.,False),(0,segment,True),
|
||||
(1,-half_width,False),(1,half_width,True)):
|
||||
polygon=_clip(polygon,axis,bound,upper)
|
||||
if not polygon:break
|
||||
if polygon:
|
||||
distance=max(.1,travelled+min(p[0] for p in polygon)-own_front)
|
||||
if best is None or distance<best['distance_m']:
|
||||
best=dict(distance_m=distance,collision_path_source=source)
|
||||
travelled+=segment
|
||||
return best
|
||||
@@ -0,0 +1,314 @@
|
||||
"""Experimental permissive-green entry from observed native traffic gaps.
|
||||
|
||||
This is NOT protected-phase or exhaustive right-of-way arbitration. Exact
|
||||
semaphore binding supplies stop/go, an explicit authored priority modifier
|
||||
resolves the selected curve's priority value, and every observed conflict is
|
||||
yielded to regardless of nominal priority. Unknown/additive/inherited priority,
|
||||
unmeasured traffic, incomplete traversal and source expiry keep entry on hold.
|
||||
|
||||
Primary semantics: SCS Prefab_Locators#Navigation_Point and ATS 1.29 priority
|
||||
modifier documentation. Profiles distinguish protected/permissive left turns;
|
||||
profile overrides/conflict tables are not yet qualified here. Protection stays
|
||||
unknown even when this bounded, repeatedly assessed gap policy allows entry.
|
||||
"""
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
from control.native_collision_path import _clip
|
||||
from control.native_following import native_lead, _vector, _dimensions
|
||||
from control.native_signal_planner import NativeSignalPlanner, fresh, projection
|
||||
from control.native_path import ordered_path
|
||||
from telemetry.driving_scene import number
|
||||
from telemetry.native_signals import PRIORITY_SOURCE, RULES_SHA256
|
||||
|
||||
|
||||
LOCATOR_SOURCE = 'https://modding.scssoft.com/wiki/Documentation/Tools/SCS_Blender_Tools/Locators/Prefab_Locators'
|
||||
RULE_SOURCE = 'https://modding.scssoft.com/wiki/Games/ATS/Modding_guides/1.29#Priority_modifier'
|
||||
HORIZON_S = 6.
|
||||
STEP_S = .25
|
||||
ENTRY_SPEED_CAP_MPS = 8.
|
||||
PROJECTION_ACCEL_MPS2 = 2.
|
||||
|
||||
|
||||
def _empty(now, reason):
|
||||
return dict(available=False, sampled_at=now, age_s=0., state='hold',reason=reason,
|
||||
proceed_authorized=False,experimental_proceed=False,observed_clearance=False,
|
||||
priority_semantics_resolved=False,protected_phase_verified=False,
|
||||
intersection_priority_verified=False,complete_coverage=False,
|
||||
exhaustive_future_clearance=False,conflicts=[],
|
||||
source='Experimental native signal / observed traffic gap policy')
|
||||
|
||||
|
||||
def _prepare_sweep(path):
|
||||
a,b=path[:-1],path[1:]
|
||||
delta=b-a
|
||||
lengths=np.linalg.norm(delta[:,:2],axis=1)
|
||||
tangent=np.divide(delta[:,:2],lengths[:,None],out=np.zeros((len(lengths),2)),
|
||||
where=lengths[:,None]>1e-6)
|
||||
return dict(a=a,b=b,lengths=lengths,tangent=tangent,
|
||||
travelled=np.r_[0.,np.cumsum(lengths)[:-1]])
|
||||
|
||||
|
||||
def _intervals(center, dimensions, heading, path, half_width, vertical):
|
||||
"""Observed/projected box intersections with the covered swept path."""
|
||||
length,width,height = dimensions
|
||||
c,s = math.cos(heading),-math.sin(heading)
|
||||
box = [(center[0]+u*c-v*s,center[1]+u*s+v*c) for u,v in
|
||||
((-length/2,-width/2),(length/2,-width/2),(length/2,width/2),(-length/2,width/2))]
|
||||
bottom,top = -center[2]-height/2,-center[2]+height/2
|
||||
sweep=path if isinstance(path,dict) else _prepare_sweep(path)
|
||||
offsets=np.asarray(center[:2])-sweep['a'][:,:2]
|
||||
tangent=sweep['tangent']
|
||||
along=np.sum(offsets*tangent,axis=1)
|
||||
normal=-offsets[:,0]*tangent[:,1]+offsets[:,1]*tangent[:,0]
|
||||
radius=math.hypot(dimensions[0],dimensions[1])/2.
|
||||
candidates=np.flatnonzero((sweep['lengths']>1e-6) & (along>=-radius-1e-8)
|
||||
& (along<=sweep['lengths']+radius+1e-8) & (np.abs(normal)<=half_width+radius+1e-8))
|
||||
found=[]
|
||||
for index in candidates:
|
||||
a,b=sweep['a'][index],sweep['b'][index]
|
||||
travelled=float(sweep['travelled'][index])
|
||||
d=b-a;length=float(np.linalg.norm(d[:2]))
|
||||
if length < 1e-6:continue
|
||||
ux,uy=d[:2]/length
|
||||
polygon=[((p[0]-a[0])*ux+(p[1]-a[1])*uy,-(p[0]-a[0])*uy+(p[1]-a[1])*ux) for p in box]
|
||||
for axis,bound,upper in ((0,0.,False),(0,length,True),(1,-half_width,False),(1,half_width,True)):
|
||||
polygon=_clip(polygon,axis,bound,upper)
|
||||
if not polygon:break
|
||||
ground,slope=-a[2],-d[2]/length
|
||||
lower,upper=bottom-vertical[1]-.1,top-vertical[0]+.1
|
||||
if polygon and abs(slope)<1e-8:
|
||||
if not lower<=ground<=upper:polygon=[]
|
||||
elif polygon:
|
||||
low,high=sorted(((lower-ground)/slope,(upper-ground)/slope))
|
||||
polygon=_clip(polygon,0,low,False)
|
||||
if polygon:polygon=_clip(polygon,0,high,True)
|
||||
if polygon:
|
||||
found.append((travelled+min(p[0] for p in polygon),
|
||||
travelled+max(p[0] for p in polygon),float(ux),float(uy)))
|
||||
return found
|
||||
|
||||
|
||||
def _progress(speed, seconds):
|
||||
acceleration=PROJECTION_ACCEL_MPS2
|
||||
cap=max(speed,ENTRY_SPEED_CAP_MPS)
|
||||
ramp=min(seconds,max(0.,(cap-speed)/acceleration))
|
||||
return speed*ramp+.5*acceleration*ramp*ramp+cap*(seconds-ramp)
|
||||
|
||||
|
||||
def _body_overlap(a, dimensions_a, heading_a, b, dimensions_b, heading_b):
|
||||
"""Oriented measured-body overlap, including bodies behind path origin."""
|
||||
if abs(float(a[2]-b[2])) > (dimensions_a[2]+dimensions_b[2])/2+.1:
|
||||
return False
|
||||
def axes(heading):
|
||||
c,s=math.cos(heading),-math.sin(heading)
|
||||
return np.array([c,s]),np.array([-s,c])
|
||||
aa,bb=axes(heading_a),axes(heading_b)
|
||||
difference=(a-b)[:2]
|
||||
for axis in (*aa,*bb):
|
||||
reach_a=sum(abs(float(axis@direction))*length/2 for direction,length in zip(aa,dimensions_a[:2]))
|
||||
reach_b=sum(abs(float(axis@direction))*length/2 for direction,length in zip(bb,dimensions_b[:2]))
|
||||
if abs(float(difference@axis)) > reach_a+reach_b+.15:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
class NativeCrossingPlanner:
|
||||
"""Stateless: permission expires with the current scene and green phase."""
|
||||
def reset(self):
|
||||
pass
|
||||
|
||||
def assess(self,scene,native_plan=None,signal_plan=None,following=None):
|
||||
now=number(scene.get('sampled_at'))
|
||||
if now is None:raise ValueError('Finite crossing scene time required')
|
||||
result=_empty(now,'Fresh route-specific green and traffic evidence required')
|
||||
plan=native_plan if native_plan is not None else scene.get('native_plan')
|
||||
supplied=signal_plan if signal_plan is not None else scene.get('signal_plan',scene.get('native_signal_plan'))
|
||||
try:
|
||||
if not isinstance(plan,dict) or not fresh(plan,now,.35):
|
||||
raise ValueError('Fresh selected native route path required')
|
||||
exact=NativeSignalPlanner().assess(scene,plan)
|
||||
match_fields=('route_revision','selected_lane_id','phase','phase_code','phase_sampled_at','association')
|
||||
if (isinstance(supplied,dict) and supplied.get('retained_stop') is True
|
||||
and any(supplied.get(k)!=exact.get(k) for k in match_fields)):
|
||||
# Only an existing controller hold may nominate a just-passed
|
||||
# point. Recompute its exact authored/live evidence rather
|
||||
# than trusting remembered phase or supplied geometry. The
|
||||
# normal main signal result never nominates crossed points.
|
||||
exact=next((candidate for candidate in exact.get('passed_stop_points',[])
|
||||
if all(supplied.get(k)==candidate.get(k) for k in match_fields)),None)
|
||||
if exact is None:
|
||||
raise ValueError('Retained stop does not match a freshly verified passed stop point')
|
||||
exact=dict(exact,state=('proceed' if exact.get('phase')=='green'
|
||||
and (exact.get('stop_point') or {}).get('traffic_rule')=='cross_line' else 'unknown'))
|
||||
result['retained_stop']=True
|
||||
if not isinstance(supplied,dict) or any(supplied.get(k)!=exact.get(k) for k in match_fields):
|
||||
raise ValueError('Signal plan does not match the current route and live phase')
|
||||
result.update(available=exact.get('available') is True,route_revision=exact.get('route_revision'),
|
||||
association=exact.get('association'),phase=exact.get('phase'))
|
||||
if exact.get('phase')!='green' or exact.get('state')!='proceed' or exact.get('signal_phase_verified') is not True:
|
||||
raise ValueError('Exact governed green phase required; stop/yield rules remain active')
|
||||
if exact.get('front_geometry_verified') is not True:
|
||||
raise ValueError('Verified native truck front required')
|
||||
sources=scene['sources'];signals=sources['signals']['data'];graph=sources['lane_graph']['data']
|
||||
association=exact['association']
|
||||
lane=next(l for l in graph['lanes'] if l['id']==exact['selected_lane_id'])
|
||||
if lane.get('prefab_uid')!=association['prefab_uid']:
|
||||
raise ValueError('Selected intersection prefab differs from live signal')
|
||||
governed=next(c for c in lane['curves'] if c['curve_index']==association['governed_curve_index'])
|
||||
flags=governed.get('flags')
|
||||
if type(flags) is not int or not 0<=flags<=0xffffffff:
|
||||
raise ValueError('Authored curve priority flags unavailable')
|
||||
priority,additive=(flags>>16)&15,bool(flags&0x8000)
|
||||
if additive or priority not in (4,5,6,10,11,12) or flags&3:
|
||||
raise ValueError('Inherited/additive or unsupported intersection priority is unresolved')
|
||||
# A supported absolute value is not evidence of a protected phase.
|
||||
# Additional authored rules can change entry obligations; defer
|
||||
# those until rule history/stop completion are implemented.
|
||||
allowed_rules={'','cross_line','cross_end','no_priority'}
|
||||
if any(c.get('traffic_rule','') not in allowed_rules for c in lane['curves']):
|
||||
raise ValueError('Additional authored intersection priority/stop rule unresolved')
|
||||
definition=signals.get('traffic_rule_definition') or {}
|
||||
if definition.get('verified') is not True or definition.get('sha256')!=RULES_SHA256:
|
||||
raise ValueError('Installed traffic-rule definitions unqualified')
|
||||
live=next(s for s in signals['signals'] if s['prefab_uid']==association['prefab_uid']
|
||||
and s['semaphore_id']==association['semaphore_id'])
|
||||
remaining=number(live.get('time_remaining_s'))
|
||||
if remaining is not None:
|
||||
remaining-=max(0.,now-signals['sampled_at'])
|
||||
if remaining is None or remaining<=.5:
|
||||
raise ValueError('Green phase is ending or remaining time is unknown')
|
||||
result.update(priority_semantics_resolved=True,priority=dict(value=priority,additive=False,
|
||||
source=PRIORITY_SOURCE,rule_source=RULE_SOURCE,curve_index=governed['curve_index'],
|
||||
label={4:'minor left',5:'minor right',6:'minor straight',10:'major left',11:'major right',12:'major straight'}[priority],
|
||||
semantics='Explicit absolute curve priority; yield to every observed conflicting trajectory'),
|
||||
protection='unknown: permissive observed-gap policy',green_time_remaining_s=remaining)
|
||||
traffic_source=sources.get('traffic') or {};traffic=traffic_source.get('data') or {}
|
||||
if traffic_source.get('fresh') is not True or not fresh(traffic,now,.3):
|
||||
raise ValueError('Fresh native traffic required for intersection entry')
|
||||
if (traffic.get('latest_read_failed') or traffic.get('trailer_chain_traversal_complete') is not True
|
||||
or traffic.get('truncated_trailer_chains')):
|
||||
raise ValueError('Complete observed native traversal required; no torn/reused/truncated feed')
|
||||
actors=traffic.get('actors')
|
||||
count=traffic.get('observed_actor_count')
|
||||
if (not isinstance(actors,list) or len(actors)>500 or type(count) is not int
|
||||
or not len(actors)+1<=count<=500):
|
||||
raise ValueError('Native actor traversal count unqualified')
|
||||
data=dict(scene['sdk'],nearby_traffic=traffic)
|
||||
current_following=native_lead(plan,data,now) if following is None else following
|
||||
if not isinstance(current_following,(tuple,list)) or len(current_following)!=2:
|
||||
raise ValueError('Current native following assessment required')
|
||||
lead,diagnostics=current_following
|
||||
if (not isinstance(diagnostics,dict) or diagnostics.get('available') is not True
|
||||
or diagnostics.get('ego_geometry_verified') is not True
|
||||
or diagnostics.get('selected_path_available') is not True
|
||||
or diagnostics.get('acceleration_inhibited') is not False
|
||||
or diagnostics.get('sampled_at')!=traffic.get('sampled_at')):
|
||||
raise ValueError('Current native footprint/traffic assessment is incomplete')
|
||||
sdk=scene['sdk'];ego=_vector(sdk['world_position']);rotation=_vector(sdk['world_rotation'])
|
||||
speed=number(sdk.get('speed_mps'))
|
||||
if speed is None or not -.02<=speed<=70.:raise ValueError('Forward speed required')
|
||||
speed=max(0.,speed);yaw=rotation[0]*2*math.pi
|
||||
forward=np.array([-math.sin(yaw),-math.cos(yaw)]);right=np.array([-forward[1],forward[0]])
|
||||
def local(position):
|
||||
d=_vector(position)-ego
|
||||
return np.array([d[[0,2]]@forward,d[[0,2]]@right,-d[1]])
|
||||
path=ordered_path(plan)
|
||||
if np.linalg.norm(path[0])>1e-6:path=np.vstack((np.zeros(3),path))
|
||||
# Require coverage through the authored prefab exit. A short
|
||||
# approach preview cannot authorize stopping halfway across it.
|
||||
exit_local=local(lane['curves'][-1]['end'])
|
||||
exit_hit=projection(exit_local,path)
|
||||
coverage=sum(float(np.linalg.norm((b-a)[:2])) for a,b in zip(path,path[1:]))
|
||||
if (exit_hit is None or exit_hit['error']>.6 or exit_hit['height']>.3
|
||||
or exit_hit['distance']<=exact['reference_distance_m']+.5):
|
||||
raise ValueError('Selected native path does not cover the authored intersection exit')
|
||||
result['authored_exit_distance_m']=exit_hit['distance']
|
||||
front=diagnostics['own_front_extent_m'];half_width=diagnostics['own_half_width_m']
|
||||
vertical=list(diagnostics['own_vertical_extent_m']);rear=0.
|
||||
own_bodies=[]
|
||||
measured=_vector(traffic['ego_world_position']);measured_yaw=traffic['ego_world_yaw_rad']
|
||||
mf=np.array([-math.sin(measured_yaw),-math.cos(measured_yaw)]);mr=np.array([-mf[1],mf[0]])
|
||||
for body in [traffic['ego_vehicle']]+traffic['ego_trailers']:
|
||||
length,width,height=_dimensions(body);d=_vector(body['world_position'])-measured
|
||||
angle=body['world_heading_rad']-measured_yaw;c,s=abs(math.cos(angle)),abs(math.sin(angle))
|
||||
own_bodies.append((np.array([d[[0,2]]@mf,d[[0,2]]@mr,-d[1]]),
|
||||
(length,width,height),angle,body['id']))
|
||||
rear=max(rear,-float(d[[0,2]]@mf)+c*length/2+s*width/2)
|
||||
half_width=max(half_width,abs(float(d[[0,2]]@mr))+s*length/2+c*width/2+.15)
|
||||
vertical=[min(vertical[0],float(d[1]-height/2)),max(vertical[1],float(d[1]+height/2))]
|
||||
# Stop/go clearance uses all measured own bodies, not just the cab.
|
||||
if rear>150. or half_width>10.:raise ValueError('Articulated intersection footprint exceeds supported bound')
|
||||
times=np.arange(0.,HORIZON_S+STEP_S/2,STEP_S)
|
||||
sweep=_prepare_sweep(path)
|
||||
earliest=next((float(t) for t in times if _progress(speed,float(t))>=max(0.,exact['stop_distance_m'])),None)
|
||||
if earliest is None or remaining<earliest+.5:
|
||||
raise ValueError('Green is too short for the projected entry approach')
|
||||
result.update(observed_traversal_complete=True,actor_count=len(actors),
|
||||
footprint=dict(front_m=front,rear_m=rear,half_width_m=half_width,vertical_m=vertical),
|
||||
prediction=dict(horizon_s=HORIZON_S,step_s=STEP_S,acceleration_mps2=PROJECTION_ACCEL_MPS2,
|
||||
entry_speed_cap_mps=ENTRY_SPEED_CAP_MPS,position_prediction='Measured constant world velocity',
|
||||
complete_future_prediction=False),following_constraints=[])
|
||||
for actor in actors:
|
||||
dimensions=_dimensions(actor);center=local(actor['world_position'])
|
||||
velocity=_vector(actor.get('world_velocity_mps'))
|
||||
interval=number(actor.get('motion_interval_s'));age=number(actor.get('measured_age_s'))
|
||||
confidence=number(actor.get('motion_confidence'));heading=number(actor.get('world_heading_rad'))
|
||||
if (actor.get('motion_available') is not True or type(actor.get('sample_count')) is not int
|
||||
or not 3<=actor['sample_count']<=5 or interval is None or not .08<=interval<=2.4
|
||||
or age is None or not 0<=age<=.3 or confidence is None or not 0<confidence<=1.
|
||||
or np.linalg.norm(velocity)>70. or heading is None):
|
||||
raise ValueError('Measured crossing motion unavailable for actor '+str(actor.get('id')))
|
||||
local_velocity=np.array([velocity[[0,2]]@forward,velocity[[0,2]]@right,-velocity[1]])
|
||||
# Existing longitudinal following remains responsible for a
|
||||
# moving queue's same-direction nearest body and trailer chain.
|
||||
matched=bool(lead and (actor['id']==lead.get('id') or actor.get('chain_root_id')
|
||||
and actor['chain_root_id'] in (lead.get('id'),lead.get('chain_root_id'))))
|
||||
intervals=_intervals(center,dimensions,heading-yaw,sweep,half_width,vertical)
|
||||
if matched and intervals and lead.get('motion_verified_for_following') is True:
|
||||
_,_,ux,uy=intervals[0]
|
||||
aligned=math.cos(heading-yaw)*ux-math.sin(heading-yaw)*uy
|
||||
if (aligned>=.85 and local_velocity[0]*ux+local_velocity[1]*uy>.3
|
||||
and lead['distance_m']>=max(4.,speed)):
|
||||
result['following_constraints'].append(actor['id']);continue
|
||||
# Between-step expansion covers constant-velocity translation;
|
||||
# growth after that is a modest measurement uncertainty margin.
|
||||
for t in times:
|
||||
expansion=float(np.linalg.norm(local_velocity[:2]))*STEP_S+.15*float(t)
|
||||
envelope=(dimensions[0]+expansion,dimensions[1]+expansion,dimensions[2]+abs(local_velocity[2])*STEP_S)
|
||||
projected=center+local_velocity*t
|
||||
# The route begins at the tractor. Check actual attached
|
||||
# body occupancy separately so no rear trailer is erased
|
||||
# by clipping the forward path at s=0. Remaining stopped
|
||||
# is one possible entry response, hence these observations
|
||||
# remain a conservative occupancy constraint over the
|
||||
# short projection window; no rear lane is fabricated.
|
||||
rear_hit=next((body for body in own_bodies if _body_overlap(projected,envelope,heading-yaw,
|
||||
body[0],body[1],body[2])),None)
|
||||
if rear_hit is not None:
|
||||
result['conflicts'].append(dict(actor_id=actor['id'],chain_root_id=actor.get('chain_root_id'),
|
||||
time_to_conflict_s=float(t),own_body_id=rear_hit[3],
|
||||
source='Projected actor overlaps a measured current own body'))
|
||||
break
|
||||
intervals=_intervals(projected,envelope,heading-yaw,sweep,half_width,vertical)
|
||||
low=max(0.,speed*t-t*t)-rear
|
||||
high=_progress(speed,float(t))+front
|
||||
hit=next((i for i in intervals if i[0]<=high and i[1]>=low),None)
|
||||
if hit is not None:
|
||||
result['conflicts'].append(dict(actor_id=actor['id'],chain_root_id=actor.get('chain_root_id'),
|
||||
time_to_conflict_s=float(t),path_distance_interval_m=[float(hit[0]),float(hit[1])],
|
||||
source='Measured motion intersects possible ego/own-trailer occupancy'))
|
||||
break
|
||||
if result['conflicts']:
|
||||
raise ValueError('Observed crossing or occupied-exit conflict: yield')
|
||||
result['observed_clearance']=True
|
||||
if plan.get('usable_for_control') is not True or plan.get('lane_membership_verified') is not True:
|
||||
raise ValueError('Observed gap only; selected native path is not control-qualified')
|
||||
result.update(available=True,state='proceed',proceed_authorized=True,experimental_proceed=True,
|
||||
reason='Experimental permissive green: explicit authored priority and no observed conflict',
|
||||
entry_speed_cap_mps=ENTRY_SPEED_CAP_MPS,valid_for_s=.2,
|
||||
semantics_source=LOCATOR_SOURCE)
|
||||
except (KeyError,TypeError,ValueError,OverflowError,StopIteration) as exc:
|
||||
result['reason']=str(exc) or 'Required native crossing evidence unavailable'
|
||||
return result
|
||||
@@ -0,0 +1,222 @@
|
||||
"""Battery-triggered native station detours; game GPS/job destination stays intact."""
|
||||
import copy
|
||||
import hashlib
|
||||
import heapq
|
||||
import math
|
||||
from pathlib import Path
|
||||
import threading
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
|
||||
from control.native_route_planner import closest
|
||||
from control.native_trip_planner import _connections, _lateral, _length, _qualified, compile_trip
|
||||
from control.native_path import ordered_path
|
||||
from telemetry.native_stations import load_station_catalog
|
||||
from ui.power_status import power_status
|
||||
|
||||
|
||||
def charging_stop_gap(data,plan,now):
|
||||
energy=data.get('energy_navigation') or {}
|
||||
stamp=energy.get('sampled_at')
|
||||
if (energy.get('active') is not True or energy.get('route_revision')!=plan.get('route_revision')
|
||||
or energy.get('stop_lane_id') not in (plan.get('selected_lane_ids') or [])
|
||||
or not isinstance(stamp,(int,float)) or not math.isfinite(stamp)
|
||||
or not 0.<=now-stamp<=.5):return None
|
||||
try:
|
||||
point=np.asarray(energy['stop_position'],float)-np.asarray(data['world_position'],float)
|
||||
if point.shape!=(3,) or not np.isfinite(point).all():return None
|
||||
yaw=data['world_rotation'][0]*2*math.pi
|
||||
forward=np.array([-math.sin(yaw),-math.cos(yaw)])
|
||||
local=np.array([point[[0,2]]@forward,-point[0]*forward[1]+point[2]*forward[0],-point[1]])
|
||||
path=ordered_path(plan);delta=path[1:]-path[:-1]
|
||||
lengths=np.linalg.norm(delta[:,:2],axis=1)
|
||||
fraction=np.clip(np.sum((local-path[:-1])[:,:2]*delta[:,:2],axis=1)/lengths**2,0.,1.)
|
||||
projected=path[:-1]+fraction[:,None]*delta
|
||||
index=int(np.argmin(np.linalg.norm(projected-local,axis=1)))
|
||||
if np.linalg.norm((projected[index]-local)[:2])>3. or abs(projected[index,2]-local[2])>1.:return None
|
||||
distance=float(lengths[:index].sum()+fraction[index]*lengths[index])
|
||||
front=(data.get('nearby_traffic') or {}).get('own_front_extent_m')
|
||||
if not isinstance(front,(int,float)) or not math.isfinite(front) or not 0<=front<=20:return None
|
||||
return max(0.,distance-front-.5)
|
||||
except (KeyError,TypeError,ValueError):return None
|
||||
|
||||
|
||||
def station_plan(reader,data,stations):
|
||||
"""Nearest reachable gas service by directed lane distance, not air distance.
|
||||
|
||||
Pump locations do not authorize new splines. Only connected qualified
|
||||
source lanes reaching the pump area are candidates for automatic driving.
|
||||
"""
|
||||
if not reader.cache or reader.reason or reader.verify_sources is not True:
|
||||
raise ValueError('Verified native graph required')
|
||||
lanes={lane['id']:lane for lane in reader.cache['lanes'] if _qualified(lane)
|
||||
and lane.get('player_truck_access') is not False and lane.get('large_vehicle_suitable') is not False}
|
||||
successors=_connections(lanes,reader.cache['connections'])
|
||||
groups=[g for g in (getattr(reader,'permission_report',None) or {}).get('road_permissions',{}).values() if g.get('available') is True]
|
||||
permissions=dict(available=bool(groups),boundaries=[b for g in groups for b in g.get('boundaries',())])
|
||||
lateral=_lateral(lanes,permissions)
|
||||
position=np.asarray(data['world_position'],float);yaw=data['world_rotation'][0]*2.*math.pi
|
||||
forward=np.array([-math.sin(yaw),-math.cos(yaw)])
|
||||
candidates=[];lengths={key:_length(lane) for key,lane in lanes.items()}
|
||||
for key,lane in lanes.items():
|
||||
# Cheap envelope avoids projection against the complete mounted map.
|
||||
points=lane['centerline']
|
||||
if not (min(p[0] for p in points)-2.<=position[0]<=max(p[0] for p in points)+2.
|
||||
and min(p[2] for p in points)-2.<=position[2]<=max(p[2] for p in points)+2.):continue
|
||||
hit=closest(points,position,forward)
|
||||
if hit and hit['error_m']<=1.75 and hit['height_error_m']<=.75 and hit['heading_dot']>=.97:
|
||||
progress=sum(math.hypot(b[0]-a[0],b[2]-a[2]) for a,b in zip(points[:hit['index']],points[1:hit['index']+1]))
|
||||
progress+=hit['fraction']*math.hypot(points[hit['index']+1][0]-points[hit['index']][0],points[hit['index']+1][2]-points[hit['index']][2])
|
||||
candidates.append((hit['score'],key,progress))
|
||||
if not candidates:raise ValueError('Align with a supported lane to plan the charging detour')
|
||||
candidates.sort();_,start,start_progress=candidates[0]
|
||||
targets={}
|
||||
by_prefab={}
|
||||
for key,lane in lanes.items():
|
||||
if lane.get('kind')=='prefab':by_prefab.setdefault(lane.get('prefab_uid'),[]).append(key)
|
||||
for station in stations:
|
||||
if station.get('location_verified') is not True:continue
|
||||
pump=np.asarray(station['position'],float)
|
||||
for key in by_prefab.get(station['prefab_uid'],[]):
|
||||
points=np.asarray(lanes[key]['centerline'],float)
|
||||
delta=points[1:]-points[:-1];distance=np.linalg.norm(delta[:,[0,2]],axis=1)
|
||||
fraction=np.clip(np.sum((pump-points[:-1])[:,[0,2]]*delta[:,[0,2]],axis=1)/np.maximum(distance**2,1e-9),0.,1.)
|
||||
projected=points[:-1]+fraction[:,None]*delta
|
||||
error=np.linalg.norm((projected-pump)[:,[0,2]],axis=1)
|
||||
indices=np.flatnonzero((error<=12.) & (np.abs(projected[:,1]-pump[1])<=1.))
|
||||
if not len(indices):continue
|
||||
index=int(indices[np.argmin(error[indices])])
|
||||
progress=float(distance[:index].sum()+fraction[index]*distance[index])
|
||||
if key==start and progress<start_progress+3.:continue
|
||||
entry=dict(station=station,stop_progress_m=progress,stop_position=projected[index].tolist())
|
||||
targets.setdefault(key,[]).append(entry)
|
||||
if not targets:raise ValueError('No mapped station has a supported driving path to its pump area')
|
||||
queue=[(0.,start)];cost={start:0.};parent={};best=None;visits=0
|
||||
while queue and visits<10000:
|
||||
value,key=heapq.heappop(queue)
|
||||
if value!=cost.get(key) or best and value>best[0]:continue
|
||||
visits+=1
|
||||
for target in targets.get(key,[]):
|
||||
travel=value+target['stop_progress_m']-(start_progress if key==start else 0.)
|
||||
if travel>=0 and (best is None or travel<best[0]):best=(travel,key,target)
|
||||
exit_cost=value+lengths[key]-(start_progress if key==start else 0.)
|
||||
for following in successors.get(key,[]):
|
||||
if exit_cost<cost.get(following,math.inf):
|
||||
cost[following]=exit_cost;parent[following]=key;heapq.heappush(queue,(exit_cost,following))
|
||||
for following in lateral.get(key,[]):
|
||||
change_cost=value+5.
|
||||
if change_cost<cost.get(following,math.inf):
|
||||
cost[following]=change_cost;parent[following]=key;heapq.heappush(queue,(change_cost,following))
|
||||
if best is None:raise ValueError('No connected supported route reaches a station from this lane')
|
||||
distance,key,target=best;path=[key]
|
||||
while key in parent:key=parent[key];path.append(key)
|
||||
path.reverse()
|
||||
scale=data.get('local_scale',1.)
|
||||
if not isinstance(scale,(int,float)) or not math.isfinite(scale) or not 1.<=scale<=40.:raise ValueError('Valid map distance scale required')
|
||||
miles=distance*scale/1609.344
|
||||
available_range=power_status(data)['range_miles']
|
||||
if available_range is not None and miles>available_range*.9:
|
||||
raise ValueError('Nearest supported station exceeds estimated remaining range reserve')
|
||||
# Real authored node identities/poses only. The lane policy pins every
|
||||
# branch to the connected lane chain used by the station search.
|
||||
selected=[lanes[k] for k in path];nodes=[]
|
||||
for lane in selected:
|
||||
if not nodes:nodes.append(dict(uid=str(lane['start_node_uid']),position=list(lane['centerline'][0])))
|
||||
if nodes[-1]['uid']!=str(lane['end_node_uid']):
|
||||
nodes.append(dict(uid=str(lane['end_node_uid']),position=list(lane['centerline'][-1])))
|
||||
remaining=0.
|
||||
for index in range(len(nodes)-1,-1,-1):
|
||||
nodes[index]['distance_to_end_m']=remaining
|
||||
if index:remaining+=math.dist(nodes[index-1]['position'],nodes[index]['position'])*scale
|
||||
revision='charge-'+hashlib.sha256(('|'.join(path)+'|'+target['station']['id']).encode()).hexdigest()[:20]
|
||||
route=dict(available=True,usable_for_control=False,revision=revision,route_revision=revision,nodes=nodes,
|
||||
navigation_distance_m=remaining,source='Native battery station detour',estimated_distance=True)
|
||||
graph=dict(source_verified=True,lanes=selected,connections=[edge for edge in reader.cache['connections']
|
||||
if edge['from_lane_id'] in path and edge['to_lane_id'] in path])
|
||||
trip=compile_trip(route,graph,cache_sha256=reader.provenance['cache_sha256'],permissions=permissions)
|
||||
if not trip['complete']:raise ValueError('Charging detour has unresolved lane connections')
|
||||
return dict(route=route,trip_plan=trip,station=target['station'],lane_ids=path,
|
||||
stop_lane_id=path[-1],stop_position=target['stop_position'],distance_miles=miles,
|
||||
stop_progress_m=target['stop_progress_m'],graph_sha256=reader.provenance['cache_sha256'])
|
||||
|
||||
|
||||
class NativeEnergyNavigation:
|
||||
TRIGGER_PERCENT=20.
|
||||
RESUME_PERCENT=90.
|
||||
|
||||
def __init__(self,clock=time.monotonic):
|
||||
self.clock=clock;self._lock=threading.Lock();self._thread=None
|
||||
self._result=None;self._reason='';self._reader=None;self._stations=None
|
||||
self._retry_at=0.;self._generation=0;self._closed=False;self._latched=False
|
||||
|
||||
def _build(self,reader,data,generation):
|
||||
try:
|
||||
stations=self._stations if reader is self._reader and self._stations is not None else load_station_catalog(reader.cache,Path(reader.provenance['cache_path']).parent)
|
||||
result=station_plan(reader,data,stations);reason=''
|
||||
except Exception as exc:result=None;reason=str(exc)
|
||||
with self._lock:
|
||||
if generation==self._generation and not self._closed:
|
||||
self._reader=reader;self._stations=locals().get('stations')
|
||||
self._result=result;self._reason=reason;self._retry_at=self.clock()+3.
|
||||
|
||||
def snapshot(self,data,original_route,manager):
|
||||
now=self.clock();power=power_status(data);percent=power['percent']
|
||||
status=dict(active=False,state='idle',trigger_percent=self.TRIGGER_PERCENT,charge_target_percent=self.RESUME_PERCENT,battery_percent=percent,
|
||||
reason='',original_destination_preserved=True,game_gps_modified=False)
|
||||
amount,capacity=data.get('fuel_amount_l'),data.get('fuel_capacity_l')
|
||||
valid=(data.get('valid') is True and not data.get('paused') and power['electric']
|
||||
and percent is not None and isinstance(amount,(int,float)) and isinstance(capacity,(int,float))
|
||||
and math.isfinite(amount) and math.isfinite(capacity) and 0.<=amount<=capacity and capacity>0.)
|
||||
if not valid:return dict(status,state='unavailable',reason='Fresh battery telemetry required'),original_route,None
|
||||
if percent>=self.RESUME_PERCENT:
|
||||
with self._lock:
|
||||
self._generation+=1;self._result=None;self._latched=False
|
||||
return dict(status,state='resumed' if self._reader else 'idle'),original_route,None
|
||||
if percent<=self.TRIGGER_PERCENT:self._latched=True
|
||||
if not self._latched:return status,original_route,None
|
||||
reader=manager.reader
|
||||
with self._lock:
|
||||
result=self._result
|
||||
if result and reader is not self._reader and reader.cache and not reader.reason:
|
||||
old_identity=getattr(self._reader,'source_identity',None)
|
||||
wanted=set(result['lane_ids'])
|
||||
found={lane['id'] for lane in reader.cache['lanes'] if lane['id'] in wanted and _qualified(lane)
|
||||
and lane.get('player_truck_access') is not False and lane.get('large_vehicle_suitable') is not False}
|
||||
if old_identity is not None and old_identity==getattr(reader,'source_identity',None) and found==wanted:
|
||||
# Background graph expansion must not switch back to the
|
||||
# job route midway through a charging turn. The mounted
|
||||
# source identities and every selected lane still agree.
|
||||
result=dict(result,trip_plan=dict(result['trip_plan'],graph_sha256=reader.provenance['cache_sha256']),
|
||||
graph_sha256=reader.provenance['cache_sha256'])
|
||||
self._result=result;self._reader=reader
|
||||
if result and (reader is not self._reader or reader.reason or reader.verify_sources is not True):
|
||||
result=None;self._result=None
|
||||
if result is None and (self._thread is None or not self._thread.is_alive()) and now>=self._retry_at:
|
||||
if reader.cache and not reader.reason and reader.verify_sources:
|
||||
self._generation+=1
|
||||
sampled={key:copy.deepcopy(data.get(key)) for key in ('world_position','world_rotation','local_scale',
|
||||
'truck_name','truck_model','engine_type','drivetrain_type','fuel_capacity_l','fuel_amount_l','fuel_range_km')}
|
||||
self._thread=threading.Thread(target=self._build,args=(reader,sampled,self._generation),
|
||||
name='ATS battery station planner',daemon=True)
|
||||
self._thread.start()
|
||||
reason=self._reason
|
||||
if result is None:
|
||||
return dict(status,state='waiting',reason=reason or 'Planning nearest supported charging/fuel stop'),original_route,None
|
||||
# Route progress is recomputed from the actual pose every snapshot.
|
||||
route=copy.deepcopy(result['route']);points=np.asarray([n['position'] for n in route['nodes']],float)
|
||||
position=np.asarray(data['world_position'],float);delta=points[1:]-points[:-1]
|
||||
fraction=np.clip(np.sum((position-points[:-1])*delta,axis=1)/np.maximum(np.sum(delta*delta,axis=1),1e-9),0.,1.)
|
||||
index=int(np.argmin(np.sum((points[:-1]+fraction[:,None]*delta-position)**2,axis=1)))
|
||||
route.update(sampled_at=now,age_s=0.,segment_index=index,segment_fraction=float(fraction[index]))
|
||||
remaining=max(0.,route['nodes'][index]['distance_to_end_m']-float(fraction[index])*
|
||||
(route['nodes'][index]['distance_to_end_m']-route['nodes'][index+1]['distance_to_end_m']))
|
||||
route['navigation_distance_m']=remaining
|
||||
status.update(active=True,state='routing',reason='Routing to charging/fuel stop',station=result['station'],
|
||||
distance_miles=remaining/1609.344,route_revision=route['revision'],
|
||||
stop_lane_id=result['stop_lane_id'],stop_position=result['stop_position'],sampled_at=now)
|
||||
return status,route,result['trip_plan']
|
||||
|
||||
def close(self):
|
||||
with self._lock:self._closed=True;self._generation+=1
|
||||
if self._thread is not None:self._thread.join(timeout=.5)
|
||||
@@ -0,0 +1,276 @@
|
||||
"""Pure native-actor following evidence; no model or actuator dependencies.
|
||||
|
||||
Bodies remain separately observed, including every foreign trailer. Cached
|
||||
actor positions are reprojected, never predicted. Unknown motion is treated as
|
||||
a stationary obstacle for braking, never as evidence that a queue departed.
|
||||
"""
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
from control.native_collision_path import _clip
|
||||
from control.native_path import ordered_path
|
||||
from telemetry.driving_scene import number
|
||||
|
||||
|
||||
def _vector(value):
|
||||
if not isinstance(value, (list, tuple)) or len(value) != 3 or any(number(v) is None for v in value):
|
||||
raise ValueError('Finite native world vector required')
|
||||
return np.asarray(value, float)
|
||||
|
||||
|
||||
def _dimensions(actor):
|
||||
result = [number(actor.get(k)) for k in ('length_m', 'width_m', 'height_m')]
|
||||
if any(v is None or not .2 <= v <= 60. for v in result):
|
||||
raise ValueError('Native body dimensions unavailable or invalid')
|
||||
return result
|
||||
|
||||
|
||||
def _fresh(report, now, limit=.3):
|
||||
stamp, age = number(report.get('sampled_at')), number(report.get('age_s'))
|
||||
return (report.get('available') is True and stamp is not None and age is not None
|
||||
and 0. <= age <= limit and 0. <= now-stamp <= limit)
|
||||
|
||||
|
||||
def _contact(center, dimensions, heading, paths, front, half_width, own_vertical):
|
||||
length, width, height = dimensions
|
||||
c, s = math.cos(heading), -math.sin(heading) # native yaw is positive to the left
|
||||
box = [(center[0]+u*c-v*s, center[1]+u*s+v*c) for u, v in
|
||||
((-length/2,-width/2),(length/2,-width/2),(length/2,width/2),(-length/2,width/2))]
|
||||
actor_bottom, actor_top = -center[2]-height/2, -center[2]+height/2
|
||||
best = None
|
||||
for source, points in paths:
|
||||
travelled = 0.
|
||||
for a, b in zip(points, points[1:]):
|
||||
delta = b-a
|
||||
length = float(np.linalg.norm(delta[:2]))
|
||||
if length < 1e-6:
|
||||
continue
|
||||
ux, uy = delta[:2]/length
|
||||
polygon = [((p[0]-a[0])*ux+(p[1]-a[1])*uy,
|
||||
-(p[0]-a[0])*uy+(p[1]-a[1])*ux) for p in box]
|
||||
for axis, bound, upper in ((0,0.,False),(0,length,True),
|
||||
(1,-half_width,False),(1,half_width,True)):
|
||||
polygon = _clip(polygon, axis, bound, upper)
|
||||
if not polygon:
|
||||
break
|
||||
# Clip by the actual selected path elevation as well. A vehicle on
|
||||
# an overpass must not become a road-level braking obstacle.
|
||||
ground, slope = -a[2], -delta[2]/length
|
||||
lower, upper = actor_bottom-own_vertical[1]-.1, actor_top-own_vertical[0]+.1
|
||||
if polygon and abs(slope) < 1e-8:
|
||||
if not lower <= ground <= upper:
|
||||
polygon = []
|
||||
elif polygon:
|
||||
start, end = sorted(((lower-ground)/slope,(upper-ground)/slope))
|
||||
polygon = _clip(polygon,0,start,False)
|
||||
if polygon:
|
||||
polygon = _clip(polygon,0,end,True)
|
||||
if polygon:
|
||||
reference = travelled+min(p[0] for p in polygon)
|
||||
gap = max(.1,reference-front)
|
||||
# Keep the actor centre's signed offset from this path
|
||||
# segment. It lets the following layer distinguish a
|
||||
# measured vehicle crossing away from the selected corridor
|
||||
# from a vehicle that is actually following it.
|
||||
path_lateral = (-(center[0]-a[0])*uy
|
||||
+(center[1]-a[1])*ux)
|
||||
if best is None or gap < best['distance_m']:
|
||||
best = dict(distance_m=float(gap),reference_contact_distance_m=float(reference),
|
||||
collision_path_source=source,
|
||||
path_tangent=[float(ux),float(uy)],
|
||||
path_lateral_m=float(path_lateral))
|
||||
travelled += length
|
||||
return best
|
||||
|
||||
|
||||
def native_lead(plan, data, now, *, selected_path_only=False):
|
||||
"""Return the nearest measured obstacle plus explicit freshness/coverage.
|
||||
|
||||
``plan`` is the current native plan containing a forward/right/down path.
|
||||
Missing path evidence retains straight-ahead braking and inhibits positive
|
||||
acceleration. This helper grants neither lane clearance nor right of way.
|
||||
"""
|
||||
diagnostics = dict(available=False,reason='',native_report_fresh=False,
|
||||
ego_geometry_verified=False,selected_path_available=False,
|
||||
trailer_chain_incomplete=False,acceleration_inhibited=True,
|
||||
complete_coverage=False,clearance_verified=False,source='ATS simulator actors',
|
||||
actor_count=0,invalid_actor_count=0,collision_candidate_count=0,
|
||||
departing_crossing_count=0)
|
||||
try:
|
||||
now = number(now)
|
||||
if now is None or not isinstance(data,dict):
|
||||
raise ValueError('Finite following time and SDK data required')
|
||||
age = number(data.get('age'))
|
||||
if (data.get('valid') is not True or data.get('paused') is not False
|
||||
or data.get('position_valid') is not True or age is None or not 0. <= age <= .35):
|
||||
raise ValueError('Fresh unpaused SDK pose required')
|
||||
ego, rotation = _vector(data['world_position']), _vector(data['world_rotation'])
|
||||
speed = number(data.get('speed_mps'))
|
||||
if speed is None or not -.02 <= speed <= 70.:
|
||||
raise ValueError('Finite forward SDK speed required')
|
||||
speed = max(0.,speed)
|
||||
yaw = rotation[0]*2*math.pi
|
||||
forward = np.array([-math.sin(yaw),-math.cos(yaw)])
|
||||
right = np.array([-forward[1],forward[0]])
|
||||
def local(position):
|
||||
delta = _vector(position)-ego
|
||||
return np.array([delta[[0,2]]@forward,delta[[0,2]]@right,-delta[1]])
|
||||
report = data.get('nearby_traffic')
|
||||
if not isinstance(report,dict) or report.get('source') != 'ATS simulator actors' or not _fresh(report,now):
|
||||
raise ValueError('Fresh native actor observation required')
|
||||
diagnostics['native_report_fresh'] = True
|
||||
if report.get('ego_geometry_available') is not True or not isinstance(report.get('ego_vehicle'),dict):
|
||||
raise ValueError('Verified native tractor geometry required')
|
||||
own = report['ego_vehicle']
|
||||
if own.get('type') != 'player' or not own.get('id'):
|
||||
raise ValueError('Matched native player identity required')
|
||||
own_length, own_width, own_height = _dimensions(own)
|
||||
if own_length > 25. or own_width > 4. or own_height > 6.:
|
||||
raise ValueError('Native tractor dimensions outside supported bounds')
|
||||
measured_ego = _vector(report['ego_world_position'])
|
||||
measured_yaw, own_yaw = number(report.get('ego_world_yaw_rad')), number(own.get('world_heading_rad'))
|
||||
front = number(report.get('own_front_extent_m'))
|
||||
if measured_yaw is None or own_yaw is None or front is None or not .05 <= front <= 15.:
|
||||
raise ValueError('Measured native front extent/frame required')
|
||||
measured_forward = np.array([-math.sin(measured_yaw),-math.cos(measured_yaw)])
|
||||
measured_right = np.array([-measured_forward[1],measured_forward[0]])
|
||||
own_center_offset = _vector(own['world_position'])-measured_ego
|
||||
own_offset = own_center_offset[[0,2]]
|
||||
own_vertical = (float(own_center_offset[1]-own_height/2),float(own_center_offset[1]+own_height/2))
|
||||
delta = own_yaw-measured_yaw
|
||||
expected_front = float(own_offset@measured_forward)+abs(math.cos(delta))*own_length/2+abs(math.sin(delta))*own_width/2
|
||||
# The cached truck body is attached to the truck: validating against its
|
||||
# sample pose avoids shortening the nose as current SDK position moves.
|
||||
if abs(expected_front-front) > .1:
|
||||
raise ValueError('Native front extent disagrees with measured tractor box')
|
||||
if np.linalg.norm(ego-measured_ego) > .75+speed*(now-report['sampled_at']):
|
||||
raise ValueError('Native tractor sample disagrees with current SDK pose')
|
||||
half_width = abs(float(own_offset@measured_right))+abs(math.cos(delta))*own_width/2+abs(math.sin(delta))*own_length/2+.15
|
||||
trailers = report.get('ego_trailers')
|
||||
if not isinstance(trailers,list) or len(trailers) > 32 or type(report.get('ego_trailer_attached')) is not bool:
|
||||
raise ValueError('Verified own trailer exclusion required')
|
||||
if report['ego_trailer_attached'] != bool(trailers):
|
||||
raise ValueError('Own trailer attachment disagrees with measured chain')
|
||||
excluded = {own['id']}
|
||||
for trailer in trailers:
|
||||
if not isinstance(trailer,dict) or trailer.get('type') != 'player-trailer' or not trailer.get('id') or trailer['id'] in excluded:
|
||||
raise ValueError('Verified own trailer identity required')
|
||||
_dimensions(trailer); _vector(trailer['world_position'])
|
||||
excluded.add(trailer['id'])
|
||||
actors = report.get('actors')
|
||||
if not isinstance(actors,list) or len(actors) > 500:
|
||||
raise ValueError('Bounded native actor list required')
|
||||
diagnostics.update(available=True,ego_geometry_verified=True,actor_count=len(actors),
|
||||
own_front_extent_m=front,own_half_width_m=half_width,own_height_m=own_height,
|
||||
own_vertical_extent_m=list(own_vertical),
|
||||
sampled_at=report['sampled_at'],age_s=max(report['age_s'],now-report['sampled_at']),
|
||||
reused_after_read_failure=report.get('latest_read_failed') is True,
|
||||
trailer_chain_incomplete=(report.get('trailer_chain_traversal_complete') is False
|
||||
or bool(report.get('truncated_trailer_chains'))))
|
||||
except (KeyError,TypeError,ValueError,OverflowError) as exc:
|
||||
diagnostics['reason'] = str(exc)
|
||||
return None,diagnostics
|
||||
|
||||
paths = []
|
||||
try:
|
||||
if not isinstance(plan,dict) or not _fresh(dict(plan,age_s=plan.get('age_s',0.)),now,.35):
|
||||
raise ValueError('Current selected native path unavailable')
|
||||
path = ordered_path(plan)
|
||||
if ((plan.get('traversal_path') is None and not 0. <= path[0,0] <= 5.)
|
||||
or not plan.get('selected_lane_ids')):
|
||||
raise ValueError('Bounded directed selected native path required')
|
||||
# Only the covered path is swept. No resampling/extrapolation to make an
|
||||
# absent route segment appear available to collision association.
|
||||
if np.linalg.norm(path[0]) > 1e-6:
|
||||
path = np.vstack((np.zeros(3),path))
|
||||
paths.append(('selected native footprint',path))
|
||||
if not selected_path_only:
|
||||
# Preserve an immediate nose/reaction corridor when the truck is
|
||||
# recovering toward its lane. A 100 m straight sweep also cuts
|
||||
# across opposing lanes beyond bends and creates phantom stops.
|
||||
straight_extent = front+max(2.,speed*.4)
|
||||
paths.append(('forward footprint',np.array([[0.,0.,0.],[straight_extent,0.,0.]])))
|
||||
diagnostics['forward_footprint_extent_m'] = straight_extent
|
||||
diagnostics['selected_path_available'] = True
|
||||
except (KeyError,TypeError,ValueError,OverflowError) as exc:
|
||||
diagnostics['reason'] = str(exc)
|
||||
if not paths:
|
||||
paths = [('forward footprint',np.array([[0.,0.,0.],[100.,0.,0.]]))]
|
||||
|
||||
candidates, seen = [], set()
|
||||
for actor in actors:
|
||||
try:
|
||||
if not isinstance(actor,dict) or not actor.get('id') or actor['id'] in seen:
|
||||
raise ValueError('Missing/duplicate native actor identity')
|
||||
seen.add(actor['id'])
|
||||
if actor['id'] in excluded:
|
||||
raise ValueError('Own body unexpectedly present in obstacle list')
|
||||
dimensions = _dimensions(actor)
|
||||
heading = number(actor.get('world_heading_rad'))
|
||||
if heading is None:
|
||||
raise ValueError('Measured native world heading required')
|
||||
center = local(actor['world_position'])
|
||||
if np.linalg.norm(center[:2]) > 160.:
|
||||
continue
|
||||
contact = _contact(center,dimensions,heading-yaw,paths,front,half_width,own_vertical)
|
||||
if contact is None:
|
||||
continue
|
||||
motion_known, relative = False,-speed
|
||||
try:
|
||||
velocity = _vector(actor.get('world_velocity_mps'))
|
||||
interval, confidence = number(actor.get('motion_interval_s')),number(actor.get('motion_confidence'))
|
||||
measured_age = number(actor.get('measured_age_s'))
|
||||
if (diagnostics['reused_after_read_failure'] or actor.get('motion_available') is not True or type(actor.get('sample_count')) is not int
|
||||
or not 3 <= actor['sample_count'] <= 5 or interval is None or not .08 <= interval <= 2.4
|
||||
or confidence is None or not 0. < confidence <= 1.
|
||||
or measured_age is None or not 0. <= measured_age <= .3
|
||||
or np.linalg.norm(velocity) > 70.):
|
||||
raise ValueError('Consecutive measured native motion unavailable')
|
||||
tangent = np.asarray(contact['path_tangent'])
|
||||
world_tangent = tangent[0]*forward+tangent[1]*right
|
||||
relative = float(velocity[[0,2]]@world_tangent)-speed
|
||||
# A vehicle crossing an intersection can geometrically touch
|
||||
# the swept route while already moving away from it. The old
|
||||
# lead calculation projected only onto the route tangent, so
|
||||
# that actor looked like a stationary obstacle and could cause
|
||||
# a full emergency stop at a circle. Use the measured normal
|
||||
# velocity and the current signed path offset to admit this
|
||||
# case only when the body will be clear before our arrival.
|
||||
path_lateral = number(contact.get('path_lateral_m'))
|
||||
world_normal = (-tangent[1])*forward+tangent[0]*right
|
||||
lateral_velocity = float(velocity[[0,2]]@world_normal)
|
||||
contact['lateral_velocity_mps'] = lateral_velocity
|
||||
if (path_lateral is not None and abs(lateral_velocity) > 1.
|
||||
and abs(path_lateral) > .25
|
||||
and path_lateral*lateral_velocity > 0.):
|
||||
lateral_overlap = half_width+dimensions[1]/2.-abs(path_lateral)
|
||||
arrival = max(.05,contact['distance_m']/max(.1,speed))
|
||||
clear_time = max(0.,lateral_overlap)/abs(lateral_velocity)
|
||||
if (lateral_overlap > 0. and contact['distance_m'] > 5.
|
||||
and clear_time+.2 < arrival):
|
||||
diagnostics['departing_crossing_count'] += 1
|
||||
continue
|
||||
motion_known = True
|
||||
except (TypeError,ValueError,OverflowError):
|
||||
pass
|
||||
candidates.append(dict(id=actor['id'],type=actor.get('type'),**contact,
|
||||
chain_root_id=actor.get('chain_root_id'),discovery_source=actor.get('discovery_source'),
|
||||
world_position=list(actor['world_position']),relative_forward_mps=relative,
|
||||
motion_estimated=not motion_known,motion_verified_for_following=motion_known,
|
||||
motion_source='Measured world velocity projected on contact path minus current SDK speed' if motion_known
|
||||
else 'Unknown motion: stationary obstacle for braking only',
|
||||
source='ATS simulator actors',sampled_at=report['sampled_at'],
|
||||
lane_association_verified=False,clearance_verified=False))
|
||||
except (KeyError,TypeError,ValueError,OverflowError):
|
||||
diagnostics['invalid_actor_count'] += 1
|
||||
diagnostics.update(collision_candidate_count=len(candidates),
|
||||
acceleration_inhibited=(diagnostics['trailer_chain_incomplete'] or bool(diagnostics['invalid_actor_count'])
|
||||
or diagnostics['reused_after_read_failure'] or not diagnostics['selected_path_available']))
|
||||
if diagnostics['trailer_chain_incomplete']:
|
||||
diagnostics['reason'] = 'Foreign trailer chain truncated; observed braking obstacles retained'
|
||||
elif diagnostics['invalid_actor_count']:
|
||||
diagnostics['reason'] = 'Invalid native actor omitted; positive acceleration inhibited'
|
||||
elif diagnostics['reused_after_read_failure']:
|
||||
diagnostics['reason'] = 'Native read failed; retained measured boxes are braking evidence only'
|
||||
return (min(candidates,key=lambda actor:actor['distance_m']) if candidates else None),diagnostics
|
||||
@@ -0,0 +1,736 @@
|
||||
"""ATS-native path following: no neural model, tensor history or camera gates."""
|
||||
import math
|
||||
import time
|
||||
from control.gameplay_cruise import GameplayCruise
|
||||
from control.gameplay_lead_guard import GameplayLeadGuard
|
||||
from control.native_following import native_lead
|
||||
from control.native_path import ordered_path, steering, curve_speed
|
||||
from control.gameplay_speed import measured_trailer_attached
|
||||
from control.native_energy_navigation import charging_stop_gap
|
||||
from telemetry.driving_scene import number
|
||||
|
||||
|
||||
class NativeGameplayController:
|
||||
requires_inference = False
|
||||
MIN_TARGET_MPH = 5.
|
||||
MAX_TARGET_MPH = 80.
|
||||
MAX_AXIS = 1.
|
||||
# The first live native runs exposed a slow recovery loop: a semi could
|
||||
# build five to six feet of cross-track error before the bounded pursuit
|
||||
# command had time to move the wheel. Keep the command rate bounded, but
|
||||
# give the lane-centre correction enough authority to recover before the
|
||||
# route-membership gate has to release the lease.
|
||||
# A semi's lateral response is slow at highway speed. The old single
|
||||
# slew rate let a route-profile sample change the command sign fast enough
|
||||
# to create a left/right oscillation before the chassis had responded.
|
||||
STEERING_RATE_PER_S = .45
|
||||
HIGH_SPEED_STEERING_RATE_PER_S = .18
|
||||
HIGH_SPEED_THRESHOLD_MPS = 18.0
|
||||
STEERING_FILTER_TIME_S = .22
|
||||
SEMI_STEERING_GAIN = .1535
|
||||
LANE_CENTER_FEEDBACK_GAIN = .05
|
||||
LANE_CENTER_FEEDBACK_HIGH_SPEED_GAIN = .022
|
||||
LATERAL_RATE_DAMPING_GAIN = .018
|
||||
MIN_HIGH_SPEED_AXIS = .14
|
||||
ROAD_CONTROL_AXIS = .35
|
||||
MAX_CONTROL_AXIS = 1.
|
||||
output_gap_limit_s = .5
|
||||
# A native graph can briefly lose its forward prefix as a stopped truck
|
||||
# reaches a route node. Keep the existing lease long enough to hold the
|
||||
# brake and let the next fresh graph sample reconnect. A missing path
|
||||
# never authorizes throttle or a new engagement.
|
||||
ROUTE_GAP_HOLD_S = 1.5
|
||||
ROUTE_GAP_MAX_SPEED_MPS = 2.0
|
||||
ROUTE_GAP_STOP_TARGET_MPH = 5.0
|
||||
ROUTE_SOURCE_GAP_HOLD_S = 1.5
|
||||
ROUTE_SOURCE_GAP_MAX_SPEED_MPS = 18.0
|
||||
# Small curve/traffic-map target changes should not alternate the pedal
|
||||
# every control sample. Large drops remain immediate for real stops and
|
||||
# emergency geometry.
|
||||
TARGET_DROP_HARD_MPH = 4.0
|
||||
TARGET_DROP_SMOOTH_TIME_S = .35
|
||||
# The RenCloud engine flag can briefly read false while ATS refreshes an
|
||||
# electric-truck snapshot. Keep a live lease through that one-sample
|
||||
# blip, but only as a short no-throttle brake hold; a real engine-off state
|
||||
# still releases as soon as the bounded grace expires.
|
||||
ENGINE_STATE_GAP_HOLD_S = 1.0
|
||||
ENGINE_STATE_GAP_MAX_SPEED_MPS = 22.0
|
||||
# Losing the qualified lane at speed must hand the truck back safely. A
|
||||
# short brake-only lease avoids releasing all pedals on the same frame that
|
||||
# a bad lane association is reported, while still forcing a human takeover
|
||||
# if the lane cannot be reacquired.
|
||||
LANE_LOSS_BRAKE_HOLD_S = 1.5
|
||||
LANE_LOSS_MAX_SPEED_MPS = 35.0
|
||||
LANE_LOSS_BRAKE_INTENSITY = .5
|
||||
REVERSE_SPEED_TOLERANCE_MPS = .25
|
||||
|
||||
def __init__(self, target_speed_mph=35.):
|
||||
self._now = 0.
|
||||
self.cruise = GameplayCruise(lambda: self._now)
|
||||
self.lead_guard = GameplayLeadGuard()
|
||||
self.target_speed_mph = 35.
|
||||
self.set_target_speed(target_speed_mph)
|
||||
self.reset()
|
||||
|
||||
def set_target_speed(self, mph):
|
||||
mph = number(mph)
|
||||
if mph is None or not self.MIN_TARGET_MPH <= mph <= self.MAX_TARGET_MPH:
|
||||
raise ValueError('Native speed target must be within 5..80 MPH')
|
||||
if mph < self.target_speed_mph:
|
||||
self.cruise.integral = 0.
|
||||
self.target_speed_mph = mph
|
||||
return mph
|
||||
|
||||
def reset(self):
|
||||
self._last = None
|
||||
self._axis = self._smoothed = 0.
|
||||
self._target = None
|
||||
self._last_good_plan = None
|
||||
self._last_good_position = None
|
||||
self._route_gap_since = None
|
||||
self._route_source_gap_since = None
|
||||
self._engine_state_gap_since = None
|
||||
self._lane_loss_since = None
|
||||
self._last_lateral_error = None
|
||||
self._lateral_error_rate = 0.
|
||||
self._last_lateral_lane_key = None
|
||||
self._signal_hold = None
|
||||
self.cruise.reset()
|
||||
self.lead_guard.reset()
|
||||
|
||||
@staticmethod
|
||||
def _signal_identity(signal):
|
||||
association = signal.get('association') or {}
|
||||
# Multiple routed lanes can share one physical stop curve. Lane and
|
||||
# route qualification belong to the fresh crossing permission, while
|
||||
# the held lamp remains identified by its exact prefab and curve.
|
||||
keys = ('prefab_uid', 'semaphore_id', 'stop_curve_index')
|
||||
identity = tuple(association.get(key) for key in keys)
|
||||
return identity if all(value is not None for value in identity) else None
|
||||
|
||||
def resolve_signal_plan(self, scene, signal):
|
||||
"""Recover a just-passed stop only when this session was holding it.
|
||||
|
||||
A front bumper crossing the stop point is not permission to depart.
|
||||
Conversely, an already-authorized crossing must not pick up a red
|
||||
behind the truck as a new stop. All phase evidence here still comes
|
||||
from the current route-specific signal planner.
|
||||
"""
|
||||
held = self._signal_hold
|
||||
now = number(scene.get('sampled_at'))
|
||||
if held is None or now is None:
|
||||
return signal
|
||||
authorized = held.get('authorized_at')
|
||||
expires = held.get('authorization_expires_at')
|
||||
authorized_entry = (authorized is not None and expires is not None
|
||||
and authorized <= now <= expires)
|
||||
# The selected prefab may drop out on the crossing frame. Fresh pose
|
||||
# progress through the exact recently authorized point still proves
|
||||
# entry; requiring that old prefab again would stop inside the junction.
|
||||
sdk = scene.get('sdk') or {}
|
||||
gap = self._held_signal_distance(sdk)
|
||||
position = sdk.get('world_position')
|
||||
if (authorized_entry and scene.get('sdk_fresh') is True and gap is not None
|
||||
and gap < -.75 and math.dist(position, held['position']) <= 15.):
|
||||
self._signal_hold = None
|
||||
return signal
|
||||
identity = self._signal_identity(held['signal'])
|
||||
for candidate in signal.get('passed_stop_points', []):
|
||||
stamp = number(candidate.get('sampled_at'))
|
||||
if (self._signal_identity(candidate) != identity or stamp is None
|
||||
or not 0. <= now-stamp <= .3):
|
||||
continue
|
||||
if authorized_entry:
|
||||
self._signal_hold = None
|
||||
return signal
|
||||
restored = dict(candidate, retained_stop=True)
|
||||
green = (candidate.get('signal_phase_verified') is True
|
||||
and candidate.get('phase') == 'green')
|
||||
restored.update(state='proceed' if green else 'hold',
|
||||
stop_required=not green,
|
||||
usable_for_control=not green)
|
||||
return restored
|
||||
return signal
|
||||
|
||||
def _held_signal_distance(self, telemetry):
|
||||
"""Advance a retained stopping distance without inventing a new lamp."""
|
||||
held = self._signal_hold
|
||||
position = telemetry.get('world_position')
|
||||
if (held is None or held.get('position') is None
|
||||
or not isinstance(position, (list, tuple)) or len(position) != 3
|
||||
or any(number(value) is None for value in position)):
|
||||
return None
|
||||
origin, forward = held['position'], held['forward']
|
||||
travelled = ((position[0]-origin[0])*forward[0]
|
||||
+(position[2]-origin[2])*forward[1])
|
||||
return held['signal']['stop_distance_m']-travelled
|
||||
|
||||
def _remember_signal(self, signal, telemetry, authorized_at=None, authorization_expires_at=None):
|
||||
if self._signal_identity(signal) is None:
|
||||
return
|
||||
position, rotation = telemetry.get('world_position'), telemetry.get('world_rotation')
|
||||
valid_pose = (isinstance(position, (list, tuple)) and len(position) == 3
|
||||
and isinstance(rotation, (list, tuple)) and len(rotation) == 3
|
||||
and all(number(value) is not None for value in (*position, *rotation)))
|
||||
yaw = rotation[0]*2.*math.pi if valid_pose else 0.
|
||||
self._signal_hold = dict(signal=dict(signal),
|
||||
position=list(position) if valid_pose else None,
|
||||
forward=(-math.sin(yaw), -math.cos(yaw)), authorized_at=authorized_at,
|
||||
authorization_expires_at=authorization_expires_at)
|
||||
|
||||
def _route_gap_hold_allowed(self, data, now):
|
||||
plan = data.get('native_route_plan') or {}
|
||||
if plan.get('reason') != 'Native route path lacks current forward coverage':
|
||||
self._route_gap_since = None
|
||||
return False
|
||||
speed = number(data.get('speed_mps'))
|
||||
if (self._last is None or self._last_good_plan is None or speed is None):
|
||||
return False
|
||||
# A qualified path can end at the active GPS destination while the
|
||||
# truck is still rolling. Once the previous controller target has
|
||||
# already fallen to a stop target, preserve the last bounded steering
|
||||
# sign and hold the brake through that short route-end gap. An
|
||||
# unexpected gap while cruising still releases immediately.
|
||||
if (speed > self.ROUTE_GAP_MAX_SPEED_MPS
|
||||
and (self._target is None or self._target > self.ROUTE_GAP_STOP_TARGET_MPH)):
|
||||
return False
|
||||
route = data.get('navigation_route') or {}
|
||||
revision = route.get('route_revision') or route.get('revision')
|
||||
if revision != self._last_good_plan.get('route_revision'):
|
||||
return False
|
||||
position = data.get('world_position')
|
||||
if (self._last_good_position is None or not isinstance(position,(list,tuple))
|
||||
or len(position) != 3 or any(not isinstance(v,(int,float)) or not math.isfinite(v) for v in position)):
|
||||
return False
|
||||
if math.dist(position,self._last_good_position) > 8.:
|
||||
return False
|
||||
if self._route_gap_since is None:
|
||||
self._route_gap_since = now
|
||||
return 0. <= now-self._route_gap_since <= self.ROUTE_GAP_HOLD_S
|
||||
|
||||
def _route_source_gap_hold_allowed(self, data, now, reason):
|
||||
"""Keep a moving lease through one short GPS-reader handoff.
|
||||
|
||||
The route reader can briefly fail its process-memory snapshot while ATS
|
||||
recalculates a route. If the last native lane plan was fresh and the
|
||||
truck has not moved far, a short no-throttle hold is safer than
|
||||
dropping steering immediately. This path never creates a route or
|
||||
authorizes a new engagement.
|
||||
"""
|
||||
if reason not in ('Matched active native GPS route required',
|
||||
'Native path does not match active GPS route'):
|
||||
self._route_source_gap_since = None
|
||||
return False
|
||||
speed = number(data.get('speed_mps'))
|
||||
if (self._last is None or self._last_good_plan is None
|
||||
or self._last_good_position is None or speed is None
|
||||
or speed < -self.REVERSE_SPEED_TOLERANCE_MPS
|
||||
or speed > self.ROUTE_SOURCE_GAP_MAX_SPEED_MPS):
|
||||
return False
|
||||
position = data.get('world_position')
|
||||
if (not isinstance(position,(list,tuple)) or len(position) != 3
|
||||
or any(not isinstance(v,(int,float)) or not math.isfinite(v) for v in position)
|
||||
or math.dist(position,self._last_good_position) > 15.):
|
||||
return False
|
||||
if self._route_source_gap_since is None:
|
||||
self._route_source_gap_since = now
|
||||
return 0. <= now-self._route_source_gap_since <= self.ROUTE_SOURCE_GAP_HOLD_S
|
||||
|
||||
def _engine_state_gap_hold_allowed(self, data, now, reason):
|
||||
"""Keep a moving lease through one transient engine-state read.
|
||||
|
||||
ATS can publish an electric-truck snapshot with ``engine_enabled``
|
||||
false for one update while the SDK view is still valid. Releasing
|
||||
immediately at road speed causes an unnecessary control dropout. A
|
||||
short brake-only grace is safe and cannot create a new engagement;
|
||||
sustained engine-off, parked, reverse, stale, or large pose changes
|
||||
still fail the normal readiness gate.
|
||||
"""
|
||||
if reason != 'Turn on the engine before engaging':
|
||||
self._engine_state_gap_since = None
|
||||
return False
|
||||
speed = number(data.get('speed_mps'))
|
||||
if (self._last is None or self._last_good_plan is None
|
||||
or self._last_good_position is None or speed is None
|
||||
or speed < -self.REVERSE_SPEED_TOLERANCE_MPS
|
||||
or speed > self.ENGINE_STATE_GAP_MAX_SPEED_MPS
|
||||
or type(data.get('gear')) is not int or data['gear'] <= 0
|
||||
or data.get('park_brake') is not False):
|
||||
return False
|
||||
position = data.get('world_position')
|
||||
if (not isinstance(position,(list,tuple)) or len(position) != 3
|
||||
or any(not isinstance(v,(int,float)) or not math.isfinite(v) for v in position)
|
||||
or math.dist(position,self._last_good_position) > 15.):
|
||||
return False
|
||||
if self._engine_state_gap_since is None:
|
||||
self._engine_state_gap_since = now
|
||||
return 0. <= now-self._engine_state_gap_since <= self.ENGINE_STATE_GAP_HOLD_S
|
||||
|
||||
def _lane_loss_brake_hold_allowed(self, data, now, reason):
|
||||
"""Brake briefly when the qualified lane disappears at road speed.
|
||||
|
||||
This is deliberately narrower than the normal route-source grace. It
|
||||
only covers an association that was just near the truck and then lost
|
||||
its heading/center test. Holding the last steering command was unsafe
|
||||
in that situation: the trace showed alternating steering followed by a
|
||||
release while the truck was still moving. Fade the wheel to center and
|
||||
apply a bounded brake so the driver can recover control.
|
||||
"""
|
||||
if not (reason.startswith('Truck is ') or
|
||||
reason == 'Align the truck with the native GPS lane direction'):
|
||||
self._lane_loss_since = None
|
||||
return False
|
||||
speed = number(data.get('speed_mps'))
|
||||
if (self._last is None or self._last_good_plan is None
|
||||
or self._last_good_position is None or speed is None
|
||||
or speed < -self.REVERSE_SPEED_TOLERANCE_MPS
|
||||
or speed > self.LANE_LOSS_MAX_SPEED_MPS
|
||||
or type(data.get('gear')) is not int or data['gear'] <= 0
|
||||
or data.get('park_brake') is not False):
|
||||
self._lane_loss_since = None
|
||||
return False
|
||||
position = data.get('world_position')
|
||||
if (not isinstance(position,(list,tuple)) or len(position) != 3
|
||||
or any(not isinstance(v,(int,float)) or not math.isfinite(v) for v in position)
|
||||
or math.dist(position,self._last_good_position) > 20.):
|
||||
self._lane_loss_since = None
|
||||
return False
|
||||
if self._lane_loss_since is None:
|
||||
self._lane_loss_since = now
|
||||
return 0. <= now-self._lane_loss_since <= self.LANE_LOSS_BRAKE_HOLD_S
|
||||
|
||||
def _stability_speed_cap(self, speed, lateral_error, lateral_rate, heading_dot):
|
||||
"""Reduce speed before a growing lateral error becomes unrecoverable."""
|
||||
cap = self.target_speed_mph
|
||||
error = abs(lateral_error) if lateral_error is not None else 0.
|
||||
if speed >= self.HIGH_SPEED_THRESHOLD_MPS:
|
||||
# At 65--70 MPH, a metre of cross-track error needs braking time;
|
||||
# waiting for the route gate to fail is too late for a semi.
|
||||
if error > .35:
|
||||
cap = min(cap, max(30., self.target_speed_mph - 70.*(error-.35)))
|
||||
rate = abs(lateral_rate)
|
||||
if rate > .35:
|
||||
cap = min(cap, max(30., 55. - 20.*min(rate, 1.25)))
|
||||
if heading_dot is not None and heading_dot < .995:
|
||||
cap = min(cap, 45.)
|
||||
if heading_dot is not None and heading_dot < .985:
|
||||
cap = min(cap, 35.)
|
||||
return cap
|
||||
|
||||
def result(self, reason, allowed=False, axis=0., action='coast', intensity=0., **extra):
|
||||
return dict(allowed=allowed, allowed_for_gameplay=allowed, requested_axis=axis,
|
||||
action=action, intensity=intensity, throttle=intensity if action=='throttle' else 0.,
|
||||
brake=intensity if action=='brake' else 0., reason=reason, warnings=[],
|
||||
target_speed_mph=self.target_speed_mph, backend='ATS native',
|
||||
controls_applied=False, production_eligible=False, calibrated=False, **extra)
|
||||
|
||||
def readiness(self, data, now):
|
||||
if now is None or not isinstance(data, dict):
|
||||
return 'Finite native control time and SDK required'
|
||||
if data.get('valid') is not True or data.get('paused') is not False:
|
||||
return 'Fresh unpaused SDK required'
|
||||
age, speed = number(data.get('age')), number(data.get('speed_mps'))
|
||||
# ATS reports a small negative signed speed while an automatic truck
|
||||
# settles at a stop. Treat only a meaningful reverse motion as a
|
||||
# readiness failure; the selected forward gear and parking-brake gates
|
||||
# still prevent reverse engagement.
|
||||
if (age is None or not 0. <= age <= .35 or speed is None
|
||||
or speed < -self.REVERSE_SPEED_TOLERANCE_MPS
|
||||
or type(data.get('timestamp')) is not int or data['timestamp'] <= 0):
|
||||
return 'Fresh forward SDK speed required'
|
||||
if type(data.get('gear')) is not int or data['gear'] <= 0:
|
||||
return 'Select Drive before engaging'
|
||||
# The Tesla Semi mod is electric, but its RenCloud snapshot can leave
|
||||
# both engine/electric flags false while the truck is already rolling.
|
||||
# A moving forward-gear truck with the parking brake released is
|
||||
# already powered enough for steering and braking; require an explicit
|
||||
# power flag only for stationary engagement.
|
||||
powered = (data.get('engine_enabled') is True
|
||||
or data.get('electric_enabled') is True)
|
||||
moving_power_fallback = (speed > 2.0 and data.get('park_brake') is False)
|
||||
if not powered and not moving_power_fallback:
|
||||
return 'Turn on the engine before engaging'
|
||||
if data.get('park_brake') is not False:
|
||||
return 'Release the parking brake before engaging'
|
||||
if data.get('game_cruise_active') is True:
|
||||
return 'Turn off ATS cruise before native engagement'
|
||||
scene = data.get('driving_scene') or {}
|
||||
if scene.get('sdk_fresh') is not True or scene.get('sdk',{}).get('timestamp') != data['timestamp']:
|
||||
return 'Native scene must belong to the current SDK sample'
|
||||
plan = data.get('native_route_plan') or {}
|
||||
stamp, age = number(plan.get('sampled_at')), number(plan.get('age_s',0.))
|
||||
if (plan.get('available') is not True or plan.get('usable_for_control') is not True
|
||||
or plan.get('lane_membership_verified') is not True):
|
||||
if self._route_gap_hold_allowed(data, now):
|
||||
return ''
|
||||
return plan.get('reason') or 'Qualified native GPS lane required'
|
||||
if stamp is None or age is None or not 0. <= age <= .35 or not -.05 <= now-stamp <= .35:
|
||||
return 'Selected native route path is stale'
|
||||
route_source = scene.get('sources',{}).get('route') or {}
|
||||
route = route_source.get('data') or {}
|
||||
if (not route_source.get('fresh') or route.get('lead_in') is not None
|
||||
or plan.get('route_revision') != (route.get('route_revision') or route.get('revision'))):
|
||||
return 'Native path does not match the active GPS route'
|
||||
return ''
|
||||
|
||||
def preflight(self, perception, telemetry, model_action, now=None, warmed_once=False):
|
||||
now = number(time.monotonic() if now is None else now)
|
||||
reason = self.readiness(telemetry,now)
|
||||
if not reason:
|
||||
ordered_path(telemetry['native_route_plan'])
|
||||
_, lead_report = native_lead(telemetry['native_route_plan'],telemetry,now)
|
||||
reason = '' if lead_report.get('available') and lead_report.get('selected_path_available') else lead_report.get('reason','Fresh native traffic geometry required')
|
||||
return self.result(reason or 'Native route ready; human F8 required', not reason, preflight_only=True)
|
||||
|
||||
def assess(self, perception, telemetry, model_action, now=None, warmed_once=False):
|
||||
now = number(time.monotonic() if now is None else now)
|
||||
reason = self.readiness(telemetry,now)
|
||||
if reason:
|
||||
if self._route_source_gap_hold_allowed(telemetry, now, reason):
|
||||
dt = min(.35, now-self._last) if self._last is not None else .05
|
||||
axis = self._axis * max(0.,1.-2.*dt)
|
||||
self._axis, self._last = axis, now
|
||||
return self.result('Native GPS route sample gap; holding lane and brake', True,
|
||||
axis=axis, action='brake', intensity=.16,
|
||||
effective_speed_target_mph=self._target,
|
||||
route_source_gap_hold=True,
|
||||
steering_geometry=dict(available=False,
|
||||
reason=reason, source='ATS native GPS lane'))
|
||||
if self._engine_state_gap_hold_allowed(telemetry, now, reason):
|
||||
dt = min(.35, now-self._last) if self._last is not None else .05
|
||||
axis = self._axis * max(0.,1.-2.*dt)
|
||||
self._axis, self._last = axis, now
|
||||
return self.result('ATS engine-state sample gap; holding lane and brake', True,
|
||||
axis=axis, action='brake', intensity=.16,
|
||||
effective_speed_target_mph=self._target,
|
||||
engine_state_gap_hold=True,
|
||||
steering_geometry=dict(available=False,
|
||||
reason=reason, source='ATS native GPS lane'))
|
||||
if self._lane_loss_brake_hold_allowed(telemetry, now, reason):
|
||||
dt = min(.35, now-self._last) if self._last is not None else .05
|
||||
axis = self._axis * max(0.,1.-6.*dt)
|
||||
self._axis, self._last = axis, now
|
||||
self._target = 0.
|
||||
return self.result('Native lane confidence lost; braking for driver handoff', True,
|
||||
axis=axis, action='brake', intensity=self.LANE_LOSS_BRAKE_INTENSITY,
|
||||
effective_speed_target_mph=0., lane_loss_brake_hold=True,
|
||||
steering_geometry=dict(available=False,
|
||||
reason=reason, source='ATS native GPS lane'))
|
||||
self.reset()
|
||||
return self.result(reason)
|
||||
route_gap_hold = self._route_gap_hold_allowed(telemetry, now)
|
||||
if (self._last is not None and not 0. <= now-self._last <= self.output_gap_limit_s
|
||||
and not route_gap_hold):
|
||||
self.reset()
|
||||
return self.result('Native command gap: press F8 to reengage')
|
||||
self._now = now
|
||||
plan = telemetry['native_route_plan']
|
||||
if plan.get('usable_for_control') is not True:
|
||||
# This branch is reachable only through the short, low-speed gap
|
||||
# grace above. Stay on the last steering sign, brake gently, and
|
||||
# never synthesize a path or accelerate without fresh coverage.
|
||||
if not self._route_gap_hold_allowed(telemetry, now):
|
||||
self.reset()
|
||||
return self.result(plan.get('reason') or 'Qualified native GPS lane required')
|
||||
dt = min(.35, now-self._last) if self._last is not None else .05
|
||||
axis = self._axis * max(0., 1.-2.*dt)
|
||||
self._axis, self._last = axis, now
|
||||
self._target = 0.
|
||||
return self.result('Native route gap; holding brake for fresh coverage', True,
|
||||
axis=axis, action='brake', intensity=.28,
|
||||
effective_speed_target_mph=0., coverage_gap_hold=True,
|
||||
steering_geometry=dict(available=False,reason=plan.get('reason','')))
|
||||
# Automatic passing is a temporary, route-bound overlay. It may only
|
||||
# replace the ordered steering path after the separate lane-permission
|
||||
# and full tractor/trailer clearance gates have succeeded. The native
|
||||
# GPS plan remains the source of current-lane membership and stopping.
|
||||
control_plan = plan
|
||||
overtake = telemetry.get('native_overtake_plan') or {}
|
||||
overtake_stamp = number(overtake.get('sampled_at'))
|
||||
if (overtake.get('active') is True and overtake.get('allowed_for_gameplay') is True
|
||||
and overtake.get('permission_verified') is True
|
||||
and overtake.get('clearance_verified') is True
|
||||
and overtake.get('route_revision') == plan.get('route_revision')
|
||||
and overtake_stamp is not None and 0. <= now-overtake_stamp <= .3
|
||||
and isinstance(overtake.get('path_override'), dict)):
|
||||
control_plan = dict(plan, traversal_path=overtake['path_override'])
|
||||
if (overtake.get('maneuver_hold') is True
|
||||
and overtake.get('route_revision') == plan.get('route_revision')
|
||||
and overtake_stamp is not None and 0. <= now-overtake_stamp <= .3):
|
||||
dt = min(.35, now-self._last) if self._last is not None else .05
|
||||
self._axis *= max(0., 1.-2.*dt)
|
||||
self._last, self._target = now, 0.
|
||||
return self.result('Passing paused: '+overtake.get('reason', 'Adjacent lane blocked'),
|
||||
True, axis=self._axis, action='brake', intensity=.3,
|
||||
effective_speed_target_mph=0., native_overtake_plan=overtake,
|
||||
maneuver_brake_hold=True)
|
||||
ordered_path(control_plan)
|
||||
speed = max(0.,telemetry['speed_mps'])
|
||||
dt = min(.35,now-self._last) if self._last is not None else .05
|
||||
gain = self.SEMI_STEERING_GAIN if 'Semi' in str(telemetry.get('truck_name')) else .1254
|
||||
# Gradually extend pursuit at road speed. A short late correction
|
||||
# followed by chassis lag was the start of the observed steering wobble.
|
||||
semi = 'Semi' in str(telemetry.get('truck_name'))
|
||||
anticipation = (1.65 if semi else 1.3)+.35*max(0.,min(1.,(speed-12.)/16.))
|
||||
lateral_accel = 4. if measured_trailer_attached(telemetry) is False else 3.5
|
||||
curve = curve_speed(control_plan,lateral_accel=lateral_accel,deceleration=2.5,
|
||||
curvature_window_m=8.)
|
||||
max_lookahead = 60. if semi else 45.
|
||||
curvature = curve.get('curvature') or 0.
|
||||
tight_turn = (semi and curvature > .035
|
||||
and curve['bend_distance_m'] < max(6.,speed*anticipation)+6.)
|
||||
if tight_turn:
|
||||
# Do not aim across an entire tight ramp bend. Keep the stable
|
||||
# long forecast on highways, but track the actual local arc here.
|
||||
max_lookahead = min(max_lookahead,max(6.,.65/curvature))
|
||||
geometry = steering(control_plan,speed,gain,lookahead_time_s=anticipation,
|
||||
max_lookahead_m=max_lookahead)
|
||||
geometry['tight_turn_tracking'] = tight_turn
|
||||
if not geometry.get('available'):
|
||||
return self.result(geometry.get('reason','Native path unavailable'))
|
||||
geometry.update(source='ATS native GPS lane', sampled_at=plan['sampled_at'],
|
||||
lane_id=(overtake.get('target_lane_id') if control_plan is not plan
|
||||
else plan['selected_lane_ids'][0]),
|
||||
selected_path=control_plan.get('traversal_path') or control_plan['path'],
|
||||
source_geometry_fallback=bool(plan.get('source_geometry_fallback')))
|
||||
# Pure pursuit sees the lane centre at a lookahead distance. That is
|
||||
# deliberately stable through bends, but on a long straight it can
|
||||
# under-react to the current ego offset. The native planner already
|
||||
# reports the signed offset (positive means the truck is right of the
|
||||
# selected lane), so add a small, same-frame recovery term. Native
|
||||
# positive steering is left; the sign therefore directly counters the
|
||||
# measured rightward error.
|
||||
association = (overtake.get('association') if control_plan is not plan else None) or plan.get('association') or {}
|
||||
lateral_error = number(association.get('ego_lateral_right_m'))
|
||||
heading_dot = number(association.get('heading_dot'))
|
||||
if lateral_error is not None:
|
||||
lane_ids = plan.get('selected_lane_ids') or []
|
||||
lane_key = (plan.get('route_revision'),
|
||||
overtake.get('signal_request_id') if control_plan is not plan
|
||||
else lane_ids[0] if lane_ids else None)
|
||||
lane_changed = lane_key != self._last_lateral_lane_key
|
||||
if lane_changed:
|
||||
# A graph handoff can move the authored centerline by a few
|
||||
# inches even when the truck did not move. Do not turn that
|
||||
# bookkeeping jump into a derivative steering kick.
|
||||
self._last_lateral_error = lateral_error
|
||||
self._lateral_error_rate = 0.
|
||||
self._last_lateral_lane_key = lane_key
|
||||
elif self._last_lateral_error is not None and dt > 1e-4:
|
||||
measured_rate = (lateral_error-self._last_lateral_error)/dt
|
||||
measured_rate = max(-4.,min(4.,measured_rate))
|
||||
self._lateral_error_rate = (.7*self._lateral_error_rate
|
||||
+.3*measured_rate)
|
||||
self._last_lateral_error = lateral_error
|
||||
feedback = 0.
|
||||
if lateral_error is not None:
|
||||
bounded_error = max(-2.5, min(2.5, lateral_error))
|
||||
feedback_gain = (self.LANE_CENTER_FEEDBACK_GAIN
|
||||
if speed < self.HIGH_SPEED_THRESHOLD_MPS
|
||||
else self.LANE_CENTER_FEEDBACK_HIGH_SPEED_GAIN)
|
||||
# Pursuit's lateral position gain falls with distance squared.
|
||||
# A fixed additional gain grows its closed-loop stiffness with
|
||||
# speed squared and overpowers that stable heading correction.
|
||||
# Bound the extra position term to 25% of pursuit's position gain.
|
||||
feedback_gain = min(feedback_gain, .5/(gain*max(6.,geometry['lookahead_m'])**2))
|
||||
damping_gain = min(self.LATERAL_RATE_DAMPING_GAIN,.75*feedback_gain)
|
||||
# Positive rightward drift needs positive (left) steering. The
|
||||
# derivative term damps the alternating sign seen at route bends.
|
||||
feedback = (bounded_error * feedback_gain
|
||||
+max(-.08,min(.08,self._lateral_error_rate*damping_gain)))
|
||||
geometry['native_lane_center_feedback_gain'] = feedback_gain
|
||||
geometry['native_lane_center_damping_gain'] = damping_gain
|
||||
geometry['native_lane_center_error_m'] = lateral_error
|
||||
geometry['native_lane_center_feedback_axis'] = feedback
|
||||
geometry['native_lane_center_error_rate_mps'] = self._lateral_error_rate
|
||||
geometry['native_path_axis'] = geometry['raw_axis']
|
||||
geometry['raw_axis'] += feedback
|
||||
self._last_good_plan = dict(route_revision=plan.get('route_revision'),
|
||||
selected_lane_ids=list(plan.get('selected_lane_ids') or []))
|
||||
position = telemetry.get('world_position')
|
||||
self._last_good_position = list(position) if isinstance(position,(list,tuple)) and len(position)==3 else None
|
||||
self._route_gap_since = None
|
||||
self._route_source_gap_since = None
|
||||
self._engine_state_gap_since = None
|
||||
axis_limit=min(self.ROAD_CONTROL_AXIS,
|
||||
max(self.MIN_HIGH_SPEED_AXIS,1.-.9*min(1.,speed/20.)))
|
||||
if semi and speed < 12.:
|
||||
# Full game wheel travel is needed for ramps and junctions. Taper
|
||||
# that authority back to the road limit before highway speed.
|
||||
axis_limit = self.ROAD_CONTROL_AXIS+(self.MAX_CONTROL_AXIS-self.ROAD_CONTROL_AXIS)*max(0.,min(1.,(12.-speed)/6.))
|
||||
target_axis = max(-axis_limit,min(axis_limit,geometry['raw_axis']))
|
||||
geometry['axis_limit']=axis_limit
|
||||
filter_time = (self.STEERING_FILTER_TIME_S
|
||||
if speed < self.HIGH_SPEED_THRESHOLD_MPS else .32)
|
||||
if tight_turn and speed < 9.:
|
||||
filter_time = .12
|
||||
self._smoothed += dt/(filter_time+dt)*(target_axis-self._smoothed)
|
||||
steering_rate = (self.STEERING_RATE_PER_S
|
||||
if speed < self.HIGH_SPEED_THRESHOLD_MPS
|
||||
else self.HIGH_SPEED_STEERING_RATE_PER_S)
|
||||
if tight_turn and speed < 9.:
|
||||
steering_rate = .9
|
||||
axis = max(self._axis-steering_rate*dt,
|
||||
min(self._axis+steering_rate*dt,self._smoothed))
|
||||
geometry['steering_rate_limit_per_s'] = steering_rate
|
||||
geometry['steering_filter_time_s'] = filter_time
|
||||
lead, traffic = native_lead(control_plan,telemetry,now,
|
||||
selected_path_only=control_plan is not plan)
|
||||
if lead is None and traffic.get('selected_path_available') and not traffic.get('acceleration_inhibited'):
|
||||
previous_lead = self.lead_guard.last_lead or {}
|
||||
actors = (telemetry.get('nearby_traffic') or {}).get('actors') or []
|
||||
if any(actor.get('id') == previous_lead.get('id') for actor in actors):
|
||||
# Fresh valid boxes show this same body outside the chosen
|
||||
# corridor. This is positive geometric evidence, not a read
|
||||
# dropout; retaining its old gap produces brake/throttle kicks
|
||||
# on ordinary bends as well as during lane changes.
|
||||
self.lead_guard.reset()
|
||||
lead, guard = self.lead_guard.assess(lead,None,telemetry,now)
|
||||
# Lane recovery steering is not road curvature. Use the authored
|
||||
# road shape for corner speed and measured drift for stability limits.
|
||||
target = self.target_speed_mph
|
||||
if curve.get('speed_limit_mph') is not None:
|
||||
target = min(target,curve['speed_limit_mph'])
|
||||
stability_cap = self._stability_speed_cap(
|
||||
speed, lateral_error, self._lateral_error_rate, heading_dot)
|
||||
target = min(target, stability_cap)
|
||||
# Stop before the end of qualified geometry, never extrapolate across
|
||||
# a missing join or accelerate toward an unverified continuation. A
|
||||
# freshly sampled, lane-verified route with a full steering forecast
|
||||
# has measured continuation beyond that 100 m forecast. Use a bounded
|
||||
# stronger braking envelope there; the old 1.5 m/s2 value limited a
|
||||
# straight, verified highway to about 42 MPH with only 127 m of
|
||||
# qualified coverage. Curves, signals, and traffic apply their own
|
||||
# lower limits below.
|
||||
front = number((telemetry.get('nearby_traffic') or {}).get('own_front_extent_m'))
|
||||
coverage=number(plan.get('qualified_coverage_m'))
|
||||
# A sampled steering forecast ends at 100m even when qualified road
|
||||
# geometry continues. Brake for the actual end of qualified coverage.
|
||||
if coverage is None or not geometry['path_extent_m']-.1<=coverage<=10000.:
|
||||
coverage=geometry['path_extent_m']
|
||||
horizon_gap = max(0.,coverage-(front or 0.)-3.)
|
||||
route_verified = (plan.get('available') is True
|
||||
and plan.get('usable_for_control') is True
|
||||
and plan.get('lane_membership_verified') is True
|
||||
and plan.get('source_geometry_fallback') is not True
|
||||
and plan.get('route_revision') is not None
|
||||
and geometry['path_extent_m'] >= 80.
|
||||
and coverage >= geometry['path_extent_m']-.1)
|
||||
coverage_deceleration = 2.5 if route_verified else 1.5
|
||||
coverage_cap = math.sqrt(2.*coverage_deceleration*horizon_gap)*2.2369362921
|
||||
target = min(target,coverage_cap)
|
||||
signal = telemetry.get('native_signal_plan') or {}
|
||||
signal_associated = (signal.get('route_revision') == plan['route_revision']
|
||||
and number(signal.get('sampled_at')) is not None
|
||||
and 0. <= now-signal['sampled_at'] <= .3
|
||||
and signal.get('front_geometry_verified') is True
|
||||
and number(signal.get('stop_distance_m')) is not None)
|
||||
held_identity = (self._signal_identity(self._signal_hold['signal'])
|
||||
if self._signal_hold is not None else None)
|
||||
retained_signal_hold = (held_identity is not None and
|
||||
(not signal_associated or self._signal_identity(signal) != held_identity))
|
||||
if retained_signal_hold:
|
||||
# Unknown, stale or a different lamp cannot erase an established
|
||||
# stop. Do not relabel remembered evidence as a fresh live phase.
|
||||
signal_associated = False
|
||||
signal_stop = (signal_associated and signal.get('usable_for_control') is True
|
||||
and signal.get('stop_required') is True)
|
||||
if signal_stop:
|
||||
target = min(target,math.sqrt(2.*1.5*max(0.,signal['stop_distance_m']-1.))*2.2369362921)
|
||||
# A native signal path does not supply crossing priority. Restrict at
|
||||
# its authored point until a separate clearance/priority planner grants
|
||||
# entry, even when the phase changes to green.
|
||||
crossing = telemetry.get('native_crossing_plan') or {}
|
||||
crossing_stamp = number(crossing.get('sampled_at'))
|
||||
crossing_ttl = number(crossing.get('valid_for_s'))
|
||||
crossing_cap = number(crossing.get('entry_speed_cap_mps'))
|
||||
crossing_proceed = (signal_associated and signal.get('phase') == 'green'
|
||||
and not signal_stop and crossing.get('proceed_authorized') is True
|
||||
and crossing.get('experimental_proceed') is True
|
||||
and crossing.get('observed_clearance') is True
|
||||
and crossing.get('priority_semantics_resolved') is True
|
||||
and crossing.get('route_revision') == plan['route_revision']
|
||||
and crossing.get('association') == signal.get('association')
|
||||
and crossing_stamp is not None and crossing_ttl is not None
|
||||
and 0. < crossing_ttl <= .2 and 0. <= now-crossing_stamp <= crossing_ttl
|
||||
and crossing_cap is not None and 0. < crossing_cap <= 8.)
|
||||
crossing_hold = (signal_associated and not crossing_proceed) or retained_signal_hold
|
||||
stop_gap = (self._held_signal_distance(telemetry) if retained_signal_hold
|
||||
else signal.get('stop_distance_m') if signal_associated else None)
|
||||
if retained_signal_hold and stop_gap is None:
|
||||
stop_gap = 0.
|
||||
if crossing_hold:
|
||||
target = min(target,math.sqrt(3.*max(0.,stop_gap-1.))*2.2369362921)
|
||||
elif crossing_proceed:
|
||||
target = min(target,crossing_cap*2.2369362921)
|
||||
if signal_associated:
|
||||
self._remember_signal(signal, telemetry,
|
||||
crossing_stamp if crossing_proceed else None,
|
||||
crossing_stamp+crossing_ttl if crossing_proceed else None)
|
||||
charge_gap=charging_stop_gap(telemetry,plan,now)
|
||||
if charge_gap is not None:
|
||||
target=min(target,math.sqrt(3.*max(0.,charge_gap-1.))*2.2369362921)
|
||||
raw_target = target
|
||||
if (self._target is None or raw_target < self._target-self.TARGET_DROP_HARD_MPH
|
||||
or (crossing_hold or charge_gap is not None) and raw_target < self._target
|
||||
or (stability_cap < self.target_speed_mph-.5
|
||||
and abs(raw_target-stability_cap) < .01 and raw_target < self._target)):
|
||||
self._target = raw_target
|
||||
elif raw_target < self._target:
|
||||
alpha = min(1., max(0., dt)/self.TARGET_DROP_SMOOTH_TIME_S)
|
||||
self._target += (raw_target-self._target)*alpha
|
||||
else:
|
||||
rise = 3. if signal_associated or retained_signal_hold else 5.
|
||||
self._target = min(raw_target,self._target+rise*dt)
|
||||
action,intensity = self.cruise.compute(self._target,speed*2.2369362921,lead,
|
||||
curve_limited=self._target<self.target_speed_mph-.5,pedal_feedback=telemetry,
|
||||
throttle_ramp_scale=1.35)
|
||||
if action=='throttle' and (not traffic.get('available') or traffic.get('acceleration_inhibited')
|
||||
or guard['acceleration_inhibited']):
|
||||
action,intensity='coast',0.
|
||||
if self._target <= .5 and speed < .3:
|
||||
action,intensity='brake',max(.12,intensity if action=='brake' else 0.)
|
||||
if crossing_hold and (stop_gap <= 1.5 or speed*2.2369362921 > raw_target):
|
||||
# Cruise's acceleration forecast can coast while still rolling
|
||||
# toward a zero target. A physical stop needs a braking floor
|
||||
# until stationary, including after a small stop-line overshoot.
|
||||
required = speed*speed/(2.*max(.5, stop_gap-1.))
|
||||
floor = min(.65, max(.12, required/6.))
|
||||
action, intensity = 'brake', max(floor, intensity if action == 'brake' else 0.)
|
||||
self.cruise.integral = 0.
|
||||
self._axis,self._last = axis,now
|
||||
if charge_gap is not None and (charge_gap<=1.5 or speed*2.2369362921>raw_target):
|
||||
floor=min(.65,max(.12,speed*speed/(2.*max(.5,charge_gap-1.))/6.))
|
||||
action,intensity='brake',max(floor,intensity if action=='brake' else 0.)
|
||||
self.cruise.integral=0.
|
||||
reason = 'ATS native GPS lane following'
|
||||
if control_plan is not plan:
|
||||
reason = 'ATS native GPS lane following | '+overtake.get('reason', 'Passing slower traffic')
|
||||
if retained_signal_hold:
|
||||
reason = 'Signal stop retained; waiting for the same signal and crossing clearance'
|
||||
elif signal_stop:
|
||||
reason = 'Native signal stop'
|
||||
elif crossing_hold:
|
||||
reason = crossing.get('reason') or 'Intersection priority pending'
|
||||
elif crossing_proceed:
|
||||
reason = 'Green: yielding to observed traffic gaps'
|
||||
elif charge_gap is not None:
|
||||
reason='Charging/fuel stop: park and refuel' if charge_gap<=1.5 else 'Approaching charging/fuel stop'
|
||||
return self.result(reason,True,axis,action,intensity,
|
||||
steering_geometry=geometry,effective_speed_target_mph=self._target,
|
||||
raw_effective_speed_target_mph=raw_target,
|
||||
charging_stop_distance_m=charge_gap,
|
||||
target_smoothing_active=abs(self._target-raw_target)>.05,
|
||||
following_guard=guard,following_braking=self.cruise.following,
|
||||
native_traffic=traffic,native_signal_plan=signal,native_crossing_plan=crossing,
|
||||
retained_signal_hold=retained_signal_hold,
|
||||
signal_stop_distance_m=stop_gap,
|
||||
coverage_speed_cap_mph=coverage_cap,coverage_cap_active=coverage_cap < self.target_speed_mph-.5,
|
||||
stability_speed_cap_mph=stability_cap,
|
||||
stability_cap_active=stability_cap < self.target_speed_mph-.5,
|
||||
coverage_braking_mps2=coverage_deceleration,qualified_coverage_m=coverage,
|
||||
curve_speed_cap_mph=curve.get('speed_limit_mph'),
|
||||
curve_lateral_acceleration_mps2=lateral_accel,
|
||||
curve_curvature_window_m=8.,
|
||||
longitudinal_source='SDK speed and native traffic/route stopping distances',
|
||||
native_overtake_plan=overtake)
|
||||
@@ -0,0 +1,497 @@
|
||||
"""Route-bound automatic passing using authored lanes and native actors.
|
||||
|
||||
This planner proposes road-anchored lane transitions. Fresh measured vehicle
|
||||
bodies and mounted lane permissions are separate requirements. Vehicle-only
|
||||
observations do not establish cone/barrier or whole-road closure coverage.
|
||||
"""
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
from control.native_following import native_lead
|
||||
from control.native_route_planner import source_span_verified
|
||||
from telemetry.driving_scene import number
|
||||
|
||||
|
||||
def _empty(now, reason, state='idle'):
|
||||
return dict(available=False, allowed_for_gameplay=False, active=False,
|
||||
sampled_at=now, age_s=0., state=state, reason=reason,
|
||||
direction='left', path_override=None, source='ATS native authored lane overtake',
|
||||
route_revision=None, current_lane_id=None, target_lane_id=None,
|
||||
signal_pulse='none', signal_request_id=None,
|
||||
clearance_verified=False, permission_verified=False,
|
||||
completion_verified=False)
|
||||
|
||||
|
||||
def _fresh(report, now, limit=.3):
|
||||
stamp, age = number(report.get('sampled_at')), number(report.get('age_s', 0.))
|
||||
return (report.get('available') is True and stamp is not None and age is not None
|
||||
and 0. <= age <= limit and -.05 <= now-stamp <= limit)
|
||||
|
||||
|
||||
def _lane_key(lane):
|
||||
return (lane.get('road_uid'), lane.get('travel_direction'),
|
||||
str(lane.get('start_node_uid')), str(lane.get('end_node_uid')))
|
||||
|
||||
|
||||
def _local_points(line, position, yaw):
|
||||
line = np.asarray(line, float)
|
||||
if line.ndim != 2 or line.shape[1] != 3 or len(line) < 2 or not np.isfinite(line).all():
|
||||
raise ValueError('Target lane geometry is not finite')
|
||||
forward = np.array([-math.sin(yaw), -math.cos(yaw)])
|
||||
right = np.array([-forward[1], forward[0]])
|
||||
delta = line-np.asarray(position, float)
|
||||
local = np.column_stack((delta[:, [0, 2]]@forward,
|
||||
delta[:, [0, 2]]@right, -delta[:, 1]))
|
||||
lengths = np.linalg.norm(np.diff(local[:, :2], axis=0), axis=1)
|
||||
if np.any(lengths <= 1e-5):
|
||||
raise ValueError('Target lane has degenerate segments')
|
||||
arc = np.r_[0., np.cumsum(lengths)]
|
||||
return local, arc
|
||||
|
||||
|
||||
def _resample(points, arc, samples):
|
||||
return np.column_stack([np.interp(samples, arc, points[:, i]) for i in range(3)])
|
||||
|
||||
|
||||
def _project_line(points, position, forward):
|
||||
"""Vectorized closest-road association for each observed body."""
|
||||
points, position = np.asarray(points, float), np.asarray(position, float)
|
||||
delta = np.diff(points, axis=0)
|
||||
length = np.linalg.norm(delta[:, [0, 2]], axis=1)
|
||||
denominator = np.maximum(length*length, 1e-12)
|
||||
tangent = delta[:, [0, 2]]/np.maximum(length[:, None], 1e-6)
|
||||
heading = tangent@forward
|
||||
fraction = np.clip(np.sum((position-points[:-1])[:, [0, 2]]*delta[:, [0, 2]], axis=1)/denominator, 0., 1.)
|
||||
projection = points[:-1]+fraction[:, None]*delta
|
||||
error = np.linalg.norm((position-projection)[:, [0, 2]], axis=1)
|
||||
height = abs(position[1]-projection[:, 1])
|
||||
valid = (length > 1e-6)&(heading >= .7)&(height <= 1.)
|
||||
scores = np.where(valid, error+height*2.+(1.-heading)*3., np.inf)
|
||||
index = int(np.argmin(scores))
|
||||
if not np.isfinite(scores[index]):
|
||||
return None
|
||||
return dict(index=index, fraction=float(fraction[index]), projection=projection[index],
|
||||
error_m=float(error[index]), height_error_m=float(height[index]), heading_dot=float(heading[index]))
|
||||
|
||||
|
||||
class NativeOvertakePlanner:
|
||||
"""Stateful passing proposal with explicit permission and clearance gates."""
|
||||
|
||||
MAX_AGE_S = .3
|
||||
TRIGGER_GAP_M = 75.
|
||||
MIN_GAP_M = 12.
|
||||
REAR_GAP_M = 22.
|
||||
TRANSITION_M = 38.
|
||||
MAX_MANEUVER_S = 14.
|
||||
|
||||
def __init__(self):
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.state = 'idle'
|
||||
self.started = None
|
||||
self.direction = 'left'
|
||||
self.current_lane_id = self.target_lane_id = None
|
||||
self.route_revision = None
|
||||
self.world_path = None
|
||||
self.transition_m = self.TRANSITION_M
|
||||
self.blocking_ids = set()
|
||||
self.mode = 'overtake'
|
||||
self.completed_at = None
|
||||
|
||||
def _permission(self, graph, current, target):
|
||||
permissions = graph.get('lane_permissions') or {}
|
||||
if not isinstance(permissions, dict) or permissions.get('available') is not True:
|
||||
raise ValueError('Mounted lane permissions unavailable for automatic overtake')
|
||||
if permissions.get('route_revision') not in (None, graph.get('route_revision')):
|
||||
raise ValueError('Lane permission revision is stale')
|
||||
boundary = next((b for b in permissions.get('boundaries', [])
|
||||
if {b.get('inner_lane_id'), b.get('outer_lane_id')} ==
|
||||
{current['id'], target['id']}), None)
|
||||
if boundary is None or boundary.get('status') != 'allowed' or boundary.get('clearance_verified'):
|
||||
if boundary is None:
|
||||
raise ValueError('No exact mounted permission for adjacent lane')
|
||||
if boundary.get('status') != 'allowed':
|
||||
raise ValueError(boundary.get('reason') or 'Mounted lane boundary blocks passing')
|
||||
raise ValueError('Lane permission must remain separate from traffic clearance')
|
||||
if boundary.get('same_direction') is not True or boundary.get('definition_only') is not True:
|
||||
raise ValueError('Adjacent lane permission lacks same-direction provenance')
|
||||
return boundary
|
||||
|
||||
def _choose_target(self, graph, current, direction='left'):
|
||||
candidates = [lane for lane in graph.get('lanes', [])
|
||||
if lane.get('kind') == 'road' and lane.get('id') != current['id']
|
||||
and _lane_key(lane) == _lane_key(current)]
|
||||
if not candidates:
|
||||
raise ValueError('No adjacent authored lane on this road segment')
|
||||
# Signed measured offsets are ordered toward the road edge. Passing on
|
||||
# the left selects the immediately inner lane, never a shoulder or a
|
||||
# lane across a junction.
|
||||
ordered = sorted([current, *candidates],
|
||||
key=lambda lane: lane['travel_direction']*float(lane['offset_m']))
|
||||
index = next((i for i, lane in enumerate(ordered) if lane['id'] == current['id']), None)
|
||||
target_index = index+(-1 if direction == 'left' else 1) if index is not None else -1
|
||||
if not 0 <= target_index < len(ordered):
|
||||
raise ValueError('No adjacent authored lane on the '+direction)
|
||||
target = ordered[target_index]
|
||||
spacing = abs(float(target['offset_m'])-float(current['offset_m']))
|
||||
return dict(target, width_m=number(target.get('width_m')) or spacing)
|
||||
|
||||
def _road_width(self, graph, lane):
|
||||
width = number(lane.get('width_m'))
|
||||
if width is not None:
|
||||
return width
|
||||
spacings = [abs(float(other['offset_m'])-float(lane['offset_m']))
|
||||
for other in graph.get('lanes', [])
|
||||
if other.get('id') != lane['id'] and other.get('kind') == 'road'
|
||||
and _lane_key(other) == _lane_key(lane)]
|
||||
return min(spacings) if spacings else None
|
||||
|
||||
|
||||
def _path(self, plan, current, target, sdk, now):
|
||||
position, rotation = sdk['world_position'], sdk['world_rotation']
|
||||
yaw = float(rotation[0])*2.*math.pi
|
||||
target_local, target_arc = _local_points(target['centerline'], position, yaw)
|
||||
current_source = plan.get('traversal_path') or plan.get('path')
|
||||
current_local = np.column_stack([current_source[k] for k in ('x', 'y', 'z')]).astype(float)
|
||||
if len(current_local) < 2 or not np.isfinite(current_local).all():
|
||||
raise ValueError('Current ordered lane path required for passing')
|
||||
current_arc = np.r_[0., np.cumsum(np.linalg.norm(np.diff(current_local[:, :2], axis=0), axis=1))]
|
||||
extent = min(110., float(current_arc[-1]), float(target_arc[-1]))
|
||||
if extent < self.transition_m + 12.:
|
||||
raise ValueError('Both lanes lack a bounded passing horizon')
|
||||
samples = np.linspace(0., extent, min(128, max(33, int(extent/.8)+1)))
|
||||
a = _resample(current_local, current_arc, samples)
|
||||
b = _resample(target_local, target_arc, samples)
|
||||
# Smooth quintic transition; preserve the actual target lane after the
|
||||
# transition so the full tractor/trailer can settle before returning.
|
||||
t = np.clip(samples/self.transition_m, 0., 1.)
|
||||
blend = t*t*t*(t*(t*6.-15.)+10.)
|
||||
path = a*(1.-blend[:, None])+b*blend[:, None]
|
||||
# Recompute arc from the blended path; a synthetic s field is valid
|
||||
# because every point remains on a measured pair of lane centerlines.
|
||||
arc = np.r_[0., np.cumsum(np.linalg.norm(np.diff(path[:, :2], axis=0), axis=1))]
|
||||
if arc[-1] < 20. or path[1, 0]/max(1e-6, np.linalg.norm(path[1, :2])) < .6:
|
||||
raise ValueError('Passing path is not forward-directed')
|
||||
# The native controller accepts at most 120 m of ordered traversal.
|
||||
# A curved adjacent lane can add enough lateral arc to push the 100 m
|
||||
# forward horizon over that bound, which used to throw and disengage
|
||||
# exactly when an automatic pass began. Trim by measured arc while
|
||||
# retaining the lane-change transition already travelled.
|
||||
if arc[-1] > 118.:
|
||||
limit = 118.
|
||||
keep = int(np.searchsorted(arc, limit, side='left'))
|
||||
keep = max(2, min(len(path), keep))
|
||||
samples = np.r_[arc[:keep], limit]
|
||||
path = np.column_stack([np.interp(samples, arc, path[:, i]) for i in range(3)])
|
||||
arc = samples
|
||||
return dict(s=arc.tolist(), x=path[:, 0].tolist(), y=path[:, 1].tolist(),
|
||||
z=path[:, 2].tolist())
|
||||
|
||||
@staticmethod
|
||||
def _frame(sdk):
|
||||
position = np.asarray(sdk['world_position'], float)
|
||||
yaw = float(sdk['world_rotation'][0])*2.*math.pi
|
||||
forward = np.array([-math.sin(yaw), -math.cos(yaw)])
|
||||
right = np.array([-forward[1], forward[0]])
|
||||
return position, forward, right
|
||||
|
||||
def _project(self, lane, sdk):
|
||||
position, forward, _ = self._frame(sdk)
|
||||
points = np.asarray(lane['centerline'], float)
|
||||
hit = _project_line(points, position, forward)
|
||||
if hit is None:
|
||||
raise ValueError('Adjacent lane has no aligned measured road surface')
|
||||
tail = np.vstack((hit['projection'], points[hit['index']+1:]))
|
||||
lengths = np.linalg.norm(np.diff(tail[:, [0, 2]], axis=0), axis=1)
|
||||
tail = tail[np.r_[True, lengths > 1e-5]]
|
||||
return hit, tail
|
||||
|
||||
def _gap(self, report, target, sdk, speed, now, *, committed=False):
|
||||
if (not isinstance(report, dict) or not _fresh(report, now)
|
||||
or report.get('latest_read_failed') is True
|
||||
or report.get('trailer_chain_traversal_complete') is not True
|
||||
or report.get('ego_geometry_available') is not True):
|
||||
raise ValueError('Fresh complete native body observations required for passing')
|
||||
actors = report.get('actors')
|
||||
if not isinstance(actors, list) or len(actors) > 500:
|
||||
raise ValueError('Bounded native actor list required for passing')
|
||||
width = number(target.get('width_m'))
|
||||
if width is None or not 2. <= width <= 5.:
|
||||
raise ValueError('Measured adjacent lane width required')
|
||||
position, forward, _ = self._frame(sdk)
|
||||
points = np.asarray(target['centerline'], float)
|
||||
ego_hit = _project_line(points, position, forward)
|
||||
if ego_hit is None:
|
||||
raise ValueError('Adjacent lane association unavailable')
|
||||
arc = np.r_[0., np.cumsum(np.linalg.norm(np.diff(points[:, [0, 2]], axis=0), axis=1))]
|
||||
ego_s = arc[ego_hit['index']]+ego_hit['fraction']*(arc[ego_hit['index']+1]-arc[ego_hit['index']])
|
||||
front = number(report.get('own_front_extent_m'))
|
||||
bodies = [report.get('ego_vehicle'), *(report.get('ego_trailers') or [])]
|
||||
if front is None or not bodies or report.get('ego_trailer_attached') != bool(report.get('ego_trailers')):
|
||||
raise ValueError('Measured own tractor and trailer extents required')
|
||||
rear = 0.
|
||||
for body in bodies:
|
||||
center = np.asarray(body['world_position'], float)
|
||||
heading = float(body['world_heading_rad'])
|
||||
length, body_width = float(body['length_m']), float(body['width_m'])
|
||||
yaw = float(sdk['world_rotation'][0])*2.*math.pi
|
||||
extent = abs(math.cos(heading-yaw))*length/2.+abs(math.sin(heading-yaw))*body_width/2.
|
||||
rear = min(rear, float((center-position)[[0, 2]]@forward)-extent)
|
||||
nearest_front = nearest_rear = math.inf
|
||||
for actor in actors:
|
||||
center = np.asarray(actor['world_position'], float)
|
||||
length, actor_width = number(actor.get('length_m')), number(actor.get('width_m'))
|
||||
heading = number(actor.get('world_heading_rad'))
|
||||
if (center.shape != (3,) or not np.isfinite(center).all()
|
||||
or any(v is None for v in (length, actor_width, heading))
|
||||
or not .2 <= length <= 60. or not .2 <= actor_width <= 6.):
|
||||
raise ValueError('Native actor footprint is incomplete')
|
||||
# Project every body on the actual target road, including opposing
|
||||
# and crossing bodies. Absolute road offsets are not ego offsets.
|
||||
ground = center.copy()
|
||||
height = number(actor.get('height_m'))
|
||||
if height is None:
|
||||
raise ValueError('Native actor height is incomplete')
|
||||
ground[1] -= height/2.
|
||||
hit = _project_line(points, ground, forward)
|
||||
if hit is None:
|
||||
continue
|
||||
index = hit['index']
|
||||
tangent = points[index+1, [0, 2]]-points[index, [0, 2]]
|
||||
tangent /= np.linalg.norm(tangent)
|
||||
body_forward = np.array([-math.sin(heading), -math.cos(heading)])
|
||||
cosine = float(body_forward@tangent)
|
||||
sine = float(body_forward[0]*tangent[1]-body_forward[1]*tangent[0])
|
||||
half_width = abs(sine)*length/2.+abs(cosine)*actor_width/2.
|
||||
if hit['error_m'] > width/2.+half_width+.2:
|
||||
continue
|
||||
actor_s = arc[index]+hit['fraction']*(arc[index+1]-arc[index])
|
||||
half_length = abs(cosine)*length/2.+abs(sine)*actor_width/2.
|
||||
lo, hi = actor_s-ego_s-half_length, actor_s-ego_s+half_length
|
||||
velocity = actor.get('world_velocity_mps')
|
||||
known = (actor.get('motion_available') is True and actor.get('motion_confidence', 0.) > 0.
|
||||
and isinstance(velocity, (list, tuple)) and len(velocity) == 3
|
||||
and all(number(v) is not None for v in velocity)
|
||||
and number(actor.get('measured_age_s')) is not None
|
||||
and 0. <= actor['measured_age_s'] <= .3)
|
||||
if not known and -100. < lo < 120.:
|
||||
raise ValueError('Target lane actor motion is not yet measured')
|
||||
actor_speed = float(np.asarray(velocity)[[0, 2]]@tangent) if known else 0.
|
||||
if lo >= front:
|
||||
gap = lo-front
|
||||
nearest_front = min(nearest_front, gap)
|
||||
required = max(self.MIN_GAP_M, speed*.8, max(0., speed-actor_speed)*3.)
|
||||
if not committed and gap < required:
|
||||
raise ValueError('Target lane forward gap is too small or closing')
|
||||
elif hi <= rear:
|
||||
gap = rear-hi
|
||||
nearest_rear = min(nearest_rear, gap)
|
||||
required = max(self.REAR_GAP_M, max(0., actor_speed-speed)*4.)
|
||||
if not committed and gap < required:
|
||||
raise ValueError('Target lane rear gap is too small or closing')
|
||||
else:
|
||||
raise ValueError('Target lane body overlaps the tractor or trailer')
|
||||
return dict(front_gap_m=None if math.isinf(nearest_front) else nearest_front,
|
||||
rear_gap_m=None if math.isinf(nearest_rear) else nearest_rear,
|
||||
own_rear_extent_m=rear, target_lane_width_m=width)
|
||||
|
||||
def _begin(self, scene, plan, current, target, direction):
|
||||
sdk = scene['sdk']
|
||||
hit, tail = self._project(target, sdk)
|
||||
self.transition_m = max(self.TRANSITION_M, min(85., max(0., sdk['speed_mps'])*3.5))
|
||||
points = np.asarray(target['centerline'], float)
|
||||
arc = np.r_[0., np.cumsum(np.linalg.norm(np.diff(points[:, [0, 2]], axis=0), axis=1))]
|
||||
station = arc[hit['index']]+hit['fraction']*(arc[hit['index']+1]-arc[hit['index']])
|
||||
spans = list(target.get('validated_spans') or [])
|
||||
if plan.get('source_geometry_opt_in') is True:
|
||||
spans += [span for span in target.get('source_qualified_spans', []) if source_span_verified(target, span)]
|
||||
spans += [span for span in target.get('post_transition_source_qualified_spans', []) if source_span_verified(target, span)]
|
||||
if not any(span.get('usable_for_control') is True
|
||||
and span.get('start_s_m', math.inf) <= station+.1
|
||||
and span.get('end_s_m', -math.inf) >= station+self.transition_m+12.
|
||||
for span in spans):
|
||||
raise ValueError('Adjacent lane lacks qualified geometry through the transition')
|
||||
# Both paths start at the truck's current road station. The previous
|
||||
# implementation sampled the adjacent road from its distant start node.
|
||||
target_local = dict(target, centerline=tail.tolist())
|
||||
path = self._path(plan, current, target_local, sdk, scene['sampled_at'])
|
||||
position, forward, right = self._frame(sdk)
|
||||
local = np.column_stack([path[k] for k in ('x', 'y', 'z')])
|
||||
self.world_path = np.column_stack((position[0]+local[:, 0]*forward[0]+local[:, 1]*right[0],
|
||||
position[1]-local[:, 2],
|
||||
position[2]+local[:, 0]*forward[1]+local[:, 1]*right[1]))
|
||||
self.current_lane_id, self.target_lane_id = current['id'], target['id']
|
||||
self.direction, self.started = direction, scene['sampled_at']
|
||||
self.state = 'changing_out' if direction == 'left' else 'changing_back'
|
||||
|
||||
def _anchored_path(self, sdk):
|
||||
position, forward, right = self._frame(sdk)
|
||||
hit = _project_line(self.world_path, position, forward)
|
||||
if hit is None or hit['error_m'] > 1.75:
|
||||
raise ValueError('Truck departed the anchored passing path')
|
||||
line = np.vstack((hit['projection'], self.world_path[hit['index']+1:]))
|
||||
local, _ = _local_points(line, position, float(sdk['world_rotation'][0])*2.*math.pi)
|
||||
lengths = np.linalg.norm(np.diff(local[:, :2], axis=0), axis=1)
|
||||
local = local[np.r_[True, lengths > 1e-5]]
|
||||
arc = np.r_[0., np.cumsum(np.linalg.norm(np.diff(local[:, :2], axis=0), axis=1))]
|
||||
if arc[-1] < 3.:
|
||||
raise ValueError('Anchored passing path exhausted before settling')
|
||||
delta = position-hit['projection']
|
||||
association = dict(ego_lateral_right_m=float(delta[[0, 2]]@right),
|
||||
heading_dot=hit['heading_dot'], distance_to_center_m=hit['error_m'])
|
||||
full_arc = np.r_[0., np.cumsum(np.linalg.norm(np.diff(self.world_path[:, [0, 2]], axis=0), axis=1))]
|
||||
progress = full_arc[hit['index']]+hit['fraction']*(full_arc[hit['index']+1]-full_arc[hit['index']])
|
||||
return dict(s=arc.tolist(), **{k:local[:, i].tolist() for i,k in enumerate(('x','y','z'))}), association, progress
|
||||
|
||||
def _report(self, now, path, association, permission, clearance, reason):
|
||||
return dict(_empty(now, reason, self.state), available=True, active=True,
|
||||
allowed_for_gameplay=True, route_revision=self.route_revision,
|
||||
current_lane_id=self.current_lane_id, target_lane_id=self.target_lane_id,
|
||||
path_override=path, association=association, mode=self.mode,
|
||||
world_path=self.world_path.tolist(),
|
||||
permission_verified=True, permission=permission,
|
||||
clearance_verified=True, clearance=clearance,
|
||||
obstacle_coverage='measured vehicles only',
|
||||
transition_m=self.transition_m, completion_verified=self.state == 'passing',
|
||||
direction=self.direction, signal_pulse=self.direction if self.state.startswith('changing') else 'none',
|
||||
signal_request_id='%s:%s:%s:%.3f' % (
|
||||
self.route_revision, self.current_lane_id, self.target_lane_id, self.started))
|
||||
|
||||
def assess(self, scene, native_plan=None):
|
||||
now = number(scene.get('sampled_at'))
|
||||
if now is None:
|
||||
raise ValueError('Finite overtake scene time required')
|
||||
if scene.get('engaged') is False:
|
||||
self.reset()
|
||||
return _empty(now, 'Automatic passing awaits F8 engagement')
|
||||
plan = native_plan if native_plan is not None else scene.get('native_plan')
|
||||
if not isinstance(plan, dict):
|
||||
self.reset()
|
||||
return _empty(now, 'Native route plan required')
|
||||
revision = plan.get('route_revision')
|
||||
if revision != self.route_revision:
|
||||
self.reset()
|
||||
self.route_revision = revision
|
||||
if not _fresh(plan, now, .35) or plan.get('usable_for_control') is not True:
|
||||
return _empty(now, plan.get('reason') or 'Qualified current lane required', 'waiting')
|
||||
sources = scene.get('sources') or {}
|
||||
graph = (sources.get('lane_graph') or {}).get('data') or {}
|
||||
traffic = (sources.get('traffic') or {}).get('data') or scene.get('nearby_traffic') or {}
|
||||
sdk = scene.get('sdk') or {}
|
||||
try:
|
||||
speed = number(sdk.get('speed_mps'))
|
||||
if speed is None:
|
||||
raise ValueError('Current speed required for passing')
|
||||
lanes = {lane['id']:dict(lane, width_m=self._road_width(graph, lane))
|
||||
if lane.get('kind') == 'road' else lane for lane in graph.get('lanes', [])}
|
||||
current = lanes[plan['selected_lane_ids'][0]]
|
||||
if self.state.startswith('changing'):
|
||||
origin, target = lanes[self.current_lane_id], lanes[self.target_lane_id]
|
||||
permission = self._permission(graph, origin, target)
|
||||
# Once moving across a boundary, do not snap back for a shrinking
|
||||
# distant gap. Following the anchored path still brakes for any
|
||||
# body in that corridor. A body alongside blocks further motion.
|
||||
clearance = self._gap(traffic, target, sdk, speed, now, committed=True)
|
||||
path, association, progress = self._anchored_path(sdk)
|
||||
target_hit, _ = self._project(target, sdk)
|
||||
if (target_hit['error_m'] < .45 and target_hit['heading_dot'] > .995
|
||||
and progress >= self.transition_m-2.):
|
||||
if self.mode == 'gps_lane_change':
|
||||
self.reset()
|
||||
self.route_revision, self.completed_at = revision, now
|
||||
return dict(_empty(now, 'Required GPS lane reached', 'complete'),
|
||||
completion_verified=True, mode='gps_lane_change')
|
||||
if self.state == 'changing_back':
|
||||
self.reset()
|
||||
self.route_revision, self.completed_at = revision, now
|
||||
return dict(_empty(now, 'Pass complete; returned to travel lane', 'complete'),
|
||||
completion_verified=True)
|
||||
self.state = 'passing'
|
||||
elif now-self.started > max(self.MAX_MANEUVER_S, self.transition_m/max(2., speed)+5.):
|
||||
raise ValueError('Passing path did not settle; holding for manual recovery')
|
||||
return self._report(now, path, association, permission, clearance,
|
||||
'Moving into the GPS route lane' if self.mode == 'gps_lane_change' else
|
||||
'Returning to travel lane' if self.direction == 'right' else 'Passing slower traffic')
|
||||
required = plan.get('route_lane_change') or {}
|
||||
if required:
|
||||
if current['id'] != required.get('from_lane_id'):
|
||||
raise ValueError('GPS lane-change request no longer matches the current lane')
|
||||
target = lanes[required['to_lane_id']]
|
||||
if _lane_key(current) != _lane_key(target) or current.get('kind') != 'road':
|
||||
raise ValueError('GPS preparation requires an adjacent lane on this road')
|
||||
difference = (target['travel_direction']*float(target['offset_m'])
|
||||
-current['travel_direction']*float(current['offset_m']))
|
||||
direction = 'left' if difference < 0. else 'right'
|
||||
adjacent = self._choose_target(graph, current, direction)
|
||||
if adjacent['id'] != target['id']:
|
||||
raise ValueError('GPS preparation cannot skip an intervening lane')
|
||||
permission = self._permission(graph, current, target)
|
||||
clearance = self._gap(traffic, target, sdk, speed, now)
|
||||
self.mode, self.blocking_ids = 'gps_lane_change', set()
|
||||
self._begin(scene, plan, current, target, direction)
|
||||
path, association, _ = self._anchored_path(sdk)
|
||||
return self._report(now, path, association, permission, clearance,
|
||||
'Moving into the GPS route lane')
|
||||
if plan.get('gps_lane_preparation_pending') is True:
|
||||
return _empty(now, 'Staying on route to prepare for the upcoming GPS exit', 'waiting')
|
||||
if self.state == 'passing':
|
||||
if current.get('kind') != 'road':
|
||||
return _empty(now, 'Following the GPS path through the next junction', 'passing')
|
||||
# Keep the target lane through normal graph-segment handoffs.
|
||||
# Return only after every observed body of the passed consist is
|
||||
# behind the rear of our own trailer, with a newly checked gap.
|
||||
position, forward, _ = self._frame(sdk)
|
||||
own_rear = self._gap(traffic, current, sdk, speed, now, committed=True)['own_rear_extent_m']
|
||||
blockers = [actor for actor in traffic['actors'] if actor.get('id') in self.blocking_ids
|
||||
or actor.get('chain_root_id') in self.blocking_ids]
|
||||
passed = bool(blockers) and all(
|
||||
float((np.asarray(a['world_position'])-position)[[0, 2]]@forward)+float(a['length_m'])/2.
|
||||
< own_rear-8. for a in blockers)
|
||||
if passed:
|
||||
try:
|
||||
target = self._choose_target(graph, current, 'right')
|
||||
permission = self._permission(graph, current, target)
|
||||
clearance = self._gap(traffic, target, sdk, speed, now)
|
||||
self._begin(scene, plan, current, target, 'right')
|
||||
path, association, _ = self._anchored_path(sdk)
|
||||
return self._report(now, path, association, permission, clearance, 'Returning to travel lane')
|
||||
except ValueError as exc:
|
||||
waiting = str(exc)
|
||||
else:
|
||||
waiting = 'Waiting for the trailer to clear the passed vehicle'
|
||||
# Ordinary lane following continues in the passing lane; retain
|
||||
# behavior state without a stale, finite maneuver path.
|
||||
return dict(_empty(now, waiting, 'passing'), available=True,
|
||||
route_revision=revision, target_lane_id=current['id'],
|
||||
mode=self.mode, completion_verified=True)
|
||||
if self.completed_at is not None and now-self.completed_at < 3.:
|
||||
return _empty(now, 'Pass complete; holding travel lane', 'complete')
|
||||
lead, diagnostics = native_lead(plan, dict(sdk, nearby_traffic=traffic), now)
|
||||
if lead is None or not diagnostics.get('available'):
|
||||
return _empty(now, 'No measured lead vehicle blocking the set speed')
|
||||
if lead.get('motion_verified_for_following') is not True:
|
||||
raise ValueError('Lead speed is not yet measured')
|
||||
target_speed = number(scene.get('target_speed_mph'))
|
||||
lead_speed_mph = max(0., (speed+lead['relative_forward_mps'])*2.2369362921)
|
||||
if target_speed is None or target_speed <= lead_speed_mph+5. or lead['distance_m'] > max(self.TRIGGER_GAP_M, speed*3.5):
|
||||
return _empty(now, 'Lead does not block a faster set speed')
|
||||
signal = scene.get('signal_plan') or {}
|
||||
crossing = scene.get('crossing_plan') or {}
|
||||
if signal.get('stop_required') is True or crossing.get('association'):
|
||||
raise ValueError('Following the queue through a controlled junction')
|
||||
if current.get('kind') != 'road':
|
||||
raise ValueError('Automatic passing waits for an ordinary multi-lane road')
|
||||
target = self._choose_target(graph, current)
|
||||
permission = self._permission(graph, current, target)
|
||||
clearance = self._gap(traffic, target, sdk, speed, now)
|
||||
self.blocking_ids = {lead['id'], lead.get('chain_root_id')}-{None}
|
||||
self.mode = 'obstacle_bypass' if lead.get('type') in ('parked', 'parked-trailer') else 'overtake'
|
||||
self._begin(scene, plan, current, target, 'left')
|
||||
path, association, _ = self._anchored_path(sdk)
|
||||
return self._report(now, path, association, permission, clearance,
|
||||
'Bypassing a stopped vehicle' if self.mode == 'obstacle_bypass' else 'Passing slower traffic')
|
||||
except (KeyError, TypeError, ValueError, OverflowError, IndexError) as exc:
|
||||
return dict(_empty(now, str(exc), 'blocked' if self.state.startswith('changing') else 'waiting'),
|
||||
maneuver_hold=self.state.startswith('changing'), route_revision=revision)
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Bounded ordered native trajectories, parameterized by travelled distance."""
|
||||
import math
|
||||
import numpy as np
|
||||
|
||||
|
||||
def ordered_path(plan):
|
||||
"""Return local forward/right/down points without sorting or extending them."""
|
||||
if not isinstance(plan,dict):
|
||||
raise ValueError('Native plan required')
|
||||
traversal=plan.get('traversal_path')
|
||||
source=traversal if traversal is not None else plan['path']
|
||||
points=np.column_stack([source[k] for k in ('x','y','z')]).astype(float)
|
||||
if (points.ndim!=2 or points.shape[1]!=3 or not 2<=len(points)<=256
|
||||
or not np.isfinite(points).all() or not -5.<=points[0,0]<=5.
|
||||
or abs(points[0,1])>3. or abs(points[0,2])>1.):
|
||||
raise ValueError('Bounded native path associated with the truck required')
|
||||
lengths=np.linalg.norm(np.diff(points[:,:2],axis=0),axis=1)
|
||||
if np.any(lengths<=1e-5) or float(lengths.sum())>120.1:
|
||||
raise ValueError('Continuous bounded native traversal required')
|
||||
if traversal is None and np.any(np.diff(points[:,0])<=0.):
|
||||
raise ValueError('Legacy native path must remain monotonic forward')
|
||||
if traversal is not None:
|
||||
distance=np.asarray(source['s'],float)
|
||||
actual=np.r_[0.,np.cumsum(lengths)]
|
||||
if distance.shape!=(len(points),) or not np.isfinite(distance).all() or not np.allclose(distance,actual,atol=.01):
|
||||
raise ValueError('Native arc distance disagrees with ordered points')
|
||||
if (points[1,0]-points[0,0])/lengths[0]<.7:
|
||||
raise ValueError('Native traversal begins in an opposing direction')
|
||||
return points
|
||||
|
||||
|
||||
def steering(plan,speed,gain=.1254,lookahead_time_s=1.3,max_lookahead_m=35.):
|
||||
"""Pure pursuit on arc distance: bends may turn sideways or behind ego."""
|
||||
points=ordered_path(plan)
|
||||
if (not math.isfinite(speed) or speed<0. or not math.isfinite(gain) or gain<=0.
|
||||
or not math.isfinite(lookahead_time_s) or not 0.<lookahead_time_s<=3.
|
||||
or not math.isfinite(max_lookahead_m) or not 6.<=max_lookahead_m<=60.):
|
||||
raise ValueError('Finite native speed and positive steering gain required')
|
||||
distances=np.r_[0.,np.cumsum(np.linalg.norm(np.diff(points[:,:2],axis=0),axis=1))]
|
||||
if distances[-1]<3.:
|
||||
raise ValueError('Native traversal shorter than three metres')
|
||||
requested=max(6.,min(max_lookahead_m,speed*lookahead_time_s))
|
||||
distance=min(requested,float(distances[-1]))
|
||||
x,y=[float(np.interp(distance,distances,points[:,i])) for i in (0,1)]
|
||||
curvature=2.*y/max(1e-6,x*x+y*y)
|
||||
scale=min(1.,(distance/requested)**2)
|
||||
return dict(available=True,curvature=curvature,raw_axis=-curvature/gain*scale,
|
||||
undamped_axis=-curvature/gain,extent_gain_scale=scale,lookahead_m=distance,
|
||||
requested_lookahead_m=requested,path_extent_m=float(distances[-1]),
|
||||
lookahead_limited=distance<requested,target_lateral_m=y,target_forward_m=x,
|
||||
source='ATS native ordered-path pursuit')
|
||||
|
||||
|
||||
def curve_speed(plan,lateral_accel=2.,deceleration=1.5,curvature_window_m=0.):
|
||||
points=ordered_path(plan)
|
||||
if (not all(math.isfinite(v) for v in (lateral_accel,deceleration,curvature_window_m))
|
||||
or lateral_accel<=0. or deceleration<=0. or not 0.<=curvature_window_m<=20.):
|
||||
raise ValueError('Finite positive curve dynamics and bounded curvature window required')
|
||||
distance=np.r_[0.,np.cumsum(np.linalg.norm(np.diff(points[:,:2],axis=0),axis=1))]
|
||||
best=None
|
||||
for i,(a,b,c) in enumerate(zip(points,points[1:],points[2:])):
|
||||
if curvature_window_m:
|
||||
center=distance[i+1]
|
||||
sample=[max(0.,center-curvature_window_m/2.),center,
|
||||
min(distance[-1],center+curvature_window_m/2.)]
|
||||
a,b,c=np.column_stack([np.interp(sample,distance,points[:,k]) for k in range(3)])
|
||||
ab,ac,bc=b[:2]-a[:2],c[:2]-a[:2],c[:2]-b[:2]
|
||||
denominator=np.linalg.norm(ab)*np.linalg.norm(ac)*np.linalg.norm(bc)
|
||||
if denominator<1e-6:continue
|
||||
curvature=abs(2.*(ab[0]*ac[1]-ab[1]*ac[0])/denominator)
|
||||
if curvature<1e-4:continue
|
||||
bend_speed=math.sqrt(lateral_accel/curvature)
|
||||
allowed=math.sqrt(bend_speed*bend_speed+2.*deceleration*distance[i+1])*2.2369362921
|
||||
if best is None or allowed<best['speed_limit_mph']:
|
||||
best=dict(speed_limit_mph=allowed,bend_distance_m=float(distance[i+1]),curvature=curvature)
|
||||
return dict(available=True,covered_distance_m=float(distance[-1]),**(best or dict(speed_limit_mph=None)))
|
||||
@@ -0,0 +1,789 @@
|
||||
"""Route selection over authored game lanes, independent of neural inference.
|
||||
|
||||
This computes a native candidate path. Actual actuator eligibility inherits
|
||||
lane/connection verification; a preview cannot promote an unvalidated spline.
|
||||
"""
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
from telemetry.driving_scene import number
|
||||
from telemetry.native_player_access import route_eligible
|
||||
from telemetry.native_geometry import ROAD_INTERPOLATION_SOURCE,ROAD_OFFSET_SOURCE
|
||||
|
||||
PROFILE_TRANSITION_MAX_GAP_M = 4.5
|
||||
# A profile handoff is a change in road cross-section, not permission to jump
|
||||
# sideways at the authored node. Use a bounded arc on both sides of the node
|
||||
# so the trailer sees a continuous path. If either lane is too short for that
|
||||
# arc, the handoff stays unqualified and the controller holds before it.
|
||||
PROFILE_TRANSITION_MIN_ARC_M = 8.0
|
||||
PROFILE_TRANSITION_MAX_ARC_M = 20.0
|
||||
PROFILE_TRANSITION_MAX_HEADING_STEP_DEG = 28.0
|
||||
PROFILE_TRANSITION_ENTRY_WINDOW_M = 32.0
|
||||
|
||||
|
||||
def unavailable(reason, now):
|
||||
return dict(available=False, reason=reason, sampled_at=now, age_s=0.,
|
||||
usable_for_control=False, selected_lane_ids=[], path=None,
|
||||
route_revision=None, lane_membership_verified=False,
|
||||
clearance_verified=False, intersection_priority_verified=False,
|
||||
source='ATS directed native lane graph')
|
||||
|
||||
|
||||
def closest(points, position, forward):
|
||||
# Authored prefab paths can contain thousands of segments. Project them
|
||||
# together: a Python/NumPy call per segment used to delay fresh commands.
|
||||
# Keep the original heading/height gates and first-minimum tie behavior.
|
||||
points = np.asarray(points, dtype=float)
|
||||
if len(points) < 2:
|
||||
return None
|
||||
position = np.asarray(position, dtype=float)
|
||||
delta = np.diff(points, axis=0)
|
||||
horizontal = delta[:, [0, 2]]
|
||||
length = np.linalg.norm(horizontal, axis=1)
|
||||
indices = np.flatnonzero(length >= 1e-6)
|
||||
if not len(indices):
|
||||
return None
|
||||
heading = (horizontal[indices]/length[indices, None]) @ forward
|
||||
indices = indices[heading >= .7]
|
||||
heading = heading[heading >= .7]
|
||||
if not len(indices):
|
||||
return None
|
||||
offset = (position-points[indices])[:, [0, 2]]
|
||||
fraction = np.clip(np.sum(offset*horizontal[indices], axis=1)/length[indices]**2, 0., 1.)
|
||||
projection = points[indices]+fraction[:, None]*delta[indices]
|
||||
lateral = np.linalg.norm((position-projection)[:, [0, 2]], axis=1)
|
||||
height = np.abs(position[1]-projection[:, 1])
|
||||
score = lateral+height*2.+(1.-heading)*3.
|
||||
valid = np.flatnonzero((height <= 1.) & np.isfinite(score))
|
||||
if not len(valid):
|
||||
return None
|
||||
j = int(valid[np.argmin(score[valid])])
|
||||
return dict(index=int(indices[j]), fraction=float(fraction[j]), projection=projection[j],
|
||||
error_m=float(lateral[j]), height_error_m=float(height[j]),
|
||||
heading_dot=float(heading[j]), score=float(score[j]))
|
||||
|
||||
|
||||
def same_lane_prefab_continuation(lane_ids, lanes):
|
||||
"""Resolve a same-exit fork only when authored lane slots identify it.
|
||||
|
||||
A prefab can offer both an ordinary continuation and an optional lane
|
||||
change between the same GPS nodes. GPS cannot distinguish these paths,
|
||||
but the PPD input/output slots can: keep the unique unchanged slot. This
|
||||
does not resolve different exits, different inputs, or duplicate paths.
|
||||
"""
|
||||
if len(lane_ids) < 2:
|
||||
return None
|
||||
records = [lanes[key] for key in lane_ids]
|
||||
first = records[0]
|
||||
identity = (first.get('prefab_uid'), first.get('start_node_uid'),
|
||||
first.get('end_node_uid'), first.get('input_lane_index'))
|
||||
if any(value is None for value in identity):
|
||||
return None
|
||||
for lane in records:
|
||||
if (lane.get('kind') != 'prefab'
|
||||
or lane.get('authoring_formula_verified') is not True
|
||||
or lane.get('input_lane_index_source') != 'PPD raw input slot'
|
||||
or (lane.get('prefab_uid'), lane.get('start_node_uid'),
|
||||
lane.get('end_node_uid'), lane.get('input_lane_index')) != identity
|
||||
or type(lane.get('output_lane_index')) is not int
|
||||
or type(lane.get('input_lane_index')) is not int):
|
||||
return None
|
||||
unchanged = [lane['id'] for lane in records
|
||||
if lane['input_lane_index'] == lane['output_lane_index']]
|
||||
return unchanged[0] if len(unchanged) == 1 else None
|
||||
|
||||
|
||||
def source_span_verified(lane,span):
|
||||
proof=span.get('proof') or {}
|
||||
transition = span.get('transition_kind') == 'road-profile'
|
||||
if (span.get('qualification_kind')!='source-derived-experimental'
|
||||
or span.get('empirically_validated') is not False
|
||||
or span.get('requires_explicit_native_experimental_opt_in') is not True
|
||||
or proof.get('mounted_sources_verified') is not True or not span.get('geometry_sha256')):
|
||||
return False
|
||||
if lane.get('kind')=='prefab':
|
||||
return bool(proof.get('asset_sha256'))
|
||||
if lane.get('kind')=='road':
|
||||
length=number(proof.get('stored_length_m'))
|
||||
return bool(proof.get('road_look_source_sha256')
|
||||
and proof.get('interpolation_source')==ROAD_INTERPOLATION_SOURCE
|
||||
and proof.get('offset_source')==ROAD_OFFSET_SOURCE
|
||||
and ((not transition and proof.get('cross_profile_transition') is False)
|
||||
or (transition and proof.get('cross_profile_transition') is True
|
||||
and proof.get('transition_edge_required') is True))
|
||||
and length is not None and length>0.)
|
||||
return False
|
||||
|
||||
|
||||
def _horizontal_length(a, b):
|
||||
return float(np.linalg.norm((np.asarray(b, float)-np.asarray(a, float))[[0, 2]]))
|
||||
|
||||
|
||||
def _trim_tail(points, distance):
|
||||
"""Return a polyline shortened by distance at its forward end."""
|
||||
result = [list(map(float, point)) for point in points]
|
||||
remaining = max(0.0, float(distance))
|
||||
while len(result) > 1:
|
||||
length = _horizontal_length(result[-2], result[-1])
|
||||
if length <= 1e-6:
|
||||
result.pop()
|
||||
continue
|
||||
if remaining <= length:
|
||||
fraction = remaining / length
|
||||
result[-1] = (np.asarray(result[-1])*(1.-fraction)
|
||||
+np.asarray(result[-2])*fraction).tolist()
|
||||
return result
|
||||
remaining -= length
|
||||
result.pop()
|
||||
return result
|
||||
|
||||
|
||||
def _trim_head(points, distance):
|
||||
"""Return a polyline shortened by distance at its beginning."""
|
||||
result = [list(map(float, point)) for point in points]
|
||||
remaining = max(0.0, float(distance))
|
||||
while len(result) > 1:
|
||||
length = _horizontal_length(result[0], result[1])
|
||||
if length <= 1e-6:
|
||||
result.pop(0)
|
||||
continue
|
||||
if remaining <= length:
|
||||
fraction = remaining / length
|
||||
result[0] = (np.asarray(result[0])*(1.-fraction)
|
||||
+np.asarray(result[1])*fraction).tolist()
|
||||
return result
|
||||
remaining -= length
|
||||
result.pop(0)
|
||||
return result
|
||||
|
||||
|
||||
def _unit_tangent(points, at_end=False):
|
||||
if len(points) < 2:
|
||||
return None
|
||||
a, b = (points[-2], points[-1]) if at_end else (points[0], points[1])
|
||||
delta = np.asarray(b, float)-np.asarray(a, float)
|
||||
length = float(np.linalg.norm(delta[[0, 2]]))
|
||||
if length <= 1e-6:
|
||||
return None
|
||||
delta = delta/length
|
||||
return delta
|
||||
|
||||
|
||||
def _transition_path(world, segment, gap):
|
||||
"""Join two profile lanes with a C1, forward-only bounded transition.
|
||||
|
||||
The old implementation interpolated directly between the two endpoint
|
||||
centers. That creates a lateral segment whose first heading is nearly
|
||||
perpendicular to the road. This routine consumes a short portion of both
|
||||
lanes and uses their measured tangents to make the cross-section change.
|
||||
It returns None when the available geometry cannot support a safe join.
|
||||
"""
|
||||
if gap <= .05:
|
||||
return list(segment)
|
||||
arc = max(PROFILE_TRANSITION_MIN_ARC_M,
|
||||
min(PROFILE_TRANSITION_MAX_ARC_M, gap*4.0))
|
||||
before = _trim_tail(world, arc)
|
||||
after = _trim_head(segment, arc)
|
||||
if len(before) < 2 or len(after) < 2:
|
||||
return None
|
||||
tangent0 = _unit_tangent(before, at_end=True)
|
||||
tangent1 = _unit_tangent(after, at_end=False)
|
||||
if tangent0 is None or tangent1 is None:
|
||||
return None
|
||||
horizontal_dot = float(np.dot(tangent0[[0, 2]], tangent1[[0, 2]]))
|
||||
if horizontal_dot < math.cos(math.radians(18.0)):
|
||||
return None
|
||||
p0, p3 = np.asarray(before[-1], float), np.asarray(after[0], float)
|
||||
forward = tangent0[[0, 2]]
|
||||
chord = p3-p0
|
||||
if float(np.dot(chord[[0, 2]], forward)) <= arc*.35:
|
||||
return None
|
||||
handle = min(arc*.65, max(2.0, _horizontal_length(p0, p3)*.45))
|
||||
p1 = p0+tangent0*handle
|
||||
p2 = p3-tangent1*handle
|
||||
t = np.linspace(0., 1., 17)[:, None]
|
||||
bridge = ((1-t)**3*p0 + 3*(1-t)**2*t*p1
|
||||
+ 3*(1-t)*t*t*p2 + t**3*p3)
|
||||
# Reject loops or a sharp sample-to-sample heading change. A path that
|
||||
# fails this check is safer as an unavailable route than as a false lane.
|
||||
deltas = np.diff(bridge[:, [0, 2]], axis=0)
|
||||
lengths = np.linalg.norm(deltas, axis=1)
|
||||
if np.any(lengths <= 1e-4):
|
||||
return None
|
||||
directions = deltas/lengths[:, None]
|
||||
angles = np.degrees(np.arccos(np.clip(np.sum(directions[:-1]*directions[1:], axis=1), -1., 1.)))
|
||||
if len(angles) and float(np.max(angles)) > PROFILE_TRANSITION_MAX_HEADING_STEP_DEG:
|
||||
return None
|
||||
if np.any(np.sum(deltas*forward[None, :], axis=1) <= 0.):
|
||||
return None
|
||||
return before[:-1] + bridge.tolist()[1:-1] + after
|
||||
|
||||
|
||||
def qualified_prefix(lanes, points, selected, edges, hit, allow_source_geometry=False,
|
||||
transition_entry_lane=None):
|
||||
"""Trim to contiguous independently measured spans, never extend evidence."""
|
||||
world, accepted = [], []
|
||||
for index, key in enumerate(selected):
|
||||
line = points[key]
|
||||
arc = np.r_[0., np.cumsum(np.linalg.norm(np.diff(line[:,[0,2]],axis=0),axis=1))]
|
||||
start = (arc[hit['index']]+hit['fraction']*(arc[hit['index']+1]-arc[hit['index']])) if index==0 else 0.
|
||||
end = start
|
||||
spans = list(lanes[key].get('validated_spans',[]))
|
||||
if allow_source_geometry:
|
||||
spans += [span for span in lanes[key].get('source_qualified_spans',[])
|
||||
if source_span_verified(lanes[key],span)]
|
||||
if index and edges[index-1].get('transition_kind') == 'road-profile':
|
||||
spans += [span for span in lanes[key].get('transition_source_qualified_spans',[])
|
||||
if source_span_verified(lanes[key],span)]
|
||||
spans += [span for span in lanes[key].get('post_transition_source_qualified_spans',[])
|
||||
if source_span_verified(lanes[key],span)]
|
||||
elif (index == 0 and key == transition_entry_lane
|
||||
and hit.get('distance_from_start_m', math.inf) <= PROFILE_TRANSITION_ENTRY_WINDOW_M):
|
||||
spans += [span for span in lanes[key].get('transition_source_qualified_spans',[])
|
||||
if source_span_verified(lanes[key],span)]
|
||||
elif index == 0 and key == transition_entry_lane:
|
||||
spans += [span for span in lanes[key].get('post_transition_source_qualified_spans',[])
|
||||
if source_span_verified(lanes[key],span)]
|
||||
spans.sort(key=lambda s:s.get('start_s_m',math.inf))
|
||||
for span in spans:
|
||||
a,b = number(span.get('start_s_m')),number(span.get('end_s_m'))
|
||||
if (span.get('usable_for_control') is not True or a is None or b is None
|
||||
or a<0. or b<=a or b>arc[-1]+.001
|
||||
or not (span.get('evidence_sha256') or allow_source_geometry and span.get('geometry_sha256'))):
|
||||
continue
|
||||
if a <= end+.01 and b > end:
|
||||
end = b
|
||||
if end <= start+.1:
|
||||
break
|
||||
if index:
|
||||
edge = edges[index-1]
|
||||
gap = math.dist(world[-1],line[0])
|
||||
transition = edge.get('transition_kind') == 'road-profile'
|
||||
if (edge.get('from_lane_id') != selected[index-1] or edge.get('to_lane_id') != key
|
||||
or (gap>.05 and not transition)
|
||||
or (transition and gap>PROFILE_TRANSITION_MAX_GAP_M)
|
||||
or edge.get('heading_dot',0.)<.995):
|
||||
break
|
||||
start_point=[float(np.interp(start,arc,line[:,j])) for j in range(3)]
|
||||
end_point=[float(np.interp(end,arc,line[:,j])) for j in range(3)]
|
||||
segment=[start_point]+line[(arc>start+1e-5)&(arc<end-1e-5)].tolist()+[end_point]
|
||||
if not world or math.dist(world[-1],segment[0])<1e-5:
|
||||
world.extend(segment if not world else segment[1:])
|
||||
elif transition:
|
||||
joined = _transition_path(world, segment, gap)
|
||||
if joined is None:
|
||||
break
|
||||
world = joined
|
||||
else:
|
||||
world.extend(segment)
|
||||
accepted.append(key)
|
||||
if end < arc[-1]-.01:
|
||||
break
|
||||
return world,accepted
|
||||
|
||||
|
||||
def clip_to_pose(world, position, forward):
|
||||
"""Trim a fixed qualified traversal at the current projection."""
|
||||
line = np.asarray(world, float)
|
||||
if len(line) < 2:
|
||||
return [], None
|
||||
hit = closest(line, position, forward)
|
||||
if hit is None:
|
||||
return [], None
|
||||
return [hit['projection'].tolist()]+line[hit['index']+1:].tolist(), hit
|
||||
|
||||
|
||||
class NativeRoutePlanner:
|
||||
MAX_GRAPH_AGE_S = .5
|
||||
MAX_PATH_M = 100.
|
||||
# Keep steering bounded to MAX_PATH_M while carrying more verified route
|
||||
# ahead for speed planning. Every extra span still has to be connected and
|
||||
# route matched; this never authorizes an unqualified extension.
|
||||
MAX_SPEED_COVERAGE_M = 500.
|
||||
# The SDK pose is the truck reference point while authored lane geometry
|
||||
# follows the road surface. Small grade/anchor noise should not drop a
|
||||
# centered semi at speed.
|
||||
MAX_CONTROL_HEIGHT_ERROR_M = .75
|
||||
|
||||
def __init__(self, *, allow_source_geometry=False):
|
||||
self.allow_source_geometry=bool(allow_source_geometry)
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.lane_id = self.route_revision = None
|
||||
self.next_lane_id = self.trip_edge_index = None
|
||||
self._transition_entry_lane = None
|
||||
|
||||
def assess(self, scene):
|
||||
now = number(scene.get('sampled_at'))
|
||||
if now is None:
|
||||
raise ValueError('Finite native scene time required')
|
||||
empty = lambda reason: unavailable(reason, now)
|
||||
if not scene.get('sdk_fresh'):
|
||||
return empty('Fresh SDK pose required for native planning')
|
||||
sources = scene.get('sources') or {}
|
||||
graph_source, route_source = (sources.get(key) or {} for key in ('lane_graph', 'route'))
|
||||
if not graph_source.get('fresh'):
|
||||
return empty(graph_source.get('reason') or 'Native lane graph unavailable')
|
||||
if not route_source.get('fresh'):
|
||||
return empty('Matched active native GPS route required')
|
||||
graph, route = graph_source['data'], route_source['data']
|
||||
if route.get('lead_in') is not None or route.get('display_only'):
|
||||
return empty('GPS approach has not been matched to the native graph')
|
||||
sdk = scene['sdk']
|
||||
try:
|
||||
position = np.asarray(sdk['world_position'], float)
|
||||
rotation = np.asarray(sdk['world_rotation'], float)
|
||||
if (sdk.get('position_valid') is not True or position.shape != (3,)
|
||||
or rotation.shape != (3,) or not np.isfinite(position).all()
|
||||
or not np.isfinite(rotation).all()):
|
||||
raise ValueError('Finite native truck pose required')
|
||||
yaw = rotation[0]*2*math.pi
|
||||
forward = np.array([-math.sin(yaw), -math.cos(yaw)])
|
||||
nodes = route['nodes']
|
||||
if not isinstance(nodes, list) or not 2 <= len(nodes) <= 6000:
|
||||
raise ValueError('Bounded native route node sequence required')
|
||||
# ATS can repeat the current route node while it recalculates. A
|
||||
# consecutive repeat carries no directed edge and should not
|
||||
# invalidate an otherwise usable route; collapse only adjacent
|
||||
# duplicates and preserve every real transition.
|
||||
uids, unique_nodes = [], []
|
||||
for node in nodes:
|
||||
uid = str(node['uid'])
|
||||
if not uids or uid != uids[-1]:
|
||||
uids.append(uid)
|
||||
unique_nodes.append(node)
|
||||
nodes = unique_nodes
|
||||
if len(uids) < 2:
|
||||
raise ValueError('Bounded native route node sequence required')
|
||||
pairs = list(zip(uids, uids[1:]))
|
||||
records = graph['lanes']
|
||||
if not isinstance(records, list) or not 1 <= len(records) <= 10000:
|
||||
raise ValueError('Bounded native lane graph required')
|
||||
except (KeyError, TypeError, ValueError, OverflowError) as exc:
|
||||
return empty(str(exc))
|
||||
revision = route.get('route_revision') or route.get('revision')
|
||||
gps_pairs = set(pairs)
|
||||
trip = graph.get('trip_plan') or {}
|
||||
trip_policy = None
|
||||
graph_hash = (graph.get('provenance') or {}).get('cache_sha256')
|
||||
if (trip.get('available') is True and trip.get('source_verified') is True
|
||||
and trip.get('route_revision') == revision and graph_hash
|
||||
and (trip.get('graph_sha256') == graph_hash
|
||||
or trip.get('cache_extension_compatible') is True
|
||||
and trip.get('active_graph_sha256') == graph_hash)):
|
||||
compiled_pairs, policies = trip.get('directed_pairs'), trip.get('lane_policy')
|
||||
if (isinstance(compiled_pairs, list) and isinstance(policies, list)
|
||||
and len(compiled_pairs) == len(policies) and 1 <= len(policies) <= 12000
|
||||
and all(isinstance(p, list) and len(p) == 2 for p in compiled_pairs)):
|
||||
pairs = [tuple(map(str, p)) for p in compiled_pairs]
|
||||
trip_policy = policies
|
||||
maneuver = scene.get('lane_maneuver') or {}
|
||||
maneuver_hit = None
|
||||
maneuver_ids = {maneuver.get('current_lane_id'), maneuver.get('target_lane_id')}-{None}
|
||||
maneuver_stamp = number(maneuver.get('sampled_at'))
|
||||
if (maneuver.get('active') is True and maneuver.get('allowed_for_gameplay') is True
|
||||
and maneuver.get('permission_verified') is True
|
||||
and maneuver.get('clearance_verified') is True
|
||||
and maneuver.get('route_revision') == revision
|
||||
and maneuver_stamp is not None and 0. <= now-maneuver_stamp <= .3
|
||||
and len(maneuver_ids) == 2):
|
||||
try:
|
||||
line = np.asarray(maneuver['world_path'], float)
|
||||
if line.ndim == 2 and line.shape[1] == 3 and 2 <= len(line) <= 256 and np.isfinite(line).all():
|
||||
hit = closest(line, position, forward)
|
||||
if hit is not None and hit['error_m'] <= 1.25 and hit['heading_dot'] >= .97:
|
||||
maneuver_hit = hit
|
||||
except (KeyError, TypeError, ValueError):
|
||||
pass
|
||||
if revision != self.route_revision:
|
||||
self.reset()
|
||||
self.route_revision = revision
|
||||
lanes, points, candidates, near_route = {}, {}, [], []
|
||||
raw_hits = {}
|
||||
for lane in records:
|
||||
try:
|
||||
if not route_eligible(lane, gps_pairs):
|
||||
continue
|
||||
lane_id = lane['id']
|
||||
if not isinstance(lane_id, str) or lane_id in lanes:
|
||||
raise ValueError('Duplicate/invalid native lane identity')
|
||||
line = np.asarray(lane['centerline'], float)
|
||||
if (line.ndim != 2 or line.shape[1] != 3 or not 2 <= len(line) <= 8192
|
||||
or not np.isfinite(line).all()):
|
||||
continue
|
||||
lanes[lane_id], points[lane_id] = lane, line
|
||||
pair = str(lane['start_node_uid']), str(lane['end_node_uid'])
|
||||
if pair not in pairs:
|
||||
continue
|
||||
route_indices = [i for i,p in enumerate(pairs) if p == pair
|
||||
and (trip_policy is None or lane_id in trip_policy[i])]
|
||||
if not route_indices:
|
||||
continue
|
||||
hit = closest(line, position, forward)
|
||||
if hit is not None:
|
||||
arc=np.r_[0.,np.cumsum(np.linalg.norm(np.diff(line[:,[0,2]],axis=0),axis=1))]
|
||||
hit['distance_from_start_m'] = float(
|
||||
arc[hit['index']]+hit['fraction']*(arc[hit['index']+1]-arc[hit['index']]))
|
||||
remaining=arc[-1]-hit['distance_from_start_m']
|
||||
raw_hits[lane_id] = hit
|
||||
# A lane with an explicit connected successor remains
|
||||
# current until its endpoint is consumed. Switching three
|
||||
# metres early treats the next lane's longitudinal start
|
||||
# gap as lateral misalignment and drops a centered truck.
|
||||
if remaining<=.1:continue
|
||||
near_route.append((hit['score'],lane_id,hit))
|
||||
if hit['error_m'] <= 3.:
|
||||
# The physical GPS array includes already travelled
|
||||
# nodes. Pick the correct occurrence on looping trips
|
||||
# from its distance-to-destination, never list.index.
|
||||
remaining_trip = number(route.get('navigation_distance_m'))
|
||||
if remaining_trip is None:
|
||||
remaining_trip = number(sdk.get('navigation_distance_m'))
|
||||
origins = trip.get('gps_edge_indices') if trip_policy is not None else None
|
||||
def progress_error(i):
|
||||
original = origins[i] if origins else i
|
||||
distance = number(nodes[original].get('distance_to_end_m'))
|
||||
past = trip_policy is not None and self.trip_edge_index is not None and i < self.trip_edge_index
|
||||
residual = abs(distance-remaining_trip) if distance is not None and remaining_trip is not None else 0.
|
||||
return past, residual, i
|
||||
index = min(route_indices, key=progress_error)
|
||||
candidates.append((hit['score'], lane_id, index, hit))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
# A profile change moves the road's coordinate origin sideways. Its
|
||||
# bridge must be anchored to both complete primitives, not to the
|
||||
# shrinking piece ahead of the truck. Project membership on that same
|
||||
# bridge while crossing its seam; the raw target center is deliberately
|
||||
# offset until the end of the bridge.
|
||||
profile_matches = []
|
||||
if graph.get('source_verified') is True:
|
||||
by_candidate = {c[1]: c for c in candidates}
|
||||
for edge in graph.get('connections', ()):
|
||||
if (not isinstance(edge, dict) or edge.get('transition_kind') != 'road-profile'
|
||||
or edge.get('route_bound') is not True or edge.get('heading_dot', 0.) < .995):
|
||||
continue
|
||||
source, target = edge.get('from_lane_id'), edge.get('to_lane_id')
|
||||
if source not in points or target not in points:
|
||||
continue
|
||||
source_candidate, target_candidate = by_candidate.get(source), by_candidate.get(target)
|
||||
index = (source_candidate[2] if source_candidate else
|
||||
target_candidate[2]-1 if target_candidate else -1)
|
||||
if index < 0 or index+1 >= len(pairs):
|
||||
continue
|
||||
if (pairs[index] != (str(lanes[source]['start_node_uid']), str(lanes[source]['end_node_uid']))
|
||||
or pairs[index+1] != (str(lanes[target]['start_node_uid']), str(lanes[target]['end_node_uid']))):
|
||||
continue
|
||||
if trip_policy is not None:
|
||||
policy = trip_policy[index].get(source) or {}
|
||||
if policy.get('kind') != 'continue' or policy.get('next_lane_id') != target:
|
||||
continue
|
||||
gap = math.dist(points[source][-1], points[target][0])
|
||||
if not .05 < gap <= PROFILE_TRANSITION_MAX_GAP_M:
|
||||
continue
|
||||
arc = max(PROFILE_TRANSITION_MIN_ARC_M,
|
||||
min(PROFILE_TRANSITION_MAX_ARC_M, gap*4.))
|
||||
tangent = _unit_tangent(points[source], at_end=True)
|
||||
if tangent is None:
|
||||
continue
|
||||
station = float(np.dot((position-points[source][-1])[[0, 2]], tangent[[0, 2]]))
|
||||
if not -arc-1. <= station <= arc+1.:
|
||||
continue
|
||||
reference, ids = qualified_prefix(lanes, points, [source, target], [edge],
|
||||
dict(index=0, fraction=0.), self.allow_source_geometry)
|
||||
if ids != [source, target]:
|
||||
continue
|
||||
_, association_hit = clip_to_pose(reference, position, forward)
|
||||
if association_hit is None or association_hit['error_m'] > 3.:
|
||||
continue
|
||||
preferred = source if station < 0. else target
|
||||
original_hit = raw_hits.get(preferred)
|
||||
if original_hit is None:
|
||||
continue
|
||||
hit = dict(original_hit, profile_association_hit=association_hit,
|
||||
profile_source_id=source, profile_target_id=target, profile_edge=edge)
|
||||
profile_matches.append((association_hit['score'], preferred,
|
||||
index if preferred == source else index+1, hit))
|
||||
if profile_matches:
|
||||
profile_matches.sort(key=lambda c:(c[0], c[1]))
|
||||
match = profile_matches[0]
|
||||
transition_ids = {match[3]['profile_source_id'], match[3]['profile_target_id']}
|
||||
candidates = [c for c in candidates if c[1] not in transition_ids]+[match]
|
||||
if not candidates:
|
||||
result=empty('No forward native lane on the GPS route near this pose')
|
||||
if trip_policy is not None:
|
||||
# Explain the actual route blocker, rather than making a
|
||||
# truck-only restriction look like a hotkey/input failure.
|
||||
nearest_issue = None
|
||||
for issue in trip.get('issues', ()):
|
||||
origin = issue.get('gps_edge_index')
|
||||
if type(origin) is not int or not 0 <= origin < len(nodes)-1:
|
||||
continue
|
||||
try:
|
||||
distance = min(math.dist(position, nodes[i]['position']) for i in (origin, origin+1))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if nearest_issue is None or distance < nearest_issue[0]:
|
||||
nearest_issue = distance, issue
|
||||
if nearest_issue and nearest_issue[0] < 500.:
|
||||
kind = nearest_issue[1]['reason']
|
||||
result['reason'] = {'truck-restricted':'GPS requests a truck-restricted path; choose another route',
|
||||
'player-inaccessible':'GPS path enters a game boundary closed to player trucks; reroute',
|
||||
'lane-connection-gap':'GPS lanes do not connect through the upcoming junction',
|
||||
'unqualified-geometry':'GPS segment lacks qualified truck geometry',
|
||||
'missing-geometry':'Whole-trip GPS map coverage is loading'}.get(kind, kind)
|
||||
result['trip_plan'] = dict(state=trip.get('state'), complete=trip.get('complete'),
|
||||
unresolved_segments=len(trip.get('issues') or []), artifact_path=trip.get('artifact_path'))
|
||||
if near_route:
|
||||
_,nearest,hit=min(near_route,key=lambda value:(value[0],value[1]))
|
||||
delta=position-hit['projection']
|
||||
lateral=float(-delta[0]*forward[1]+delta[2]*forward[0])
|
||||
result['association']=dict(nearest_lane_id=nearest,distance_to_center_m=hit['error_m'],
|
||||
ego_lateral_right_m=lateral,heading_dot=hit['heading_dot'],height_error_m=hit['height_error_m'])
|
||||
if abs(lateral)>1.75 and hit['error_m']<20.:
|
||||
side='right' if lateral>0. else 'left'
|
||||
result['reason']=f'Truck is {abs(lateral)*3.280839895:.1f} ft {side} of GPS lane center; center in lane'
|
||||
return result
|
||||
candidates.sort(key=lambda candidate: (candidate[0], candidate[1]))
|
||||
retained = next((candidate for candidate in candidates if candidate[1] == self.lane_id), None)
|
||||
if retained is None and trip_policy is not None:
|
||||
expected = next((c for c in candidates if c[1] == self.next_lane_id
|
||||
and c[0] <= candidates[0][0]+.1), None)
|
||||
if expected is not None:
|
||||
retained = expected
|
||||
if maneuver_hit is not None:
|
||||
# A lane change intentionally crosses the midpoint between two
|
||||
# lanes. Keep the nearest of the authorized pair, rather than
|
||||
# retaining the departure lane until it exceeds the center gate.
|
||||
pair = [candidate for candidate in candidates if candidate[1] in maneuver_ids]
|
||||
if pair:
|
||||
retained = min(pair, key=lambda candidate: (candidate[0], candidate[1]))
|
||||
chosen = retained or candidates[0]
|
||||
if retained is None:
|
||||
tied = [candidate for candidate in candidates if candidate[0]-chosen[0] < .1]
|
||||
preferred = None
|
||||
if trip_policy is not None and len({candidate[2] for candidate in tied}) == 1:
|
||||
best = min(tied, key=lambda c:(trip_policy[c[2]][c[1]].get('cost_to_region_end_m', math.inf), c[1]))
|
||||
preferred = best[1]
|
||||
else:
|
||||
preferred = same_lane_prefab_continuation([candidate[1] for candidate in tied], lanes)
|
||||
if preferred is not None:
|
||||
chosen = next(candidate for candidate in tied if candidate[1] == preferred)
|
||||
# Exact shared approach geometry can describe different exits. GPS must
|
||||
# resolve it; nearest-distance ties alone cannot decide a turn.
|
||||
if retained is None and len(candidates) > 1 and candidates[1][0]-chosen[0] < .1:
|
||||
a, b = (lanes[c[1]] for c in (chosen, candidates[1]))
|
||||
if (a['start_node_uid'], a['end_node_uid']) != (b['start_node_uid'], b['end_node_uid']):
|
||||
return empty('Native route lane association is ambiguous')
|
||||
_, lane_id, route_index, hit = chosen
|
||||
self.lane_id = lane_id
|
||||
self.trip_edge_index = route_index if trip_policy is not None else None
|
||||
selected = [lane_id]
|
||||
world = [hit['projection'].tolist()]+points[lane_id][hit['index']+1:].tolist()
|
||||
successors = {}
|
||||
for edge in graph.get('connections', []):
|
||||
if isinstance(edge, dict):
|
||||
successors.setdefault(edge.get('from_lane_id'), []).append(edge)
|
||||
used_edges, continuation = [], 'covered-route'
|
||||
initial_route_index = route_index
|
||||
lane_change = None
|
||||
if trip_policy is not None:
|
||||
choice = trip_policy[route_index].get(lane_id) or {}
|
||||
if choice.get('kind') == 'lane-change':
|
||||
target = choice.get('next_lane_id')
|
||||
if target in lanes:
|
||||
lane_change = dict(from_lane_id=lane_id, to_lane_id=target,
|
||||
edge_index=route_index, reason='Move into the required lane for the GPS route')
|
||||
length = sum(math.dist(a, b) for a, b in zip(world, world[1:]))
|
||||
# Keep the steering path bounded to MAX_PATH_M below, but carry at
|
||||
# least one uniquely route-matched successor for speed planning. A
|
||||
# long straight lane otherwise hides its already-qualified successor
|
||||
# until the last 100 m and makes the coverage brake slow highway turns
|
||||
# even when the next lane is connected and fully measured.
|
||||
while (length < self.MAX_SPEED_COVERAGE_M or not used_edges) and len(selected) < 16:
|
||||
choice = trip_policy[route_index].get(selected[-1]) if trip_policy is not None else None
|
||||
if choice is not None and choice.get('kind') != 'continue':
|
||||
continuation = 'gps-lane-change-required' if choice.get('kind') == 'lane-change' else choice.get('kind')
|
||||
break
|
||||
options = []
|
||||
for edge in successors.get(selected[-1], []):
|
||||
target = edge.get('to_lane_id')
|
||||
if target not in lanes or target in selected:
|
||||
continue
|
||||
if choice is not None and target != choice.get('next_lane_id'):
|
||||
continue
|
||||
lane = lanes[target]
|
||||
pair = str(lane['start_node_uid']), str(lane['end_node_uid'])
|
||||
if route_index+1 >= len(pairs) or pair != pairs[route_index+1]:
|
||||
continue
|
||||
error = math.dist(world[-1], points[target][0])
|
||||
transition = edge.get('transition_kind') == 'road-profile'
|
||||
if error <= .25 or (transition and error <= PROFILE_TRANSITION_MAX_GAP_M):
|
||||
options.append((error, target, edge))
|
||||
if len(options) > 1:
|
||||
preferred = same_lane_prefab_continuation([option[1] for option in options], lanes)
|
||||
if preferred is not None:
|
||||
options = [option for option in options if option[1] == preferred]
|
||||
if len(options) != 1:
|
||||
continuation = 'route-end' if route_index+1 >= len(pairs) else 'connection-missing-or-ambiguous'
|
||||
break
|
||||
_, target, edge = options[0]
|
||||
selected.append(target); used_edges.append(edge); route_index += 1
|
||||
extra = points[target].tolist()
|
||||
if math.dist(world[-1], extra[0]) < 1e-5:
|
||||
extra = extra[1:]
|
||||
world.extend(extra)
|
||||
length = sum(math.dist(a, b) for a, b in zip(world, world[1:]))
|
||||
self.next_lane_id = used_edges[0].get('to_lane_id') if used_edges else None
|
||||
local = np.asarray(world, float)-position
|
||||
transition_entry_lane = self._transition_entry_lane
|
||||
transition_targets = [edge.get('to_lane_id') for edge in used_edges
|
||||
if edge.get('transition_kind') == 'road-profile']
|
||||
if transition_targets:
|
||||
transition_entry_lane = transition_targets[-1]
|
||||
qualified, qualified_ids = qualified_prefix(
|
||||
lanes, points, selected, used_edges,
|
||||
dict(index=0, fraction=0.) if hit.get('profile_source_id') == lane_id else hit,
|
||||
self.allow_source_geometry,
|
||||
transition_entry_lane=transition_entry_lane)
|
||||
association_hit = hit.get('profile_association_hit') or hit
|
||||
if hit.get('profile_source_id'):
|
||||
source = hit['profile_source_id']
|
||||
if source != lane_id:
|
||||
qualified, qualified_ids = qualified_prefix(
|
||||
lanes, points, [source]+selected, [hit['profile_edge']]+used_edges,
|
||||
dict(index=0, fraction=0.), self.allow_source_geometry,
|
||||
transition_entry_lane=transition_entry_lane)
|
||||
qualified_ids = [key for key in qualified_ids if key != source]
|
||||
qualified, _ = clip_to_pose(qualified, position, forward)
|
||||
qualification_truncated = (qualified_ids != selected or (len(qualified) >= 2
|
||||
and math.dist(qualified[-1], world[-1]) > .01))
|
||||
center_bound = 2.5 if maneuver_hit is not None and lane_id in maneuver_ids else 1.75
|
||||
membership = (graph.get('source_verified') is True and bool(qualified_ids)
|
||||
and association_hit['error_m'] <= center_bound
|
||||
and association_hit['height_error_m'] <= self.MAX_CONTROL_HEIGHT_ERROR_M
|
||||
and association_hit['heading_dot'] >= .97)
|
||||
# A source-qualified span can end at a road-profile handoff even when
|
||||
# the route-matched lane graph still has a continuous, forward path.
|
||||
# In the native runner source geometry is an explicit experimental
|
||||
# opt-in; use that path for a bounded recovery instead of releasing the
|
||||
# lease at the handoff and leaving a moving truck with no steering.
|
||||
# This never promotes an unverified graph: the cache sources, pose
|
||||
# association, and route lane identity must all still be verified.
|
||||
source_recovery = False
|
||||
if (not membership and self.allow_source_geometry
|
||||
and graph.get('source_verified') is True
|
||||
and hit['error_m'] <= 1.75
|
||||
and hit['height_error_m'] <= self.MAX_CONTROL_HEIGHT_ERROR_M
|
||||
and hit['heading_dot'] >= .97
|
||||
and not hit.get('profile_source_id')
|
||||
and not any(edge.get('transition_kind') == 'road-profile' for edge in used_edges)
|
||||
and len(world) >= 2):
|
||||
current_lane = lanes.get(selected[0], {}) if selected else {}
|
||||
source_spans = list(current_lane.get('source_qualified_spans') or [])
|
||||
source_spans += list(current_lane.get('transition_source_qualified_spans') or [])
|
||||
source_spans += list(current_lane.get('post_transition_source_qualified_spans') or [])
|
||||
source_recovery = any(source_span_verified(current_lane, span)
|
||||
and span.get('usable_for_control') is True
|
||||
for span in source_spans)
|
||||
if source_recovery:
|
||||
qualified = list(world)
|
||||
qualified_ids = list(selected)
|
||||
membership = True
|
||||
if membership and len(qualified)>=2:
|
||||
world=qualified; selected=qualified_ids
|
||||
local=np.asarray(world,float)-position
|
||||
self._transition_entry_lane = transition_entry_lane
|
||||
qualified_coverage=sum(float(np.linalg.norm((np.asarray(b)-a)[[0,2]])) for a,b in zip(world,world[1:])) if membership else None
|
||||
local = np.column_stack((local[:, [0, 2]]@forward,
|
||||
-local[:, 0]*forward[1]+local[:, 2]*forward[0],
|
||||
-local[:, 1]))
|
||||
# Preserve authored traversal order through sharp bends. The legacy
|
||||
# projection below remains available to model callers, but native
|
||||
# consumers use this bounded distance-parameterized trajectory.
|
||||
ordered=[local[0]]
|
||||
lengths=[0.]
|
||||
for point in local[1:]:
|
||||
segment=float(np.linalg.norm((point-ordered[-1])[:2]))
|
||||
if segment<=1e-5:continue
|
||||
remaining=self.MAX_PATH_M-lengths[-1]
|
||||
if remaining<=1e-5:break
|
||||
ordered.append(ordered[-1]+(point-ordered[-1])*min(1.,remaining/segment))
|
||||
lengths.append(lengths[-1]+min(segment,remaining))
|
||||
ordered=np.asarray(ordered)
|
||||
traversal=None
|
||||
if len(ordered)>=2:
|
||||
samples=np.linspace(0.,lengths[-1],min(256,max(33,int(lengths[-1]/.75)+1)))
|
||||
sampled=np.column_stack([np.interp(samples,lengths,ordered[:,i]) for i in range(3)])
|
||||
arc=np.r_[0.,np.cumsum(np.linalg.norm(np.diff(sampled[:,:2],axis=0),axis=1))]
|
||||
traversal=dict(s=arc.tolist(),**{k:sampled[:,i].tolist() for i,k in enumerate(('x','y','z'))})
|
||||
# Native path is a directed traversal. Never sort a bend into a fake
|
||||
# straight road; publish only its monotonic forward prefix.
|
||||
prefix = [local[0]]
|
||||
for point in local[1:]:
|
||||
if point[0] <= prefix[-1][0]+1e-4:
|
||||
if np.linalg.norm(point-prefix[-1]) < 1e-5:
|
||||
continue
|
||||
break
|
||||
prefix.append(point)
|
||||
if point[0] >= self.MAX_PATH_M:
|
||||
break
|
||||
local = np.asarray(prefix)
|
||||
# The legacy model path is a forward-only projection. At a sharp
|
||||
# authored bend its x projection can become shorter than three metres
|
||||
# even though the ordered native traversal still has ample arc length.
|
||||
# Native control must follow that ordered traversal instead of dropping
|
||||
# a centered truck at the bend. Keep the legacy projection when it has
|
||||
# useful coverage, and publish a bounded two-point fallback otherwise;
|
||||
# the native controller consumes traversal_path and never extrapolates.
|
||||
legacy_valid = len(local) >= 2 and local[-1, 0] >= 3. and local[0, 0] >= -5.
|
||||
traversal_extent = float(lengths[-1]) if len(lengths) else 0.
|
||||
if len(local) < 2 or local[0, 0] < -5. or traversal_extent < 3.:
|
||||
return empty('Native route path lacks current forward coverage')
|
||||
if legacy_valid:
|
||||
x = np.linspace(max(0., float(local[0, 0])), min(self.MAX_PATH_M, float(local[-1, 0])), 33)
|
||||
path = dict(x=x.tolist(), y=np.interp(x, local[:, 0], local[:, 1]).tolist(),
|
||||
z=np.interp(x, local[:, 0], local[:, 2]).tolist())
|
||||
else:
|
||||
# This is display/backward-compatibility geometry only. It is not
|
||||
# promoted to the control path and deliberately contains no
|
||||
# straight-line extension through the bend.
|
||||
path = dict(x=[float(local[0, 0]), float(local[-1, 0])],
|
||||
y=[float(local[0, 1]), float(local[-1, 1])],
|
||||
z=[float(local[0, 2]), float(local[-1, 2])])
|
||||
eligible = membership and bool(qualified_ids) and traversal_extent >= 3.
|
||||
reason=''
|
||||
delta=position-association_hit['projection']
|
||||
lateral=float(-delta[0]*forward[1]+delta[2]*forward[0])
|
||||
if not eligible:
|
||||
if association_hit['error_m']>1.75:
|
||||
reason=f'Truck is {abs(lateral)*3.280839895:.1f} ft '+('right' if lateral>0. else 'left')+' of GPS lane center; center in lane'
|
||||
elif association_hit['height_error_m']>self.MAX_CONTROL_HEIGHT_ERROR_M:
|
||||
reason='Truck height does not match the native GPS lane'
|
||||
elif association_hit['heading_dot']<.97:
|
||||
reason='Align the truck with the native GPS lane direction'
|
||||
else:
|
||||
reason=lanes[lane_id].get('source_qualification_reason') or 'Native interpolation/membership awaiting validation'
|
||||
return dict(available=True, reason=reason,
|
||||
sampled_at=now, age_s=0., usable_for_control=eligible,
|
||||
selected_lane_ids=selected, path=path, traversal_path=traversal, source='ATS directed native lane graph',
|
||||
route_revision=revision, lane_membership_verified=eligible,
|
||||
clearance_verified=False, intersection_priority_verified=False,
|
||||
association=dict(distance_to_center_m=association_hit['error_m'],
|
||||
ego_lateral_right_m=lateral,height_error_m=association_hit['height_error_m'],
|
||||
profile_transition_active=bool(hit.get('profile_source_id')),
|
||||
lane_change_envelope=maneuver_hit is not None and lane_id in maneuver_ids,
|
||||
heading_dot=association_hit['heading_dot'], retained_lane=retained is not None),
|
||||
continuation='qualified-span-end' if eligible and qualification_truncated else continuation,
|
||||
forward_coverage_m=traversal_extent, qualified_lane_ids=qualified_ids,
|
||||
qualified_coverage_m=qualified_coverage,
|
||||
source_geometry_fallback=bool(source_recovery),
|
||||
source_geometry_opt_in=self.allow_source_geometry,
|
||||
trip_plan=dict(state=trip.get('state'), complete=trip.get('complete'),
|
||||
gps_edge_count=trip.get('gps_edge_count'), planned_edge_count=trip.get('planned_edge_count'),
|
||||
unresolved_segments=len(trip.get('issues') or []), artifact_path=trip.get('artifact_path')) if trip else None,
|
||||
trip_edge_index=initial_route_index, route_lane_change=lane_change,
|
||||
gps_lane_preparation_pending=lane_change is not None or continuation == 'gps-lane-change-required',
|
||||
governed_curves=[dict(prefab_uid=lanes[key].get('prefab_uid'), lane_id=key, **curve)
|
||||
for key in selected for curve in lanes[key].get('curves', [])])
|
||||
@@ -0,0 +1,256 @@
|
||||
"""Route-specific light restrictions from authored stop points and live phases.
|
||||
|
||||
This planner never infers a stop line from a lamp's position. A green phase
|
||||
removes a light restriction; it does not prove intersection right of way or
|
||||
clearance. No actuator commands or remembered green phases are produced here.
|
||||
"""
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
|
||||
from telemetry.driving_scene import number
|
||||
from telemetry.native_signals import PHASES
|
||||
from control.native_path import ordered_path
|
||||
|
||||
|
||||
def unknown(reason, now):
|
||||
return dict(available=False, reason=reason, sampled_at=now, age_s=0.,
|
||||
state='unknown', phase=None, stop_distance_m=None,
|
||||
stop_required=None, usable_for_control=False,
|
||||
proceed_authorized=False, intersection_priority_verified=False,
|
||||
full_stop_line_span_verified=False, passed_stop_points=[],
|
||||
source='ATS route-specific native signals')
|
||||
|
||||
|
||||
def fresh(payload, now, limit):
|
||||
stamp, age = number(payload.get('sampled_at')), number(payload.get('age_s', 0.))
|
||||
return (payload.get('available') is True and stamp is not None and age is not None
|
||||
and 0. <= age <= limit and -.05 <= now-stamp <= limit)
|
||||
|
||||
|
||||
def xyz(value):
|
||||
if not isinstance(value, (tuple, list)) or len(value) != 3 or any(number(v) is None for v in value):
|
||||
raise ValueError('Finite three-dimensional coordinates required')
|
||||
return np.asarray(value, float)
|
||||
|
||||
|
||||
def projection(point, path):
|
||||
"""Nearest projection and directed distance, without extending a path."""
|
||||
lengths = np.linalg.norm(np.diff(path[:, :2], axis=0), axis=1)
|
||||
cumulative = np.r_[0., np.cumsum(lengths)]
|
||||
best = None
|
||||
for i, (a, b) in enumerate(zip(path, path[1:])):
|
||||
if lengths[i] < 1e-6:
|
||||
continue
|
||||
direction = b-a
|
||||
t = float(np.clip(np.dot((point-a)[:2], direction[:2])/lengths[i]**2, 0., 1.))
|
||||
hit = a+t*direction
|
||||
error, height = float(np.linalg.norm((hit-point)[:2])), abs(float(hit[2]-point[2]))
|
||||
candidate = dict(error=error, height=height, distance=float(cumulative[i]+t*lengths[i]),
|
||||
heading=direction[:2]/lengths[i])
|
||||
if best is None or error+height < best['error']+best['height']:
|
||||
best = candidate
|
||||
return best
|
||||
|
||||
|
||||
class NativeSignalPlanner:
|
||||
"""Stateless assessment: every result belongs to this pose and route revision."""
|
||||
def reset(self):
|
||||
pass
|
||||
|
||||
def assess(self, scene, native_plan=None):
|
||||
now = number(scene.get('sampled_at'))
|
||||
if now is None:
|
||||
raise ValueError('Finite scene time required')
|
||||
empty = lambda reason: unknown(reason, now)
|
||||
if native_plan is None:
|
||||
native_plan = scene.get('native_plan')
|
||||
if scene.get('sdk_fresh') is not True:
|
||||
return empty('Fresh SDK pose required for signal planning')
|
||||
sources = scene.get('sources') or {}
|
||||
for key, limit in (('signals', .3), ('route', .5), ('lane_graph', .5)):
|
||||
source = sources.get(key) or {}
|
||||
if source.get('fresh') is not True or not fresh(source.get('data') or {}, now, limit):
|
||||
return empty('Fresh '+key+' source required for signal planning')
|
||||
if not isinstance(native_plan, dict) or not fresh(native_plan, now, .35):
|
||||
return empty('Fresh selected native route path required')
|
||||
route = sources['route']['data']
|
||||
revision = route.get('route_revision') or route.get('revision')
|
||||
if (revision is None or native_plan.get('route_revision') != revision
|
||||
or route.get('lead_in') is not None or route.get('display_only')):
|
||||
return empty('Selected path does not match the current GPS route revision')
|
||||
report = sources['signals']['data']
|
||||
try:
|
||||
sdk = scene['sdk']
|
||||
if sdk.get('position_valid') is not True:
|
||||
raise ValueError('Valid SDK position required')
|
||||
position, rotation = xyz(sdk['world_position']), xyz(sdk['world_rotation'])
|
||||
yaw = rotation[0]*2*math.pi
|
||||
forward = np.array([-math.sin(yaw), -math.cos(yaw)])
|
||||
def local(point):
|
||||
delta = xyz(point)-position
|
||||
return np.array([delta[[0, 2]]@forward,
|
||||
-delta[0]*forward[1]+delta[2]*forward[0], -delta[1]])
|
||||
path = ordered_path(native_plan)
|
||||
origin = projection(np.zeros(3), path)
|
||||
if origin is None or origin['error'] > 3. or origin['height'] > 1.:
|
||||
raise ValueError('Native path is not associated with the truck pose')
|
||||
selected = native_plan['selected_lane_ids']
|
||||
curves = native_plan['governed_curves']
|
||||
if (not isinstance(selected, list) or not 1 <= len(selected) <= 16
|
||||
or any(not isinstance(v, str) for v in selected) or len(set(selected)) != len(selected)
|
||||
or not isinstance(curves, list) or len(curves) > 4096):
|
||||
raise ValueError('Bounded selected native lanes and ordered curves required')
|
||||
signals, stops = report.get('signals', []), report.get('authored_stop_points', [])
|
||||
if not isinstance(signals, list) or len(signals) > 2048 or not isinstance(stops, list) or len(stops) > 10000:
|
||||
raise ValueError('Bounded signal and authored stop point evidence required')
|
||||
lanes = {lane['id']: lane for lane in sources['lane_graph']['data']['lanes']}
|
||||
if any(key not in lanes for key in selected):
|
||||
raise ValueError('Selected route lane is absent from the current graph')
|
||||
except (KeyError, TypeError, ValueError, OverflowError) as exc:
|
||||
return empty(str(exc))
|
||||
|
||||
candidates, rejected = [], []
|
||||
for lane_id in selected:
|
||||
lane = lanes[lane_id]
|
||||
if lane.get('kind') != 'prefab':
|
||||
continue
|
||||
ordered = [c for c in curves if c.get('lane_id') == lane_id]
|
||||
authored = lane.get('curves', [])
|
||||
# Do not accept rearranged, truncated or stale curve sequences.
|
||||
if len(ordered) != len(authored) or any(any(a.get(k) != b.get(k) for k in
|
||||
('curve_index', 'start', 'end', 'semaphore_id', 'traffic_rule'))
|
||||
for a, b in zip(ordered, authored)):
|
||||
rejected.append('Selected curve order differs from authored lane'); continue
|
||||
for index, curve in enumerate(ordered):
|
||||
if curve.get('traffic_rule') not in ('cross_line', 'cross_line_s'):
|
||||
continue
|
||||
try:
|
||||
uid = lane['prefab_uid']
|
||||
if any(c.get('prefab_uid') != uid for c in ordered):
|
||||
raise ValueError('Prefab identity differs on selected route')
|
||||
point = next((p for p in stops if p.get('prefab_uid') == uid
|
||||
and p.get('curve_index') == curve['curve_index'] and lane_id in p.get('lane_ids', [])), None)
|
||||
if (point is None or point.get('position_verified') is not True
|
||||
or point.get('rule_definition_verified') is not True
|
||||
or report.get('traffic_rule_definition', {}).get('verified') is not True
|
||||
or point.get('traffic_rule') != curve['traffic_rule']
|
||||
or np.linalg.norm(xyz(point['position'])-xyz(curve['start'])) > 1e-5):
|
||||
raise ValueError('Verified authored stop point required')
|
||||
stop_local = local(point['position'])
|
||||
hit = projection(stop_local, path)
|
||||
heading = (local(curve['end'])-stop_local)[:2]
|
||||
heading_norm = np.linalg.norm(heading)
|
||||
if (hit is None or hit['error'] > .6 or hit['height'] > .3 or heading_norm < .1
|
||||
or float(heading@hit['heading']/heading_norm) < .7):
|
||||
raise ValueError('Stop point is not on the forward selected lane')
|
||||
distance = hit['distance']-origin['distance']
|
||||
if (distance < -.5 or hit['distance'] <= .05
|
||||
and float((stop_local[:2]-path[0,:2])@hit['heading']) < -.5):
|
||||
raise ValueError('Authored stop point already behind the truck')
|
||||
# The first semaphore in the uninterrupted authored approach
|
||||
# governs this point. Never skip it to borrow a later lamp.
|
||||
governor, chain, chain_length = None, [], 0.
|
||||
for j in range(index, len(ordered)):
|
||||
c = ordered[j]
|
||||
if j > index:
|
||||
if c.get('traffic_rule') in ('cross_line', 'cross_line_s', 'cross_end'):
|
||||
break
|
||||
if np.linalg.norm(xyz(ordered[j-1]['end'])-xyz(c['start'])) > .05:
|
||||
raise ValueError('Authored stop approach is discontinuous')
|
||||
chain.append(c['curve_index'])
|
||||
chain_length += float(np.linalg.norm(xyz(c['end'])-xyz(c['start'])))
|
||||
if chain_length > 100.:
|
||||
raise ValueError('Semaphore exceeds bounded authored approach')
|
||||
semaphore = c.get('semaphore_id')
|
||||
if type(semaphore) is int and semaphore >= 0:
|
||||
governor = c; break
|
||||
if governor is None:
|
||||
raise ValueError('No semaphore governs this authored stop approach')
|
||||
matching = [s for s in signals if s.get('prefab_uid') == uid
|
||||
and s.get('semaphore_id') == governor['semaphore_id']]
|
||||
signal = matching[0] if len(matching) == 1 else None
|
||||
evidence = None if signal is None else next((c for c in signal.get('governed_curves', [])
|
||||
if c.get('curve_index') == governor['curve_index']), None)
|
||||
verified = bool(signal is not None and signal.get('live_phase_verified') is True
|
||||
and PHASES.get(signal.get('phase_code')) == signal.get('phase')
|
||||
and evidence is not None and evidence.get('placement_verified') is True
|
||||
and np.linalg.norm(xyz(evidence.get('start'))-xyz(governor['start'])) <= 1e-5)
|
||||
candidates.append(dict(distance=distance, point=point, governor=governor,
|
||||
signal=signal, phase_verified=verified, lane_id=lane_id,
|
||||
chain=chain, error_m=hit['error'], heading_dot=float(heading@hit['heading']/heading_norm)))
|
||||
except (KeyError, TypeError, ValueError, OverflowError) as exc:
|
||||
rejected.append(str(exc))
|
||||
traffic_source = sources.get('traffic') or {}
|
||||
traffic = traffic_source.get('data') or {}
|
||||
front = number(traffic.get('own_front_extent_m'))
|
||||
front_verified = (traffic_source.get('fresh') is True and fresh(traffic, now, .3)
|
||||
and traffic.get('ego_geometry_available') is True
|
||||
and front is not None and .05 <= front <= 30.)
|
||||
def evidence(candidate):
|
||||
point, signal, governor = candidate['point'], candidate['signal'], candidate['governor']
|
||||
verified = candidate['phase_verified']
|
||||
return dict(unknown('', now), available=verified,
|
||||
phase=signal.get('phase') if verified else None,
|
||||
phase_code=signal.get('phase_code') if verified else None,
|
||||
route_revision=revision, selected_lane_id=candidate['lane_id'],
|
||||
stop_point=point,
|
||||
stop_distance_m=candidate['distance']-front if front_verified else None,
|
||||
reference_distance_m=candidate['distance'],
|
||||
own_front_extent_m=front if front_verified else None,
|
||||
front_geometry_verified=front_verified, signal_phase_verified=verified,
|
||||
association=dict(prefab_uid=point['prefab_uid'], semaphore_id=governor['semaphore_id'],
|
||||
stop_curve_index=point['curve_index'], governed_curve_index=governor['curve_index'],
|
||||
ordered_curve_chain=candidate['chain'], lane_id=candidate['lane_id'],
|
||||
path_error_m=candidate['error_m'], heading_dot=candidate['heading_dot'],
|
||||
native_rule_id=signal.get('native_rule_id') if signal else None,
|
||||
source='Exact prefab UID, first semaphore and selected authored curve chain'),
|
||||
phase_sampled_at=report['sampled_at'])
|
||||
|
||||
# Keep exact current evidence for a controller already holding this
|
||||
# intersection after a small bumper overshoot. This is not a new stop
|
||||
# or an entry grant: the main result still ignores crossed points, so
|
||||
# a lawful crossing is not newly stopped when its lamp changes behind
|
||||
# the bumper. A retained hold can revalidate its own exact semaphore
|
||||
# and separately ask the crossing planner for observed clearance.
|
||||
passed = [dict(evidence(c), passed_by_front=True,
|
||||
reason='Front passed stop point; only a retained stop may reuse this evidence')
|
||||
for c in sorted(candidates, key=lambda c: c['distance'], reverse=True)
|
||||
if front_verified and -10. <= c['distance']-front < -.75][:8]
|
||||
# Once the front has crossed a point, never brake for it again while
|
||||
# continuing through the intersection. A small standstill tolerance
|
||||
# allows measured box/pose jitter at the actual stopping point.
|
||||
candidates = [c for c in candidates if not front_verified or c['distance']-front >= -.75]
|
||||
if not candidates:
|
||||
result = empty('No upcoming verified route-specific signal stop point')
|
||||
result['rejected_associations'] = rejected[:16]
|
||||
result['passed_stop_points'] = passed
|
||||
return result
|
||||
chosen = min(candidates, key=lambda c: c['distance'])
|
||||
point, signal, governor = chosen['point'], chosen['signal'], chosen['governor']
|
||||
phase = signal.get('phase') if chosen['phase_verified'] else None
|
||||
speed = number(sdk.get('speed_mps'))
|
||||
gap = chosen['distance']-front if front_verified else None
|
||||
result = dict(evidence(chosen), rejected_associations=rejected[:16], passed_stop_points=passed)
|
||||
if phase == 'yellow-to-red' and speed is not None and speed >= 0. and gap is not None:
|
||||
result['yellow_assessment'] = dict(comfortable_deceleration_mps2=2., reaction_time_s=.3,
|
||||
stopping_distance_m=speed*.3+speed*speed/4., stop_feasible=gap >= speed*.3+speed*speed/4.,
|
||||
crossing_permission_verified=False)
|
||||
if not chosen['phase_verified']:
|
||||
result['reason'] = 'Selected approach semaphore has no verified live phase'
|
||||
elif not front_verified or speed is None or speed < 0.:
|
||||
result['reason'] = 'Fresh native front extent and forward speed required'
|
||||
elif point['traffic_rule'] == 'cross_line_s' or phase in ('red', 'yellow-to-green') or (phase == 'yellow-to-red'
|
||||
and gap >= speed*.3+speed*speed/4.):
|
||||
result.update(state='hold' if speed <= .3 and gap <= 1.5 else 'stop', stop_required=True,
|
||||
usable_for_control=(native_plan.get('usable_for_control') is True
|
||||
and native_plan.get('lane_membership_verified') is True))
|
||||
if point['traffic_rule'] == 'cross_line_s':
|
||||
result['reason'] = 'Authored unconditional stop; stop completion and crossing priority unverified'
|
||||
elif phase == 'green':
|
||||
result.update(state='proceed', stop_required=False,
|
||||
reason='Green phase; intersection priority and clearance remain unverified')
|
||||
else:
|
||||
result['reason'] = ('Yellow phase inside comfortable stopping distance; crossing decision unverified'
|
||||
if phase == 'yellow-to-red' else 'Signal phase does not establish right of way')
|
||||
return result
|
||||
@@ -0,0 +1,273 @@
|
||||
"""Compile a GPS trip against the full mounted directed lane graph.
|
||||
|
||||
Planning is independent of the local actuator horizon. Lane-change edges mean
|
||||
that a maneuver is needed; they never authorize a lateral jump or certify a
|
||||
traffic gap. The live maneuver planner still checks both before crossing.
|
||||
"""
|
||||
import heapq
|
||||
import math
|
||||
from collections import defaultdict
|
||||
|
||||
from control.native_route_planner import source_span_verified
|
||||
from telemetry.native_player_access import route_eligible
|
||||
|
||||
|
||||
def route_nodes(route):
|
||||
nodes = []
|
||||
for node in route.get('nodes', ()):
|
||||
if not nodes or str(nodes[-1]['uid']) != str(node['uid']):
|
||||
nodes.append(node)
|
||||
if not 2 <= len(nodes) <= 6000:
|
||||
raise ValueError('Bounded whole-trip GPS nodes required')
|
||||
return nodes
|
||||
|
||||
|
||||
def _length(lane):
|
||||
points = lane['centerline']
|
||||
return sum(math.hypot(b[0]-a[0], b[2]-a[2]) for a, b in zip(points, points[1:]))
|
||||
|
||||
|
||||
def _qualified(lane):
|
||||
spans = list(lane.get('validated_spans') or [])
|
||||
spans += [s for key in ('source_qualified_spans', 'transition_source_qualified_spans',
|
||||
'post_transition_source_qualified_spans')
|
||||
for s in lane.get(key, ()) if source_span_verified(lane, s)]
|
||||
return any(s.get('usable_for_control') is True
|
||||
and s.get('end_s_m', 0.) > s.get('start_s_m', math.inf)
|
||||
and (s.get('evidence_sha256') or s.get('geometry_sha256')) for s in spans)
|
||||
|
||||
|
||||
def _connections(lanes, edges):
|
||||
result = defaultdict(list)
|
||||
for edge in edges:
|
||||
a, b = edge.get('from_lane_id'), edge.get('to_lane_id')
|
||||
if a not in lanes or b not in lanes:
|
||||
continue
|
||||
source, target = lanes[a], lanes[b]
|
||||
gap = math.dist(source['centerline'][-1], target['centerline'][0])
|
||||
limit = 4.5 if edge.get('transition_kind') == 'road-profile' else .25
|
||||
if (str(source['end_node_uid']) == str(target['start_node_uid'])
|
||||
and gap <= limit and edge.get('heading_dot', 0.) >= .995
|
||||
and edge.get('height_error_m', math.inf) <= .1):
|
||||
result[a].append(b)
|
||||
return result
|
||||
|
||||
|
||||
def _lateral(lanes, permissions):
|
||||
result = defaultdict(list)
|
||||
if permissions.get('available') is not True:
|
||||
return result
|
||||
for boundary in permissions.get('boundaries', ()):
|
||||
a, b = boundary.get('inner_lane_id'), boundary.get('outer_lane_id')
|
||||
if a not in lanes or b not in lanes:
|
||||
continue
|
||||
if (boundary.get('status') != 'allowed' or boundary.get('same_direction') is not True
|
||||
or boundary.get('definition_only') is not True or boundary.get('clearance_verified')):
|
||||
continue
|
||||
x, y = lanes[a], lanes[b]
|
||||
key = lambda l: (l.get('road_uid'), l.get('travel_direction'),
|
||||
str(l['start_node_uid']), str(l['end_node_uid']))
|
||||
if x.get('kind') != 'road' or y.get('kind') != 'road' or key(x) != key(y):
|
||||
continue
|
||||
# A short connector cannot hold a truck lane-change trajectory.
|
||||
if min(_length(x), _length(y)) < 50.:
|
||||
continue
|
||||
result[a].append(b)
|
||||
result[b].append(a)
|
||||
return result
|
||||
|
||||
|
||||
def _alternative(start, end, lanes, successors, lateral, groups, lengths, max_distance):
|
||||
"""Find an authored truck detour between the same GPS endpoints."""
|
||||
queue, cost, parent = [], {}, {}
|
||||
for key in groups.get(start, ()):
|
||||
cost[key] = lengths[key]
|
||||
heapq.heappush(queue, (cost[key], key))
|
||||
visits = 0
|
||||
while queue and visits < 10000:
|
||||
value, key = heapq.heappop(queue)
|
||||
if value != cost.get(key) or value > max_distance:
|
||||
continue
|
||||
visits += 1
|
||||
if str(lanes[key]['end_node_uid']) == end:
|
||||
path = [key]
|
||||
while key in parent:
|
||||
key = parent[key]
|
||||
path.append(key)
|
||||
path.reverse()
|
||||
# Lateral edges are represented by the later backward lane policy,
|
||||
# not duplicate GPS nodes. Preserve every real directed road pair.
|
||||
pairs = []
|
||||
for key in path:
|
||||
lane = lanes[key]
|
||||
pair = (str(lane['start_node_uid']), str(lane['end_node_uid']))
|
||||
if not pairs or pairs[-1] != pair:
|
||||
pairs.append(pair)
|
||||
return pairs
|
||||
for target in tuple(successors.get(key, ())) + tuple(lateral.get(key, ())):
|
||||
extra = 100. if target in lateral.get(key, ()) else lengths[target]
|
||||
trial = value+extra
|
||||
if trial < cost.get(target, math.inf) and trial <= max_distance:
|
||||
cost[target], parent[target] = trial, key
|
||||
heapq.heappush(queue, (trial, target))
|
||||
return None
|
||||
|
||||
|
||||
def compile_trip(route, graph, *, cache_sha256, permissions=None):
|
||||
"""Return a complete lane policy, or explicit gaps, for every GPS edge."""
|
||||
revision = route.get('route_revision') or route.get('revision')
|
||||
nodes = route_nodes(route)
|
||||
if not revision or graph.get('source_verified') is not True:
|
||||
raise ValueError('Verified mounted graph and GPS revision required')
|
||||
all_lanes = {l['id']: l for l in graph['lanes']}
|
||||
original = [(str(a['uid']), str(b['uid'])) for a,b in zip(nodes, nodes[1:])]
|
||||
gps_pairs = set(original)
|
||||
lanes = {k:l for k,l in all_lanes.items()
|
||||
if route_eligible(l, gps_pairs) and _qualified(l)}
|
||||
lengths = {k:_length(l) for k,l in lanes.items()}
|
||||
routing_cost = {k:distance+(250. if lanes[k].get('large_vehicle_suitable') is False else 0.)
|
||||
for k,distance in lengths.items()}
|
||||
successors = _connections(lanes, graph.get('connections', ()))
|
||||
lateral = _lateral(lanes, permissions or {})
|
||||
by_pair, raw_pair = defaultdict(list), defaultdict(list)
|
||||
for key, lane in all_lanes.items():
|
||||
pair = (str(lane['start_node_uid']), str(lane['end_node_uid']))
|
||||
raw_pair[pair].append(key)
|
||||
if key in lanes:
|
||||
by_pair[pair].append(key)
|
||||
# NPC curves may continue through player-inaccessible scenery. Only use
|
||||
# off-GPS alternatives with positive player-access evidence; geometry and
|
||||
# AI truck preferences alone do not establish passage through yellow Xs.
|
||||
detour_lanes = {k:l for k,l in lanes.items() if l.get('player_truck_access') is True
|
||||
and l.get('large_vehicle_suitable') is not False}
|
||||
detour_successors = _connections(detour_lanes, graph.get('connections', ()))
|
||||
detour_lateral = _lateral(detour_lanes, permissions or {})
|
||||
detour_groups = defaultdict(list)
|
||||
for key, lane in detour_lanes.items():
|
||||
detour_groups[str(lane['start_node_uid'])].append(key)
|
||||
pairs, origins, detours, issues = [], [], [], []
|
||||
for index, pair in enumerate(original):
|
||||
replacement = None
|
||||
if not by_pair[pair] and raw_pair[pair]:
|
||||
distance = max((_length(all_lanes[k]) for k in raw_pair[pair]), default=0.)
|
||||
replacement = _alternative(*pair, detour_lanes, detour_successors, detour_lateral, detour_groups, lengths,
|
||||
max_distance=min(15000., max(10000., distance*6.)))
|
||||
if replacement:
|
||||
detours.append(dict(gps_edge_index=index, original_pair=list(pair),
|
||||
directed_pairs=[list(p) for p in replacement],
|
||||
reason='Truck-compatible authored alternative'))
|
||||
for p in replacement or [pair]:
|
||||
pairs.append(p)
|
||||
if len(pairs) > 12000:
|
||||
raise ValueError('Whole trip exceeds the bounded 12000 directed segments')
|
||||
origins.append(index)
|
||||
if not by_pair[p]:
|
||||
reason = ('missing-geometry' if not raw_pair[p] else
|
||||
'player-inaccessible' if all(all_lanes[k].get('player_truck_access') is False
|
||||
for k in raw_pair[p]) else
|
||||
'truck-restricted' if all(all_lanes[k].get('large_vehicle_suitable') is False
|
||||
for k in raw_pair[p]) else 'unqualified-geometry')
|
||||
issues.append(dict(edge_index=len(pairs)-1, gps_edge_index=index,
|
||||
node_pair=list(p), reason=reason))
|
||||
|
||||
# Work backwards from destination. Every input lane learns which exit
|
||||
# remains reachable several junctions later, rather than picking locally.
|
||||
policies = [{} for _ in pairs]
|
||||
costs, downstream_complete = {}, True
|
||||
for index in range(len(pairs)-1, -1, -1):
|
||||
keys = sorted(by_pair[pairs[index]])
|
||||
here, choices = {}, {}
|
||||
if index == len(pairs)-1 or not costs:
|
||||
for key in keys:
|
||||
here[key] = routing_cost[key]
|
||||
choices[key] = dict(kind='destination' if index == len(pairs)-1 else 'coverage-end',
|
||||
next_lane_id=None, reaches_destination=downstream_complete)
|
||||
else:
|
||||
for key in keys:
|
||||
options = [target for target in successors.get(key, ()) if target in costs]
|
||||
if options:
|
||||
# Authored optional same-exit lane shifts carry a cost;
|
||||
# still select one when needed for a later GPS junction.
|
||||
penalty = lambda t: 20. if (lanes[t].get('kind') == 'prefab'
|
||||
and lanes[t].get('input_lane_index') != lanes[t].get('output_lane_index')) else 0.
|
||||
target = min(options, key=lambda t:(costs[t]+penalty(t), t))
|
||||
here[key] = routing_cost[key]+costs[target]+penalty(target)
|
||||
choices[key] = dict(kind='continue', next_lane_id=target,
|
||||
reaches_destination=downstream_complete)
|
||||
queue = [(v,k) for k,v in here.items()]
|
||||
heapq.heapify(queue)
|
||||
while queue:
|
||||
value, target = heapq.heappop(queue)
|
||||
if value != here[target]:
|
||||
continue
|
||||
for key in lateral.get(target, ()):
|
||||
if key not in keys:
|
||||
continue
|
||||
trial, previous = value+100., here.get(key, math.inf)
|
||||
# Equal total maneuver cost should prepare on this long
|
||||
# road now, rather than defer the same change to the last
|
||||
# short connector before the exit. A strict cost-only tie
|
||||
# otherwise postpones every necessary lane change.
|
||||
earlier = (trial == previous and choices[key]['kind'] == 'continue'
|
||||
and choices[target]['kind'] != 'lane-change')
|
||||
if trial > previous or trial == previous and not earlier:
|
||||
continue
|
||||
here[key] = trial
|
||||
choices[key] = dict(kind='lane-change', next_lane_id=target,
|
||||
reaches_destination=downstream_complete)
|
||||
heapq.heappush(queue, (here[key], key))
|
||||
if keys and not here:
|
||||
issues.append(dict(edge_index=index, gps_edge_index=origins[index],
|
||||
node_pair=list(pairs[index]), reason='lane-connection-gap'))
|
||||
downstream_complete = False
|
||||
for key in keys:
|
||||
here[key] = routing_cost[key]
|
||||
choices[key] = dict(kind='coverage-end', next_lane_id=None,
|
||||
reaches_destination=False)
|
||||
if not keys:
|
||||
downstream_complete = False
|
||||
for key, choice in choices.items():
|
||||
choice['cost_to_region_end_m'] = here[key]
|
||||
policies[index] = choices
|
||||
costs = here
|
||||
|
||||
selected = []
|
||||
maneuvers = [dict(edge_index=i, gps_edge_index=origins[i], from_lane_id=key,
|
||||
to_lane_id=choice['next_lane_id'], reason='Required lane for upcoming GPS exit')
|
||||
for i, policy in enumerate(policies) for key,choice in policy.items()
|
||||
if choice['kind'] == 'lane-change']
|
||||
current = min(costs, key=lambda k:(costs[k], k)) if costs else None
|
||||
index, seen = 0, set()
|
||||
while current is not None and (index, current) not in seen:
|
||||
seen.add((index, current))
|
||||
selected.append(dict(edge_index=index, lane_id=current))
|
||||
choice = policies[index].get(current) or {}
|
||||
target = choice.get('next_lane_id')
|
||||
if choice.get('kind') != 'lane-change' and target is not None:
|
||||
index += 1
|
||||
current = target
|
||||
issues.sort(key=lambda issue:issue['edge_index'])
|
||||
positions = {str(n['uid']):n.get('position') for n in nodes if n.get('position') is not None}
|
||||
for a,b in pairs:
|
||||
keys = by_pair[(a,b)] or raw_pair[(a,b)]
|
||||
if keys:
|
||||
line = all_lanes[keys[0]]['centerline']
|
||||
positions.setdefault(a, line[0])
|
||||
positions.setdefault(b, line[-1])
|
||||
display_uids = [pairs[0][0]]+[b for a,b in pairs]
|
||||
map_nodes = [dict(uid=uid,position=positions[uid]) for uid in display_uids if uid in positions]
|
||||
return dict(schema_version=1, available=True, state='ready' if not issues else 'gaps',
|
||||
reason='' if not issues else 'GPS trip has '+str(len(issues))+' unresolved segments',
|
||||
route_revision=revision, graph_sha256=cache_sha256,
|
||||
source_verified=True, complete=not issues,
|
||||
gps_edge_count=len(original), planned_edge_count=len(pairs),
|
||||
directed_pairs=[list(p) for p in pairs], gps_edge_indices=origins,
|
||||
lane_policy=policies, selected_lane_chain=selected,
|
||||
required_lane_changes=maneuvers, truck_detours=detours, issues=issues,
|
||||
player_access_policy=dict(npc_preferences_are_access_restrictions=False,
|
||||
preference_fallback_scope='Actual game GPS node pairs only',
|
||||
off_gps_detours_require_player_access=True,
|
||||
invisible_collision_coverage_complete=False),
|
||||
map_nodes=map_nodes if len(map_nodes) == len(display_uids) else [],
|
||||
traffic_clearance_verified=False, control_authorized=False,
|
||||
source='Whole GPS trip over mounted ATS directed lanes')
|
||||
@@ -0,0 +1,204 @@
|
||||
"""Route execution state for the experimental ATS Navigate-on-Autopilot HUD.
|
||||
|
||||
The native GPS graph tells us which directed road pair is next. This module
|
||||
turns that evidence into a small, restartable state machine: it announces an
|
||||
approach, requests one turn signal pulse, and explicitly hands a junction to
|
||||
the driver when the map does not contain a verified lane and right-of-way
|
||||
solution. It has no actuator access. Steering remains owned by the current
|
||||
Pop path and all existing traffic, focus, and camera gates remain in force.
|
||||
"""
|
||||
import math
|
||||
import numbers
|
||||
import time
|
||||
|
||||
|
||||
def _number(value):
|
||||
if isinstance(value, bool) or not isinstance(value, numbers.Real):
|
||||
return None
|
||||
value = float(value)
|
||||
return value if math.isfinite(value) else None
|
||||
|
||||
|
||||
class NavigateOnAutopilot:
|
||||
"""Keep route maneuvers coherent across noisy GPS/model frames."""
|
||||
|
||||
SIGNAL_APPROACH_M = 350.0
|
||||
MANUAL_JUNCTION_M = 45.0
|
||||
MAX_AGE_S = .6
|
||||
|
||||
def __init__(self, clock=time.monotonic):
|
||||
self.clock = clock
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self._revision = None
|
||||
self._bend_key = None
|
||||
self._signal_sent = False
|
||||
self._last_phase = 'route-uncertain'
|
||||
self._last_now = None
|
||||
|
||||
@staticmethod
|
||||
def _report(reason='', **extra):
|
||||
result = dict(
|
||||
enabled=True,
|
||||
available=False,
|
||||
phase='route-uncertain',
|
||||
reason=str(reason),
|
||||
route_revision=None,
|
||||
next_bend=None,
|
||||
requested_signal='none',
|
||||
signal_pulse='none',
|
||||
signal_active=False,
|
||||
automatic_signal=False,
|
||||
lane_change_request=None,
|
||||
automatic_lane_change=False,
|
||||
junction_execution='manual-required',
|
||||
reroute=False,
|
||||
path_override=None,
|
||||
speed_cap_mph=None,
|
||||
experimental=True,
|
||||
production_eligible=False,
|
||||
control_eligible=False,
|
||||
)
|
||||
result.update(extra)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _bend(preview):
|
||||
if not isinstance(preview, dict) or preview.get('available') is not True:
|
||||
return None, 'Fresh matched GPS preview required'
|
||||
bend = preview.get('next_bend')
|
||||
if bend is None:
|
||||
return None, ''
|
||||
if not isinstance(bend, dict):
|
||||
return None, 'Malformed next GPS bend'
|
||||
distance = _number(bend.get('distance_m'))
|
||||
angle = _number(bend.get('angle_deg'))
|
||||
direction = bend.get('direction')
|
||||
node = bend.get('node_index')
|
||||
if (distance is None or angle is None or distance < 0
|
||||
or direction not in ('left', 'right') or type(node) is not int or node < 1):
|
||||
return None, 'Malformed next GPS bend'
|
||||
if abs(angle) < 20 or abs(angle) > 180:
|
||||
return None, 'GPS bend angle outside supported range'
|
||||
if (angle < 0) != (direction == 'left'):
|
||||
return None, 'GPS bend direction/sign disagreement'
|
||||
return dict(direction=direction, distance_m=distance, angle_deg=angle,
|
||||
node_index=node, distance_units=bend.get('distance_units',
|
||||
'ATS advisor metres')), ''
|
||||
|
||||
@staticmethod
|
||||
def _signal_matches(telemetry, direction):
|
||||
if direction == 'left':
|
||||
return telemetry.get('blinker_left') is True and telemetry.get('blinker_right') is not True
|
||||
if direction == 'right':
|
||||
return telemetry.get('blinker_right') is True and telemetry.get('blinker_left') is not True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _lane_request(lane_choice, bend):
|
||||
"""Convert a future verified lane recommendation into a request.
|
||||
|
||||
Current lane-choice reports deliberately leave this unavailable for the
|
||||
Tesla Semi calibration. Keeping the conversion here makes the runtime
|
||||
ready for a verified map/corridor association without guessing a lane
|
||||
from a turn direction today.
|
||||
"""
|
||||
if not isinstance(lane_choice, dict) or lane_choice.get('route_lane_choice_available') is not True:
|
||||
return None
|
||||
if lane_choice.get('clear_lane_verified') is not True:
|
||||
return None
|
||||
current = lane_choice.get('current_slot')
|
||||
target = lane_choice.get('recommended_slot')
|
||||
if target is None or current is None or target == current:
|
||||
return None
|
||||
direction = lane_choice.get('recommended_direction')
|
||||
if direction not in ('left', 'right'):
|
||||
return None
|
||||
return dict(direction=direction, current_slot=current, target_slot=target,
|
||||
reason='Verified route lane recommendation and fresh clear-lane evidence')
|
||||
|
||||
def assess(self, route, preview, telemetry, *, base_navigation=None,
|
||||
lane_choice=None, junction_paths=None, now=None):
|
||||
now = _number(self.clock() if now is None else now)
|
||||
if now is None or (self._last_now is not None and now < self._last_now):
|
||||
self.reset()
|
||||
return self._report('Navigate-on-Autopilot clock unavailable or regressed')
|
||||
self._last_now = now
|
||||
if (not isinstance(telemetry, dict) or telemetry.get('valid') is not True
|
||||
or telemetry.get('paused') is not False
|
||||
or telemetry.get('navigation_valid') is not True):
|
||||
return self._report('Fresh unpaused GPS telemetry required')
|
||||
if not isinstance(route, dict) or route.get('available') is not True:
|
||||
return self._report(route.get('reason', 'Native GPS route unavailable')
|
||||
if isinstance(route, dict) else 'Native GPS route unavailable')
|
||||
sampled = _number(route.get('sampled_at'))
|
||||
if sampled is None or not -.05 <= now-sampled <= self.MAX_AGE_S:
|
||||
return self._report('Native GPS route is stale', route_revision=route.get('revision'))
|
||||
revision = route.get('revision')
|
||||
if not revision:
|
||||
return self._report('Native GPS route revision unavailable')
|
||||
reroute = self._revision is not None and revision != self._revision
|
||||
if reroute:
|
||||
# Never carry a signal, lane request, or junction path across a
|
||||
# changed destination/route array.
|
||||
self._bend_key = None
|
||||
self._signal_sent = False
|
||||
self._revision = revision
|
||||
bend, reason = self._bend(preview)
|
||||
if reason:
|
||||
return self._report(reason, route_revision=revision, reroute=reroute)
|
||||
base = base_navigation if isinstance(base_navigation, dict) else {}
|
||||
cap = _number(base.get('route_speed_cap_mph'))
|
||||
common = dict(route_revision=revision, reroute=reroute,
|
||||
speed_cap_mph=cap,
|
||||
route_navigation_phase=base.get('navigation_phase', 'route-cruise'))
|
||||
if bend is None:
|
||||
self._bend_key = None
|
||||
self._signal_sent = False
|
||||
report = self._report('', available=True, phase='route-cruise',
|
||||
next_bend=None, requested_signal='none',
|
||||
signal_active=False, automatic_signal=False,
|
||||
junction_execution='none', **common)
|
||||
self._last_phase = report['phase']
|
||||
return report
|
||||
bend_key = (revision, bend['node_index'], bend['direction'])
|
||||
if bend_key != self._bend_key:
|
||||
self._bend_key = bend_key
|
||||
self._signal_sent = False
|
||||
distance = bend['distance_m']
|
||||
lane_request = self._lane_request(lane_choice, bend)
|
||||
requested = bend['direction'] if distance <= self.SIGNAL_APPROACH_M else 'none'
|
||||
pulse = 'none'
|
||||
if (requested != 'none' and telemetry.get('gameplay_engaged') is True
|
||||
and not self._signal_sent and not self._signal_matches(telemetry, requested)):
|
||||
pulse = requested
|
||||
self._signal_sent = True
|
||||
if distance <= self.MANUAL_JUNCTION_M:
|
||||
phase = 'junction'
|
||||
# Authored prefab paths are display-only until lane boundaries,
|
||||
# signals and right-of-way are verified. A future verified report
|
||||
# can supply a path without changing this state-machine contract.
|
||||
verified_paths = (isinstance(junction_paths, dict)
|
||||
and junction_paths.get('usable_for_control') is True
|
||||
and junction_paths.get('complete_coverage') is True
|
||||
and junction_paths.get('traffic_rules_verified') is True)
|
||||
junction_execution = 'authored-path' if verified_paths else 'manual-required'
|
||||
if junction_execution == 'manual-required':
|
||||
lane_request = None
|
||||
elif lane_request is not None:
|
||||
phase = 'prepare-lane'
|
||||
junction_execution = 'lane-change-requested'
|
||||
else:
|
||||
phase = 'signal-approach' if requested != 'none' else 'route-cruise'
|
||||
junction_execution = 'none'
|
||||
report = self._report('', available=True, phase=phase, next_bend=bend,
|
||||
requested_signal=requested, signal_pulse=pulse,
|
||||
signal_active=requested != 'none',
|
||||
automatic_signal=requested != 'none',
|
||||
lane_change_request=lane_request,
|
||||
automatic_lane_change=lane_request is not None,
|
||||
junction_execution=junction_execution, **common)
|
||||
self._last_phase = phase
|
||||
return report
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Bounded GPS-assisted camera trajectory selection for an ATS trial.
|
||||
|
||||
The GPS graph selects a direction; it is never a steering centerline. This
|
||||
planner has no actuator APIs and does not establish intersection right-of-way.
|
||||
"""
|
||||
import math
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
|
||||
from control.path_preview import path_reason
|
||||
|
||||
|
||||
class NavigationDriver:
|
||||
MAX_SPEED_MPH = 15.0
|
||||
MAX_STEER = .25
|
||||
MAX_STEER_RATE = .25
|
||||
|
||||
def __init__(self, clock=time.monotonic):
|
||||
self.clock = clock
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.current_steer = 0.0
|
||||
self._last_time = None
|
||||
self._path_history = []
|
||||
self._revision = None
|
||||
|
||||
def _stop(self, reason):
|
||||
self.reset()
|
||||
return dict(allowed=False, strategy='manual', steer=0.0,
|
||||
max_speed_mph=self.MAX_SPEED_MPH, reason=reason,
|
||||
obstacles_verified=False, intersection_clearance_verified=False)
|
||||
|
||||
@staticmethod
|
||||
def _lanes(perception, lookahead):
|
||||
lanes = perception.lanes
|
||||
arrays = (lanes.x, lanes.left_y, lanes.right_y)
|
||||
if any(np.shape(a) != (33,) or not np.all(np.isfinite(a)) for a in arrays):
|
||||
return None, 'Invalid model lane geometry'
|
||||
if lanes.x[0] != 0 or lanes.x[-1] < 25 or np.any(np.diff(lanes.x) <= 0):
|
||||
return None, 'Model lanes have no usable forward extent'
|
||||
region = lanes.x <= lookahead + 4
|
||||
width = lanes.right_y[region] - lanes.left_y[region]
|
||||
center = (lanes.left_y + lanes.right_y) * .5
|
||||
if np.any(width < 2.2) or np.any(width > 5.5) or np.max(np.abs(center[region])) > 5:
|
||||
return None, 'Lane geometry is not plausible'
|
||||
probabilities = (lanes.left_prob, lanes.right_prob)
|
||||
if not all(math.isfinite(v) and 0 <= v <= 1 for v in probabilities):
|
||||
return None, 'Invalid model lane confidence'
|
||||
return center, ''
|
||||
|
||||
def _path_supported(self, perception, speed, center, now):
|
||||
"""Require partial visual evidence, a lane corridor and temporal coherence.
|
||||
|
||||
Plan hypothesis scores are deliberately not used as road confidence.
|
||||
Both unobserved markings cannot be rescued by GPS graph geometry.
|
||||
"""
|
||||
lanes, plan = perception.lanes, perception.plan
|
||||
probabilities = (lanes.left_prob, lanes.right_prob)
|
||||
if min(probabilities) < .25 or max(probabilities) < .45 or path_reason(plan, speed):
|
||||
self._path_history = []
|
||||
return False
|
||||
samples = np.array([4., 8., 12.])
|
||||
if plan.x[-1] < 14:
|
||||
self._path_history = []
|
||||
return False
|
||||
proposed = np.interp(samples, plan.x, plan.y)
|
||||
lane_center = np.interp(samples, lanes.x, center)
|
||||
half_width = np.interp(samples, lanes.x, (lanes.right_y-lanes.left_y)*.5)
|
||||
# Keep the selected trajectory inside the camera corridor, allowing
|
||||
# no more than 1.2 m disagreement with the lane-center hypothesis.
|
||||
if np.any(np.abs(proposed-lane_center) > np.minimum(1.2, half_width-.35)):
|
||||
self._path_history = []
|
||||
return False
|
||||
if self._path_history:
|
||||
previous_time, previous = self._path_history[-1]
|
||||
if now-previous_time > .5 or np.max(np.abs(proposed-previous)) > .35:
|
||||
self._path_history = []
|
||||
# Reassessing the same frame/time cannot build temporal evidence.
|
||||
if not self._path_history or now > self._path_history[-1][0]:
|
||||
self._path_history.append((now, proposed))
|
||||
self._path_history = [(t, p) for t, p in self._path_history if now-t <= .5]
|
||||
return len(self._path_history) >= 3 and now-self._path_history[0][0] >= .2
|
||||
|
||||
@staticmethod
|
||||
def _near_bend(route, preview, telemetry, lookahead):
|
||||
bend = preview.get('next_bend')
|
||||
if not bend:
|
||||
return None
|
||||
try:
|
||||
point = route['nodes'][bend['node_index']]['position']
|
||||
position = telemetry['world_position']
|
||||
distance = math.hypot(point[0]-position[0], point[2]-position[2])
|
||||
angle = float(bend['angle_deg'])
|
||||
direction = bend['direction']
|
||||
if (not all(math.isfinite(v) for v in (distance, angle))
|
||||
or not 25 <= abs(angle) <= 180
|
||||
or direction not in ('left', 'right')
|
||||
or (angle < 0) != (direction == 'left')):
|
||||
raise ValueError('Invalid route bend')
|
||||
# Advisor metres are map-scaled; use world metres for this horizon.
|
||||
if distance <= 60:
|
||||
return dict(direction=direction, distance_world_m=distance,
|
||||
angle_deg=angle, near=distance <= lookahead+8)
|
||||
except (KeyError, IndexError, TypeError, ValueError):
|
||||
return dict(invalid=True)
|
||||
return None
|
||||
|
||||
def assess(self, perception, speed_mps, route, preview, telemetry, now=None):
|
||||
"""Return an allow/release decision and a rate-limited lateral command.
|
||||
|
||||
Call once per freshly inferred frame. The caller retains focus, camera,
|
||||
telemetry, inference age, F8/manual override and actuator watchdog gates.
|
||||
"""
|
||||
now = self.clock() if now is None else now
|
||||
if not math.isfinite(now) or (self._last_time is not None and now < self._last_time):
|
||||
return self._stop('Invalid navigation planner clock')
|
||||
if not math.isfinite(speed_mps) or speed_mps < 0:
|
||||
return self._stop('Invalid navigation trial speed')
|
||||
if speed_mps / .44704 > self.MAX_SPEED_MPH + .5:
|
||||
return self._stop('Navigation trial speed exceeds 15 MPH limit')
|
||||
if not (telemetry.get('valid') and telemetry.get('position_valid') and telemetry.get('navigation_valid')):
|
||||
return self._stop('Fresh GPS telemetry required')
|
||||
if not route.get('available') or not preview.get('available'):
|
||||
return self._stop(route.get('reason') or preview.get('reason') or 'No active GPS route')
|
||||
if (route.get('lead_in') is not None or preview.get('lead_in_estimated')
|
||||
or preview.get('segment_kind') == 'lead-in'):
|
||||
return self._stop('Estimated GPS lead-in is display-only; native route matching required')
|
||||
if (route.get('geometry_kind') not in (None, 'native-route-node-array')
|
||||
or preview.get('segment_kind') not in (None, 'native-node-pair')):
|
||||
return self._stop('Unverified GPS geometry representation requires manual driving')
|
||||
age = route.get('age_s')
|
||||
if age is None or not math.isfinite(age) or not 0 <= age <= .5:
|
||||
return self._stop('GPS route sample is stale')
|
||||
error, progress, heading = (preview.get(k, float('nan')) for k in
|
||||
('lateral_error_world_m', 'progress_error_m', 'heading_dot'))
|
||||
if not all(isinstance(v, (int, float)) and math.isfinite(v) for v in (error, progress, heading)):
|
||||
return self._stop('Invalid GPS matching geometry')
|
||||
if error > 18 or error < 0 or progress > 250 or progress < 0 or not .65 <= heading <= 1.000001:
|
||||
return self._stop('Truck is off route or not aligned with GPS direction')
|
||||
if preview.get('reason'):
|
||||
return self._stop(preview['reason'])
|
||||
revision = route.get('revision')
|
||||
if revision != self._revision:
|
||||
self._path_history = []
|
||||
self._revision = revision
|
||||
lookahead = float(np.clip(speed_mps*1.5, 8., 25.))
|
||||
center, reason = self._lanes(perception, lookahead)
|
||||
if reason:
|
||||
return self._stop(reason)
|
||||
path_supported = self._path_supported(perception, speed_mps, center, now)
|
||||
lane_clear = min(perception.lanes.left_prob, perception.lanes.right_prob) >= .35
|
||||
bend = self._near_bend(route, preview, telemetry, lookahead)
|
||||
if bend and bend.get('invalid'):
|
||||
return self._stop('Invalid route bend geometry')
|
||||
target_y = -float(np.interp(lookahead, perception.lanes.x, center))
|
||||
strategy = 'camera-lanes'
|
||||
# Left is positive in GPS ego coordinates and SCS steering; model y is right.
|
||||
if bend and abs(bend['angle_deg']) >= 65 and bend['distance_world_m'] <= 25:
|
||||
return self._stop('Sharp GPS turn: intersection/right-of-way requires manual driving')
|
||||
if bend and bend['near']:
|
||||
if abs(bend['angle_deg']) >= 65:
|
||||
return self._stop('Sharp GPS turn: intersection/right-of-way requires manual driving')
|
||||
direction = 1 if bend['direction'] == 'left' else -1
|
||||
lane_curve = -float(np.interp(lookahead, perception.lanes.x, center)
|
||||
- np.interp(2., perception.lanes.x, center))
|
||||
lane_matches = direction*lane_curve > .10
|
||||
if not lane_matches or not lane_clear:
|
||||
if not path_supported:
|
||||
return self._stop('GPS bend has no stable camera-supported trajectory')
|
||||
path_curve = -float(np.interp(lookahead, perception.plan.x, perception.plan.y)
|
||||
- np.interp(2., perception.plan.x, perception.plan.y))
|
||||
if direction*path_curve <= .10:
|
||||
return self._stop('Model trajectory disagrees with GPS bend')
|
||||
target_y = -float(np.interp(lookahead, perception.plan.x, perception.plan.y))
|
||||
strategy = 'route-confirmed-model-path'
|
||||
elif not lane_clear:
|
||||
if not path_supported:
|
||||
return self._stop('Lane confidence low and camera path is not confirmed')
|
||||
# Straight route agreement also constrains the fallback's local heading.
|
||||
path_curve = -float(np.interp(lookahead, perception.plan.x, perception.plan.y)
|
||||
- np.interp(2., perception.plan.x, perception.plan.y))
|
||||
if abs(math.atan2(path_curve, lookahead-2)) > math.radians(12):
|
||||
return self._stop('Low-confidence model path does not follow straight GPS context')
|
||||
target_y = -float(np.interp(lookahead, perception.plan.x, perception.plan.y))
|
||||
strategy = 'route-confirmed-model-path'
|
||||
curvature = 2*target_y/(lookahead*lookahead+target_y*target_y)
|
||||
target = float(np.clip(math.atan(curvature*4.5)/math.radians(35),
|
||||
-self.MAX_STEER, self.MAX_STEER))
|
||||
dt = .05 if self._last_time is None else max(.001, min(.1, now-self._last_time))
|
||||
self.current_steer += float(np.clip(target-self.current_steer,
|
||||
-self.MAX_STEER_RATE*dt, self.MAX_STEER_RATE*dt))
|
||||
self._last_time = now
|
||||
return dict(allowed=True, strategy=strategy, steer=self.current_steer, reason='',
|
||||
max_speed_mph=8.0 if bend else self.MAX_SPEED_MPH,
|
||||
route_revision=revision, next_bend=bend,
|
||||
obstacles_verified=False, intersection_clearance_verified=False)
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Passive route matching and direction changes, never actuator commands.
|
||||
|
||||
GPS nodes are road graph points, not lane centers. Direction changes here are
|
||||
route bends: their coordinates alone cannot identify an exit or right-of-way.
|
||||
Distances to bends use ATS's advisor metres, which can differ from world metres.
|
||||
"""
|
||||
import math
|
||||
from telemetry.gps_route_reader import validate_lead_in, RouteValidationError
|
||||
|
||||
|
||||
def route_preview(route, telemetry):
|
||||
result = dict(available=False, usable_for_control=False, reason=route.get('reason', ''),
|
||||
label='GPS route unavailable', ego_points=[], next_bend=None)
|
||||
if not route.get('available'):
|
||||
return result
|
||||
if not (telemetry.get('valid') and telemetry.get('position_valid') and telemetry.get('navigation_valid')
|
||||
and not telemetry.get('paused')):
|
||||
return dict(result, reason='Fresh GPS pose required')
|
||||
if route.get('age_s', 0) > .5:
|
||||
return dict(result, reason='GPS route sample is stale')
|
||||
nodes = route['nodes']
|
||||
px, _, pz = telemetry['world_position']
|
||||
# SCS yaw is turns, zero looking down -Z; positive yaw turns toward -X.
|
||||
yaw = telemetry['world_rotation'][0]*2*math.pi
|
||||
fx, fz = -math.sin(yaw), -math.cos(yaw)
|
||||
lead_in = None
|
||||
prefix = telemetry['navigation_distance_m']-nodes[0]['distance_to_end_m']
|
||||
if prefix > 0:
|
||||
try:
|
||||
lead_in = validate_lead_in(nodes, telemetry)
|
||||
except RouteValidationError as exc:
|
||||
if prefix > 100:
|
||||
return dict(result, reason=str(exc), diagnostics=exc.diagnostics)
|
||||
candidates = []
|
||||
for i, (a, b) in enumerate(zip(nodes, nodes[1:])):
|
||||
ax, _, az = a['position']; bx, _, bz = b['position']
|
||||
dx, dz = bx-ax, bz-az
|
||||
length2 = dx*dx+dz*dz
|
||||
if length2 < 1:
|
||||
continue
|
||||
t = min(1, max(0, ((px-ax)*dx+(pz-az)*dz)/length2))
|
||||
error = math.hypot(px-ax-t*dx, pz-az-t*dz)
|
||||
remaining = a['distance_to_end_m']*(1-t)+b['distance_to_end_m']*t
|
||||
gps_error = abs(remaining-telemetry['navigation_distance_m'])
|
||||
candidates.append((error, gps_error, i, t, dx, dz, math.sqrt(length2)))
|
||||
if not candidates and lead_in is None:
|
||||
return dict(result, reason='GPS route has no usable segments')
|
||||
# GPS progress resolves overlapping/parallel legs before geometric proximity.
|
||||
nearby = [c for c in candidates if c[0] <= 35 and c[1] <= max(250,
|
||||
abs(nodes[c[2]]['distance_to_end_m']-nodes[c[2]+1]['distance_to_end_m'])*.15)]
|
||||
if lead_in is not None:
|
||||
dx, dz = nodes[0]['position'][0]-px, nodes[0]['position'][2]-pz
|
||||
error, gps_error, index, t, length = 0., lead_in['residual_world_m']*lead_in['local_scale'], -1, 0., math.hypot(dx,dz)
|
||||
elif not nearby:
|
||||
return dict(result, reason='Truck position or GPS progress does not match route')
|
||||
else:
|
||||
error, gps_error, index, t, dx, dz, length = min(nearby, key=lambda c: c[0]+c[1]/20)
|
||||
heading_dot = (fx*dx+fz*dz)/length
|
||||
points = [(0., 0.)]
|
||||
for node in nodes[index+1:]:
|
||||
x, _, z = node['position']
|
||||
rx, rz = x-px, z-pz
|
||||
# x=forward, y=left, suitable for a separate top-down schematic only.
|
||||
points.append((rx*fx+rz*fz, rx*fz-rz*fx))
|
||||
result.update(available=True, reason='', revision=route.get('revision'),
|
||||
node_count=len(nodes), segment=index, lateral_error_world_m=error,
|
||||
progress_error_m=gps_error, heading_dot=heading_dot,
|
||||
ego_points=points, label='Follow GPS route (preview)',
|
||||
navigation_distance_m=telemetry['navigation_distance_m'],
|
||||
segment_kind='lead-in' if lead_in is not None else 'native-node-pair',
|
||||
lead_in=lead_in, lead_in_estimated=lead_in is not None,
|
||||
distance_units='ATS advisor metres; not physical world metres')
|
||||
if lead_in is not None:
|
||||
result.update(lateral_error_world_m=None,
|
||||
label='Approach first GPS node (estimated preview)',
|
||||
qualification=lead_in['qualification'])
|
||||
if heading_dot < .5:
|
||||
return dict(result, label='Route direction differs; align manually',
|
||||
reason='Truck heading differs from route')
|
||||
# A lead-in supplies no authored incoming edge. Only real three-node bends
|
||||
# can be identified; do not fabricate a turn at the first stored node.
|
||||
for i in range(max(1, index+1), len(nodes)-1):
|
||||
a, b, c = (nodes[j]['position'] for j in (i-1, i, i+1))
|
||||
ux, uz = b[0]-a[0], b[2]-a[2]
|
||||
vx, vz = c[0]-b[0], c[2]-b[2]
|
||||
if min(math.hypot(ux, uz), math.hypot(vx, vz)) < 3:
|
||||
continue
|
||||
angle = math.degrees(math.atan2(ux*vz-uz*vx, ux*vx+uz*vz))
|
||||
distance = telemetry['navigation_distance_m']-nodes[i]['distance_to_end_m']
|
||||
if abs(angle) < 25 or distance < 0:
|
||||
continue
|
||||
direction = 'left' if angle < 0 else 'right'
|
||||
bend = dict(direction=direction, angle_deg=angle, distance_m=distance, node_index=i,
|
||||
distance_units='ATS advisor metres')
|
||||
distance_label = f'{distance/1609.344:.1f} mi' if distance >= 160.9344 else f'{distance*3.28084:.0f} ft'
|
||||
result.update(next_bend=bend, label=f'Route bends {direction} in {distance_label}')
|
||||
break
|
||||
return result
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Laneless trajectory assessment for passive runs only; no actuator access."""
|
||||
import math
|
||||
import numpy as np
|
||||
|
||||
|
||||
def path_reason(plan, speed_mps):
|
||||
if not math.isfinite(speed_mps) or speed_mps < 0:
|
||||
return "Invalid preview speed"
|
||||
arrays = (plan.x, plan.y, plan.z)
|
||||
if any(np.shape(a) != (33,) or not np.all(np.isfinite(a)) for a in arrays):
|
||||
return "Invalid model trajectory"
|
||||
lookahead = float(np.clip(speed_mps*1.5, 8.0, 25.0))
|
||||
if (abs(plan.x[0]) > 2 or np.any(np.diff(plan.x) <= 0)
|
||||
or plan.x[-1] < lookahead+2):
|
||||
return "Model trajectory has no usable forward extent"
|
||||
nearby = plan.y[(plan.x >= 0) & (plan.x <= lookahead+2)]
|
||||
if not len(nearby) or np.max(np.abs(nearby)) > 5:
|
||||
return "Model trajectory leaves the forward road region"
|
||||
# Hypothesis weight is deliberately not treated as road confidence.
|
||||
return ""
|
||||
|
||||
|
||||
def preview_steering(plan, speed_mps):
|
||||
reason = path_reason(plan, speed_mps)
|
||||
if reason:
|
||||
raise ValueError(reason)
|
||||
lookahead = float(np.clip(speed_mps*1.5, 8.0, 25.0))
|
||||
y = -float(np.interp(lookahead, plan.x, plan.y))
|
||||
curvature = 2*y/(lookahead*lookahead+y*y)
|
||||
return float(np.clip(math.atan(curvature*4.5)/math.radians(35), -0.35, 0.35))
|
||||
@@ -0,0 +1,515 @@
|
||||
"""Pure continuous experimental ATS Pop steering and bounded Chill cruise.
|
||||
|
||||
No actuator access or calibrated/production eligibility is granted here.
|
||||
The caller owns engagement, foreground, blank-camera and operator cancellation.
|
||||
"""
|
||||
import math
|
||||
import numbers
|
||||
import time
|
||||
import copy
|
||||
|
||||
import numpy as np
|
||||
|
||||
from model.perception import X_IDXS
|
||||
from control.pop_path_steering import path_steering,preview_curve_speed
|
||||
from control.gameplay_lead_guard import GameplayLeadGuard
|
||||
from control.native_collision_path import collision_gap
|
||||
from control.gameplay_road_tracking import GameplayRoadTracking
|
||||
|
||||
|
||||
def _number(value):
|
||||
if isinstance(value, bool) or not isinstance(value, numbers.Real):
|
||||
return None
|
||||
value = float(value)
|
||||
return value if math.isfinite(value) else None
|
||||
|
||||
|
||||
from control.gameplay_cruise import GameplayCruise
|
||||
|
||||
|
||||
class PopGameplayController:
|
||||
MIN_TARGET_MPH = 5.
|
||||
MAX_TARGET_MPH = 80.
|
||||
MAX_AXIS = .20
|
||||
STEERING_RATE_PER_S = .35
|
||||
DESCRIPTIVE_579_GAIN = .1254
|
||||
# SDK yaw/actual steering fit from the October 3 Tesla Semi drive (195
|
||||
# moving samples); descriptive simulator tuning, not physical calibration.
|
||||
DESCRIPTIVE_TESLA_GAIN = .1535
|
||||
MAX_MODEL_AGE_S = .35
|
||||
MAX_OUTPUT_GAP_S = .50
|
||||
CURVE_LATERAL_ACCEL_MPS2 = 2.
|
||||
CURVE_SPEED_RECOVERY_MPH_PER_S = 3.
|
||||
|
||||
def __init__(self, target_speed_mph=35., smoothing_tau_s=.12,
|
||||
model_age_s=None, output_gap_s=None):
|
||||
speed, tau = _number(target_speed_mph), _number(smoothing_tau_s)
|
||||
if speed is None or not self.MIN_TARGET_MPH <= speed <= self.MAX_TARGET_MPH or tau is None or tau <= 0:
|
||||
raise ValueError('Finite gameplay speed 5..80 mph and positive smoothing required')
|
||||
model_age = self.MAX_MODEL_AGE_S if model_age_s is None else _number(model_age_s)
|
||||
output_gap = self.MAX_OUTPUT_GAP_S if output_gap_s is None else _number(output_gap_s)
|
||||
if model_age is None or model_age <= 0 or output_gap is None or output_gap <= 0:
|
||||
raise ValueError('Positive model age and output gap limits required')
|
||||
self.target_speed_mph, self.smoothing_tau_s = speed, tau
|
||||
# The default limits remain the conservative controller contract used
|
||||
# by the unit tests and other callers. The continuous WMI runner opts
|
||||
# into a slightly wider, still bounded host-spike profile.
|
||||
self.model_age_limit_s, self.output_gap_limit_s = model_age, output_gap
|
||||
self._now = 0.
|
||||
self.cruise = GameplayCruise(clock=lambda: self._now)
|
||||
self.lead_guard=GameplayLeadGuard()
|
||||
self.road_tracking=GameplayRoadTracking()
|
||||
self.reset()
|
||||
|
||||
def set_target_speed(self, mph):
|
||||
speed=_number(mph)
|
||||
if speed is None or not self.MIN_TARGET_MPH<=speed<=self.MAX_TARGET_MPH:
|
||||
raise ValueError('Speed target must be finite and within 5..80 mph')
|
||||
if speed<self.target_speed_mph:
|
||||
self.cruise.integral=0.
|
||||
self.target_speed_mph=speed
|
||||
return speed
|
||||
|
||||
def _navigation_target_mph(self, telemetry):
|
||||
"""Apply an advisory GPS bend cap without changing the user's MAX."""
|
||||
target = self.target_speed_mph
|
||||
navigation = telemetry.get('navigation_driver') if isinstance(telemetry, dict) else None
|
||||
cap = _number(navigation.get('route_speed_cap_mph')) if isinstance(navigation, dict) else None
|
||||
if navigation and navigation.get('enabled') and cap is not None:
|
||||
target = min(target, max(self.MIN_TARGET_MPH, cap))
|
||||
return target
|
||||
|
||||
def reset(self):
|
||||
self._axis = self._smoothed = 0.
|
||||
self._last_output_time = self._last_good_time = self._last_input = None
|
||||
self._warmed_once = False
|
||||
self._curve_target_mph=None
|
||||
self._neutral_brake=None
|
||||
self._road_brake=0.
|
||||
self.cruise.reset()
|
||||
self.lead_guard.reset()
|
||||
self.road_tracking.reset()
|
||||
|
||||
def _result(self, reason, allowed=False, axis=0., action='coast', intensity=0., warnings=None, **extra):
|
||||
return dict(allowed=allowed, allowed_for_gameplay=allowed, requested_axis=axis, steer=axis,
|
||||
action=action, intensity=intensity,
|
||||
throttle=intensity if action == 'throttle' else 0., brake=intensity if action == 'brake' else 0.,
|
||||
reason=reason, warnings=list(warnings or []), target_speed_mph=self.target_speed_mph,
|
||||
experimental_gameplay=True, production_eligible=False, calibrated=False,
|
||||
physical_calibration_validated=False, controls_applied=False, control_eligible=False,
|
||||
route_competence_validated=False, intersection_competence_validated=False, **extra)
|
||||
|
||||
@staticmethod
|
||||
def _complete(data):
|
||||
coverage = data.get('model_temporal_coverage')
|
||||
return (isinstance(coverage, dict) and coverage.get('complete') is True
|
||||
and coverage.get('feature_slots_present') == 25 and coverage.get('feature_slots_required') == 25
|
||||
and coverage.get('narrow_pair_present') is True and coverage.get('wide_pair_present') is True)
|
||||
|
||||
def _sdk_reason(self, data, now, allow_neutral_braking=False):
|
||||
if now is None or not isinstance(data, dict):
|
||||
return 'Finite time and SDK data required'
|
||||
if data.get('valid') is not True or data.get('paused') is not False:
|
||||
return 'Fresh unpaused SDK required'
|
||||
stamp = data.get('timestamp')
|
||||
if isinstance(stamp, bool) or not isinstance(stamp, int) or stamp <= 0:
|
||||
return 'Positive SDK timestamp required'
|
||||
age, speed = _number(data.get('age')), _number(data.get('speed_mps'))
|
||||
if age is None or not 0 <= age <= .35 or speed is None or speed < -.02:
|
||||
return 'Finite fresh forward SDK speed required'
|
||||
gear = data.get('gear')
|
||||
if (isinstance(gear, bool) or not isinstance(gear, int)
|
||||
or gear < 0 or (gear == 0 and not allow_neutral_braking)):
|
||||
return 'Select Drive before engaging'
|
||||
if data.get('engine_enabled') is not True:
|
||||
return 'Turn on the engine before engaging'
|
||||
if data.get('park_brake') is not False:
|
||||
return 'Release the parking brake before engaging'
|
||||
return ''
|
||||
|
||||
def _model_reason(self, data, model_action, now):
|
||||
if (data.get('model_current_pair_available') is not True
|
||||
or data.get('model_inferred_this_frame') is not True
|
||||
or data.get('model_obstructed') is not False or data.get('model_geometry_stale') is not False):
|
||||
return 'Fresh current unobstructed paired Pop camera input required'
|
||||
stamp, age = _number(data.get('model_input_monotonic')), _number(data.get('model_age_s'))
|
||||
if (stamp is None or age is None or not 0 <= age <= self.model_age_limit_s
|
||||
or now-stamp > self.model_age_limit_s or stamp-now > .05):
|
||||
return 'Current model frame timestamp unavailable or stale'
|
||||
if self._last_input is not None and stamp <= self._last_input:
|
||||
return 'Waiting for a new unique Pop model frame'
|
||||
if (not isinstance(model_action, dict) or model_action.get('available') is not True
|
||||
or _number(model_action.get('desired_curvature')) is None
|
||||
or _number(model_action.get('desired_acceleration')) is None
|
||||
or type(model_action.get('should_stop')) is not bool):
|
||||
return 'Finite available modern Pop action required'
|
||||
return ''
|
||||
|
||||
def _warnings(self, perception, data, model_action):
|
||||
warnings = []
|
||||
if not self._complete(data):
|
||||
warnings.append('Historical temporal slots incomplete after real initial warmup')
|
||||
if model_action.get('should_stop') is True:
|
||||
warnings.append('Model stop intent advisory only; gameplay uses SDK speed/native traffic')
|
||||
try:
|
||||
horizon = min(25., max(8., data['speed_mps']*1.5))+2.
|
||||
plan_x = np.asarray(perception.plan.x, dtype=float)
|
||||
std = np.asarray(perception.plan_std, dtype=float)
|
||||
edges_std = np.asarray(perception.road_edge_std, dtype=float)
|
||||
edge_x = np.asarray(getattr(perception, 'road_edge_x', X_IDXS), dtype=float)
|
||||
if std.shape != (33, 15) or edges_std.shape != (2, 33, 2) or plan_x.shape != (33,) or edge_x.shape != (33,):
|
||||
raise ValueError('Unavailable shapes')
|
||||
path = std[(plan_x >= 0) & (plan_x <= horizon), 1]
|
||||
edges = edges_std[:, (edge_x >= 0) & (edge_x <= horizon), 0]
|
||||
if not path.size or not edges.size or not np.isfinite(path).all() or not np.isfinite(edges).all():
|
||||
raise ValueError('Unavailable uncertainty')
|
||||
if path.max() > .75: warnings.append('Predicted local path uncertainty elevated')
|
||||
if edges.max() > 1.5: warnings.append('Predicted local road-edge uncertainty elevated')
|
||||
except (AttributeError, TypeError, ValueError, IndexError):
|
||||
warnings.append('Predicted local path/edge uncertainty unavailable')
|
||||
return warnings
|
||||
|
||||
def _native_lead(self, perception, telemetry, now, warnings):
|
||||
report = telemetry.get('nearby_traffic')
|
||||
age = _number(report.get('age_s')) if isinstance(report, dict) else None
|
||||
sampled = _number(report.get('sampled_at')) if isinstance(report, dict) else None
|
||||
ego = telemetry.get('world_position')
|
||||
if (not isinstance(report, dict) or report.get('available') is not True
|
||||
or report.get('source') != 'ATS simulator actors' or age is None or not 0 <= age <= .3
|
||||
or sampled is None or not 0 <= now-sampled <= .3 or not isinstance(ego, (list, tuple))
|
||||
or len(ego) != 3 or _number(ego[1]) is None):
|
||||
warnings.append('Native traffic unavailable: acceleration inhibited without a tracked lead')
|
||||
return None
|
||||
candidates = []
|
||||
for actor in report.get('actors', []):
|
||||
if not isinstance(actor, dict):
|
||||
continue
|
||||
values = {key:_number(actor.get(key)) for key in
|
||||
('forward_m','left_m','length_m','width_m','height_m','heading_delta_rad')}
|
||||
relative=_number(actor.get('relative_forward_mps'))
|
||||
motion_known=actor.get('motion_available') is True and relative is not None and abs(relative)<=80
|
||||
position = actor.get('world_position')
|
||||
if (any(v is None for v in values.values()) or not isinstance(position, (list, tuple))
|
||||
or len(position) != 3 or _number(position[1]) is None):
|
||||
continue
|
||||
rotation=telemetry.get('world_rotation')
|
||||
if isinstance(rotation,(list,tuple)) and len(rotation)==3 and _number(rotation[0]) is not None:
|
||||
yaw=rotation[0]*2*math.pi
|
||||
dx,dz=position[0]-ego[0],position[2]-ego[2]
|
||||
if _number(position[0]) is None or _number(position[2]) is None:continue
|
||||
fx,fz=-math.sin(yaw),-math.cos(yaw)
|
||||
values['forward_m']=dx*fx+dz*fz
|
||||
values['left_m']=dx*fz-dz*fx
|
||||
world_heading=_number(actor.get('world_heading_rad'))
|
||||
if world_heading is not None:
|
||||
values['heading_delta_rad']=(world_heading-yaw+math.pi)%(2*math.pi)-math.pi
|
||||
if (not 0 < values['forward_m'] <= 100 or not 0 < values['length_m'] <= 25
|
||||
or not 0 < values['width_m'] <= 4 or not 0 < values['height_m'] <= 5
|
||||
or abs(position[1]-values['height_m']*.5-ego[1]) > 2.):
|
||||
continue
|
||||
own_front=_number(report.get('own_front_extent_m'))
|
||||
own_front=own_front if own_front is not None and 0<=own_front<=15 else 0.
|
||||
contact=collision_gap(values,getattr(perception,'plan',None),own_front)
|
||||
if contact is None:continue
|
||||
candidates.append(dict(id=actor.get('id'), **contact,
|
||||
relative_forward_mps=relative if motion_known else -telemetry['speed_mps'],
|
||||
motion_estimated=not motion_known,source='ATS simulator actors',
|
||||
lane_association_verified=False))
|
||||
warnings.append('Native traffic coverage/lane association incomplete; supervise following')
|
||||
return min(candidates, key=lambda actor:actor['distance_m']) if candidates else None
|
||||
|
||||
def preflight(self, perception, telemetry, model_action, now=None, warmed_once=False):
|
||||
now = _number(time.monotonic() if now is None else now)
|
||||
reason = self._sdk_reason(telemetry, now)
|
||||
if not reason: reason = self._model_reason(telemetry, model_action, now)
|
||||
if not reason: _,reason=self._navigation_path(perception,telemetry)
|
||||
if reason: return self._result(reason, preflight_only=True)
|
||||
if self._complete(telemetry): self._warmed_once = True
|
||||
if not self._warmed_once and warmed_once is not True:
|
||||
return self._result('Real complete Pop temporal context required once before engagement', preflight_only=True)
|
||||
return self._result('Experimental gameplay preflight ready; no controls requested', allowed=True,
|
||||
warnings=self._warnings(perception, telemetry, model_action), preflight_only=True)
|
||||
|
||||
@staticmethod
|
||||
def _navigation_path(perception,telemetry):
|
||||
change=telemetry.get('lane_change_driver') or {}
|
||||
if change.get('require_manual') is True:
|
||||
return perception,'Lane change: '+str(change.get('reason') or 'Manual completion required')
|
||||
navigation=telemetry.get('navigation_driver')
|
||||
if isinstance(navigation,dict) and navigation.get('enabled') is True and navigation.get('allowed_for_gameplay') is not True:
|
||||
# A transient GPS/model heading disagreement is a route-selection
|
||||
# gap, not proof that the camera model stopped seeing the road. The
|
||||
# navigation layer has already checked the model corridor and marks
|
||||
# only that recoverable case as transient. Keep the current camera
|
||||
# path for the short gap; hard route/shoulder/junction failures
|
||||
# continue to require manual control below.
|
||||
if navigation.get('transient') is True and navigation.get('require_manual') is not True:
|
||||
telemetry['_gps_model_fallback_reason'] = str(
|
||||
navigation.get('reason') or 'GPS alignment temporarily unavailable')
|
||||
return perception,''
|
||||
return perception,'GPS: '+str(navigation.get('reason') or 'Route-aligned road path unavailable')
|
||||
if change.get('active') is True and change.get('allowed_for_gameplay') is True:
|
||||
override=change.get('path_override')
|
||||
label='Lane change'
|
||||
else:
|
||||
override=navigation.get('path_override') if isinstance(navigation,dict) and navigation.get('enabled') is True else None
|
||||
label='GPS'
|
||||
if override is None:return perception,''
|
||||
try:
|
||||
selected=copy.copy(perception)
|
||||
selected.plan=copy.copy(perception.plan)
|
||||
for axis in ('x','y','z'):
|
||||
values=np.asarray(override[axis],dtype=float)
|
||||
if values.shape!=(33,) or not np.isfinite(values).all():
|
||||
raise ValueError('Invalid route-selected camera path')
|
||||
setattr(selected.plan,axis,values)
|
||||
return selected,''
|
||||
except (AttributeError,KeyError,TypeError,ValueError):
|
||||
return perception,label+': invalid selected camera path'
|
||||
|
||||
def _gap_pedals(self,telemetry,now):
|
||||
"""A brief path/camera gap must not cancel a closing-traffic brake."""
|
||||
self._now=now
|
||||
native=self._native_lead(None,telemetry,now,[])
|
||||
lead,guard=self.lead_guard.assess(native,None,telemetry,now)
|
||||
action,duty=self.cruise.compute(min(self._navigation_target_mph(telemetry),
|
||||
self._curve_target_mph or self.target_speed_mph),telemetry['speed_mps']*2.2369362921,lead,
|
||||
pedal_feedback=telemetry)
|
||||
if self._neutral_brake is not None:
|
||||
action,duty='brake',max(self._neutral_brake,duty if action=='brake' else 0.)
|
||||
self.cruise.action,self.cruise.intensity=action,duty
|
||||
elif action!='brake':
|
||||
action,duty='coast',0.
|
||||
self.cruise.reset()
|
||||
if self._road_brake:
|
||||
action,duty='brake',max(self._road_brake,duty if action=='brake' else 0.)
|
||||
return dict(action=action,intensity=duty,following_guard=guard,
|
||||
following_braking=self.cruise.following)
|
||||
|
||||
def _stopped_queue_hold(self, telemetry, now, reason, road_tracking=None):
|
||||
"""Keep a stopped queue brake engaged without inventing a drive path.
|
||||
|
||||
A short model horizon behind a nearby vehicle is not a reason to drop
|
||||
an already applied brake. Fresh simulator contact in the actual forward
|
||||
footprint and fresh SDK/model input remain necessary. This branch can
|
||||
never accelerate or steer around the lead; departure uses the normal
|
||||
current-road/navigation admission again.
|
||||
"""
|
||||
if (self._last_good_time is None or not 0 <= telemetry['speed_mps'] <= .5
|
||||
or not (self._road_brake > 0 or self.cruise.action == 'brake')):
|
||||
return None
|
||||
warnings = []
|
||||
native = self._native_lead(None, telemetry, now, warnings)
|
||||
if native is None or not 0 < native['distance_m'] <= 20.:
|
||||
return None
|
||||
lead, guard = self.lead_guard.assess(native, None, telemetry, now)
|
||||
if not guard['native_report_fresh'] or guard['held_during_dropout']:
|
||||
return None
|
||||
self._now = now
|
||||
action, duty = self.cruise.compute(0., telemetry['speed_mps']*2.2369362921,
|
||||
lead, pedal_feedback=telemetry)
|
||||
duty = max(.12, duty if action == 'brake' else 0.)
|
||||
self.cruise.action, self.cruise.intensity = 'brake', duty
|
||||
self.cruise.integral = 0.
|
||||
self._axis = self._smoothed = 0.
|
||||
self._last_output_time = self._last_good_time = now
|
||||
self._last_input = float(telemetry['model_input_monotonic'])
|
||||
return self._result('Stopped behind traffic: brake held; waiting for a current road path',
|
||||
allowed=True, action='brake', intensity=duty, warnings=[reason],
|
||||
queue_brake_hold=True, departure_requires_current_geometry=True,
|
||||
native_lead=native, following_guard=guard, following_braking=self.cruise.following,
|
||||
effective_speed_target_mph=0., model_input_monotonic=self._last_input,
|
||||
steering_geometry=dict(available=False, reason=reason,
|
||||
road_tracking=road_tracking or dict(strategy='stopped-traffic-brake-hold',
|
||||
lane_tracking=False,brake_required=True)))
|
||||
|
||||
def assess(self, perception, telemetry, model_action, now=None, warmed_once=False):
|
||||
now = _number(time.monotonic() if now is None else now)
|
||||
neutral_braking=(isinstance(telemetry,dict) and type(telemetry.get('gear')) is int
|
||||
and telemetry['gear']==0 and (self._neutral_brake is not None
|
||||
or (self.cruise.action=='brake' and (self.cruise.following is not None or self._road_brake))))
|
||||
previous_brake=self._neutral_brake if self._neutral_brake is not None else self.cruise.intensity
|
||||
sdk_reason = self._sdk_reason(telemetry, now,allow_neutral_braking=neutral_braking)
|
||||
if sdk_reason:
|
||||
self.reset()
|
||||
return self._result(sdk_reason)
|
||||
if neutral_braking:self._neutral_brake=previous_brake
|
||||
# SDK wheel noise can report tiny negative speed at a stationary truck.
|
||||
# Do not release a stopped-traffic brake for that noise. Keep the raw
|
||||
# caller/evidence data unchanged; real reverse motion remains rejected.
|
||||
stationary_noise=telemetry['speed_mps']<0
|
||||
if stationary_noise:telemetry=dict(telemetry,speed_mps=0.)
|
||||
if self._last_output_time is not None and now < self._last_output_time:
|
||||
self.reset()
|
||||
return self._result('Monotonic time regressed')
|
||||
output_gap=now-self._last_good_time if self._last_good_time is not None else 0.
|
||||
if output_gap > self.output_gap_limit_s:
|
||||
self.reset()
|
||||
return self._result('Command gap exceeds %.2f seconds; reengagement required'%self.output_gap_limit_s)
|
||||
reason = self._model_reason(telemetry, model_action, now)
|
||||
if reason:
|
||||
if (self._last_good_time is not None and self._last_input is not None
|
||||
and 0 <= now-self._last_good_time <= self.model_age_limit_s
|
||||
and 0 <= now-self._last_input <= self.model_age_limit_s):
|
||||
return self._result('Brief model gap: last steering held; traffic braking retained',
|
||||
allowed=True, axis=self._axis, warnings=[reason], held_previous_steering=True,
|
||||
model_hold_age_s=now-self._last_good_time,**self._gap_pedals(telemetry,now))
|
||||
self.reset()
|
||||
return self._result(reason+'; model hold deadline expired')
|
||||
if self._complete(telemetry): self._warmed_once = True
|
||||
if not self._warmed_once and warmed_once is not True:
|
||||
self.cruise.reset()
|
||||
return self._result('Real complete Pop temporal context required once before engagement')
|
||||
if neutral_braking:
|
||||
# Automatic shifts briefly report gear zero. A shift must not
|
||||
# release an already-commanded traffic brake while still moving.
|
||||
pedals=self._gap_pedals(telemetry,now)
|
||||
duty=max(previous_brake,pedals['intensity'])
|
||||
self._neutral_brake=duty
|
||||
self.cruise.action,self.cruise.intensity='brake',duty
|
||||
self._last_output_time=self._last_good_time=now
|
||||
self._last_input=float(telemetry['model_input_monotonic'])
|
||||
pedals.update(action='brake',intensity=duty)
|
||||
return self._result('Traffic brake retained through neutral/automatic shift',
|
||||
allowed=True,axis=self._axis,neutral_traffic_brake_held=True,
|
||||
held_previous_steering=True,**pedals)
|
||||
self._neutral_brake=None
|
||||
self._now = now
|
||||
warnings = self._warnings(perception, telemetry, model_action)
|
||||
game_cruise_conflict=telemetry.get('game_cruise_active') is True
|
||||
if game_cruise_conflict:
|
||||
warnings.append('ATS cruise control is active: it can hold speed after our throttle releases')
|
||||
selected,navigation_reason=self._navigation_path(perception,telemetry)
|
||||
if navigation_reason:
|
||||
# Only missing comparison distance is a queue-hold exception. A
|
||||
# shoulder, changed route, or positive GPS/model disagreement must
|
||||
# retain its existing manual-handoff path.
|
||||
if navigation_reason == 'GPS: Current trajectory lacks near-to-forward route comparison':
|
||||
queued = self._stopped_queue_hold(telemetry, now, navigation_reason)
|
||||
if queued is not None:
|
||||
return queued
|
||||
navigation=telemetry.get('navigation_driver') or {}
|
||||
expired=navigation.get('gps_hold_expired') is True
|
||||
deadline=_number(navigation.get('hold_deadline_monotonic'))
|
||||
if deadline is not None and now>deadline:expired=True
|
||||
if not expired and self._last_good_time is not None and now-self._last_good_time<=self.model_age_limit_s:
|
||||
return self._result('Brief GPS gap: traffic braking retained',allowed=True,
|
||||
axis=self._axis,warnings=[navigation_reason],held_previous_steering=True,
|
||||
**self._gap_pedals(telemetry,now))
|
||||
self.reset()
|
||||
return self._result(navigation_reason+'; manual steering required')
|
||||
fallback_reason=telemetry.get('_gps_model_fallback_reason')
|
||||
if fallback_reason:
|
||||
warnings.append('GPS alignment gap; using the current camera path')
|
||||
perception,road_tracking=self.road_tracking.assess(selected,telemetry,now)
|
||||
if road_tracking['brake_required']:
|
||||
queued = self._stopped_queue_hold(telemetry, now,
|
||||
'Current road confidence reduced behind a nearby vehicle', road_tracking)
|
||||
if queued is not None:
|
||||
return queued
|
||||
if output_gap > self.model_age_limit_s:
|
||||
# Only a unique current frame that passed the unchanged exposure
|
||||
# age checks reaches here. Restart from measured steering, rather
|
||||
# than applying a rate-limit step accumulated across the pause.
|
||||
actual=_number(telemetry.get('steering'))
|
||||
if actual is not None:self._axis=max(-self.MAX_AXIS,min(self.MAX_AXIS,actual))
|
||||
self._smoothed=self._axis
|
||||
self._last_output_time=now
|
||||
self.cruise.reset()
|
||||
warnings.append('Fresh model recovered after brief processing pause')
|
||||
gain=(self.DESCRIPTIVE_TESLA_GAIN if telemetry.get('truck_name')=='Semi truck 2019'
|
||||
else self.DESCRIPTIVE_579_GAIN)
|
||||
options=dict(lookahead_s=1.2,minimum_m=12.,maximum_m=25.) if road_tracking['lane_tracking'] else {}
|
||||
geometry=path_steering(perception.plan,telemetry['speed_mps'],gain,**options)
|
||||
if not geometry['available']:
|
||||
queued = self._stopped_queue_hold(telemetry, now, geometry['reason'], road_tracking)
|
||||
if queued is not None:
|
||||
return queued
|
||||
if self._last_good_time is not None and now-self._last_good_time<=self.model_age_limit_s:
|
||||
return self._result('Brief path gap: last steering held; traffic braking retained',allowed=True,
|
||||
axis=self._axis,warnings=[geometry['reason']],held_previous_steering=True,
|
||||
steering_geometry=geometry,**self._gap_pedals(telemetry,now))
|
||||
self.reset()
|
||||
return self._result(geometry['reason'],steering_geometry=geometry)
|
||||
geometry['lane_center_assist']=dict(available=False,enabled=False,
|
||||
reason='Disabled after reported lane-keeping regression',correction_m=0.)
|
||||
geometry['road_tracking']=road_tracking
|
||||
geometry['selected_path']={key:np.asarray(getattr(perception.plan,key)).tolist()
|
||||
for key in ('x','y','z') if hasattr(perception.plan,key)}
|
||||
geometry['descriptive_steering_gain']=gain
|
||||
if road_tracking['lane_tracking']:geometry['source']=road_tracking['strategy']
|
||||
navigation=telemetry.get('navigation_driver')
|
||||
if isinstance(navigation,dict) and navigation.get('enabled'):
|
||||
geometry['navigation_strategy']=navigation.get('strategy')
|
||||
if geometry['lookahead_limited']:warnings.append('Steering lookahead limited to actual predicted path')
|
||||
target = max(-self.MAX_AXIS, min(self.MAX_AXIS,geometry['raw_axis']))
|
||||
if road_tracking.get('road_lost'):
|
||||
target=0.
|
||||
warnings.insert(0,'Road estimate lost: braking; take over')
|
||||
dt = min(.35, max(0., now-self._last_output_time)) if self._last_output_time is not None else .05
|
||||
tau=max(.35,self.smoothing_tau_s) if geometry['lookahead_limited'] else self.smoothing_tau_s
|
||||
smoothed = self._smoothed + dt/(tau+dt)*(target-self._smoothed)
|
||||
change = self.STEERING_RATE_PER_S*dt
|
||||
axis = max(self._axis-change, min(self._axis+change, smoothed))
|
||||
native_lead = self._native_lead(perception, telemetry, now, warnings)
|
||||
following_lead,following_guard=self.lead_guard.assess(native_lead,perception,telemetry,now)
|
||||
# MAX is a ceiling, not a demand to enter every bend at that speed.
|
||||
# Use the same current path curvature as steering, never painted-lane
|
||||
# association. Decrease promptly; restore speed gradually after a bend.
|
||||
curve_limit_mph=math.sqrt(self.CURVE_LATERAL_ACCEL_MPS2/
|
||||
max(1e-6,abs(geometry['curvature'])))*2.2369362921
|
||||
navigation_target=self._navigation_target_mph(telemetry)
|
||||
wanted_speed=min(navigation_target,max(10.,curve_limit_mph))
|
||||
curve_preview=preview_curve_speed(perception.plan,self.CURVE_LATERAL_ACCEL_MPS2)
|
||||
if curve_preview['speed_limit_mph'] is not None:
|
||||
wanted_speed=min(wanted_speed,max(10.,curve_preview['speed_limit_mph']))
|
||||
recovery_cap=_number(road_tracking.get('recovery_speed_cap_mph'))
|
||||
if recovery_cap is not None:
|
||||
wanted_speed=min(wanted_speed,recovery_cap)
|
||||
warnings.insert(0,'Brief road-confidence gap: holding observed lane; reducing speed gently')
|
||||
if self._curve_target_mph is None:self._curve_target_mph=wanted_speed
|
||||
else:self._curve_target_mph=min(wanted_speed,
|
||||
self._curve_target_mph+self.CURVE_SPEED_RECOVERY_MPH_PER_S*dt)
|
||||
effective_speed=min(navigation_target,self._curve_target_mph)
|
||||
navigation=telemetry.get('navigation_driver')
|
||||
if (isinstance(navigation,dict) and navigation.get('enabled') and
|
||||
isinstance(navigation.get('route_speed_cap_mph'),(int,float)) and
|
||||
navigation['route_speed_cap_mph'] < self.target_speed_mph-.5):
|
||||
warnings.insert(0,'GPS turn approach cap %.0f MPH (MAX %.0f)' %
|
||||
(navigation['route_speed_cap_mph'],self.target_speed_mph))
|
||||
if effective_speed<self.target_speed_mph-.5:
|
||||
warnings.insert(0,'Curve speed %.0f MPH (MAX %.0f)'%(effective_speed,self.target_speed_mph))
|
||||
action, intensity = self.cruise.compute(effective_speed,
|
||||
telemetry['speed_mps']*2.2369362921, following_lead,
|
||||
curve_limited=effective_speed<self.target_speed_mph-.5,
|
||||
pedal_feedback=telemetry)
|
||||
if (following_guard['acceleration_inhibited'] or recovery_cap is not None) and action=='throttle':
|
||||
action,intensity='coast',0.
|
||||
self.cruise.action,self.cruise.intensity='coast',0.
|
||||
if road_tracking['brake_required']:
|
||||
# Keep control long enough to brake. Releasing engagement here
|
||||
# would drop the brake as well as the unreliable steering request.
|
||||
self._road_brake=min(.45,self._road_brake+.5*dt)
|
||||
action,intensity='brake',max(self._road_brake,intensity if action=='brake' else 0.)
|
||||
self.cruise.integral=0.
|
||||
self.cruise.action,self.cruise.intensity=action,intensity
|
||||
else:self._road_brake=0.
|
||||
brake_cap=1. if self.cruise.following else .45 if self._road_brake else .20
|
||||
intensity = max(0., min(1. if action == 'throttle' else brake_cap if action == 'brake' else 0., intensity))
|
||||
self._axis, self._smoothed = axis, smoothed
|
||||
self._last_output_time = self._last_good_time = now
|
||||
self._last_input = float(telemetry['model_input_monotonic'])
|
||||
return self._result('Experimental continuous Pop gameplay', allowed=True, axis=axis,
|
||||
action=action, intensity=intensity, warnings=warnings, target_axis=target,
|
||||
steering_rate_limit_per_s=self.STEERING_RATE_PER_S, smoothing_tau_s=tau,
|
||||
longitudinal_source='SDK speed hold; native lead and persistent camera rear braking', native_lead=native_lead,
|
||||
visual_lead_advisory_only=False,throttle_cap=1.,brake_cap=brake_cap,
|
||||
following_guard=following_guard,following_braking=self.cruise.following,
|
||||
pedal_feedback=self.cruise.pedal_feedback,
|
||||
game_cruise_conflict=game_cruise_conflict,
|
||||
stationary_speed_noise_clamped=stationary_noise,
|
||||
effective_speed_target_mph=effective_speed,curve_speed_limit_mph=curve_limit_mph,
|
||||
curve_speed_preview=curve_preview,
|
||||
curve_lateral_accel_limit_mps2=self.CURVE_LATERAL_ACCEL_MPS2,
|
||||
held_previous_steering=False, model_input_monotonic=self._last_input,
|
||||
steering_geometry=geometry,modern_action_curvature=model_action['desired_curvature'])
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Pure modern Pop action extraction; never an actuator or control approval.
|
||||
|
||||
Primary source revision 62bf6fb072880905a4c490f0f4f4a6b3c23346ec:
|
||||
https://github.com/commaai/openpilot/blob/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/controls/lib/drive_helpers.py
|
||||
https://github.com/commaai/openpilot/blob/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/modeld/modeld.py
|
||||
https://github.com/commaai/openpilot/blob/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/modeld/constants.py
|
||||
|
||||
These formulas match upstream model actions, before vehicle-specific control.
|
||||
The .2s ATS lateral/longitudinal defaults are UNVALIDATED assumptions. The
|
||||
upstream .05s model step and .3s longitudinal smoothing are retained exactly;
|
||||
calling at a different cadence does not establish equivalent temporal behavior.
|
||||
"""
|
||||
import math
|
||||
import numbers
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
SOURCE_REVISION = '62bf6fb072880905a4c490f0f4f4a6b3c23346ec'
|
||||
SOURCE_SHA256 = {
|
||||
'selfdrive/controls/lib/drive_helpers.py': '0c8b32b1667000d48ee4630f0b197a05edabd811d718709ab616872c35918844',
|
||||
'selfdrive/modeld/modeld.py': '571496f6e8b8364d90d0e2dddcb2a6f375ecbb434927e11078f40084e56f3b66',
|
||||
'selfdrive/modeld/constants.py': 'e1e3a01ea31dd57dbd9ffd588ff1f2ab22e6088a558c65ad68bf20678552c00c',
|
||||
}
|
||||
CONTRACT = 'pop-v2-split-1576-1000'
|
||||
PLAN_TIMES = 10. * (np.arange(33, dtype=np.float64) / 32.) ** 2
|
||||
MODEL_DT = .05
|
||||
LONG_SMOOTH_SECONDS = .3
|
||||
MIN_LAT_CONTROL_SPEED = .3
|
||||
MIN_CURVATURE_SPEED = 1.
|
||||
UPSTREAM_MAX_CURVATURE = .2
|
||||
|
||||
|
||||
def _finite_number(value):
|
||||
if isinstance(value, bool) or not isinstance(value, numbers.Real):
|
||||
return None
|
||||
try:
|
||||
value = float(value)
|
||||
except (OverflowError, ValueError):
|
||||
return None
|
||||
return value if math.isfinite(value) else None
|
||||
|
||||
|
||||
class PopModelActions:
|
||||
"""Extract model actions with explicit unvalidated delay assumptions.
|
||||
|
||||
Broad input rejection bounds (100m/s speed, 100m/s² acceleration, two
|
||||
revolutions of yaw/radian-rate) reject corrupt outputs without fitting a
|
||||
recording. The .2/m curvature rejection bound is the upstream downstream
|
||||
helper MAX_CURVATURE; no clipping hides an out-of-bound prediction.
|
||||
"""
|
||||
def __init__(self, *, lateral_delay_s=.2, longitudinal_delay_s=.2):
|
||||
lateral, longitudinal = _finite_number(lateral_delay_s), _finite_number(longitudinal_delay_s)
|
||||
if lateral is None or longitudinal is None or not (0 <= lateral <= 2 and 0 <= longitudinal <= 2):
|
||||
raise ValueError('Unvalidated action delay must be finite and within0..2 seconds')
|
||||
self.lateral_delay_s, self.longitudinal_delay_s = lateral, longitudinal
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.previous_acceleration = 0.
|
||||
self.previous_curvature = 0.
|
||||
|
||||
def assess(self, perception, speed_mps):
|
||||
lat_action_t = self.lateral_delay_s + MODEL_DT
|
||||
long_action_t = self.longitudinal_delay_s + LONG_SMOOTH_SECONDS + MODEL_DT
|
||||
result = dict(available=False, desired_curvature=None, desired_acceleration=None,
|
||||
raw_desired_curvature=None, raw_desired_acceleration=None, should_stop=None,
|
||||
target_speed_mps=None, target_speed_1s_mps=None,
|
||||
lateral_action_time_s=lat_action_t, longitudinal_action_time_s=long_action_t,
|
||||
lateral_delay_s=self.lateral_delay_s,
|
||||
longitudinal_delay_s=self.longitudinal_delay_s,
|
||||
delay_parameters_validated=False, expected_model_hz=20,
|
||||
smoothing_dt_s=MODEL_DT, upstream_cadence_validated=False,
|
||||
controls_applied=False, control_eligible=False, preview_only=True,
|
||||
source_revision=SOURCE_REVISION, source_sha256=dict(SOURCE_SHA256), reason='')
|
||||
|
||||
def unavailable(reason):
|
||||
self.reset()
|
||||
result['reason'] = reason
|
||||
return result
|
||||
|
||||
speed = _finite_number(speed_mps)
|
||||
if speed is None or not 0 <= speed <= 100:
|
||||
return unavailable('Invalid model action speed')
|
||||
if getattr(perception, 'pop_plan_contract', None) != CONTRACT:
|
||||
return unavailable('Full modern Pop plan contract is unavailable')
|
||||
try:
|
||||
velocity, acceleration, orientation, orientation_rate = (
|
||||
np.asarray(getattr(perception, name), dtype=np.float64)
|
||||
for name in ('velocity_xyz', 'acceleration_xyz', 'orientation_xyz', 'orientation_rate_xyz'))
|
||||
times = np.asarray(perception.plan_times, dtype=np.float64)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
return unavailable('Complete modern motion plan is unavailable')
|
||||
if (any(a.shape != (33, 3) or not np.all(np.isfinite(a))
|
||||
for a in (velocity, acceleration, orientation, orientation_rate))
|
||||
or times.shape != (33,) or not np.all(np.isfinite(times))
|
||||
or not np.allclose(times, PLAN_TIMES, rtol=0, atol=1e-7)):
|
||||
return unavailable('Invalid modern motion plan arrays/time contract')
|
||||
if (np.max(np.abs(velocity)) > 100 or np.max(np.abs(acceleration)) > 100
|
||||
or np.max(np.abs(orientation)) > 4*math.pi
|
||||
or np.max(np.abs(orientation_rate)) > 4*math.pi):
|
||||
return unavailable('Modern motion plan exceeds broad input bounds')
|
||||
# drive_helpers.get_accel_from_plan: x speed/acceleration at delay.
|
||||
v_now, a_now = float(velocity[0, 0]), float(acceleration[0, 0])
|
||||
v_target = float(np.interp(long_action_t, times, velocity[:, 0]))
|
||||
v_target_1sec = float(np.interp(long_action_t+1., times, velocity[:, 0]))
|
||||
raw_accel = 2*(v_target-v_now)/long_action_t-a_now
|
||||
should_stop = v_target < .05 and v_target_1sec < .05
|
||||
# Upstream smooth_value retains DT_MDL=.05 and LONG_SMOOTH_SECONDS=.3.
|
||||
alpha = 1-math.exp(-MODEL_DT/LONG_SMOOTH_SECONDS)
|
||||
desired_accel = alpha*raw_accel + (1-alpha)*self.previous_acceleration
|
||||
# drive_helpers.get_curvature_from_plan uses interpolated yaw but
|
||||
# initial yaw rate, not the rate interpolated at the actuator delay.
|
||||
psi_target = float(np.interp(lat_action_t, times, orientation[:, 2]))
|
||||
psi_rate = float(orientation_rate[0, 2])
|
||||
safe_speed = max(speed, MIN_CURVATURE_SPEED)
|
||||
raw_curvature = 2*psi_target/(safe_speed*lat_action_t)-psi_rate/safe_speed
|
||||
desired_curvature = raw_curvature if speed > MIN_LAT_CONTROL_SPEED else self.previous_curvature
|
||||
if (not all(math.isfinite(v) for v in (raw_accel, desired_accel, raw_curvature, desired_curvature))
|
||||
or abs(desired_curvature) > UPSTREAM_MAX_CURVATURE):
|
||||
return unavailable('Modern model action is nonfinite or exceeds upstream curvature bound')
|
||||
self.previous_acceleration, self.previous_curvature = desired_accel, desired_curvature
|
||||
result.update(available=True, desired_curvature=desired_curvature,
|
||||
raw_desired_curvature=raw_curvature,
|
||||
desired_acceleration=desired_accel, raw_desired_acceleration=raw_accel,
|
||||
should_stop=bool(should_stop), target_speed_mps=v_target,
|
||||
target_speed_1s_mps=v_target_1sec,
|
||||
low_speed_curvature_held=speed <= MIN_LAT_CONTROL_SPEED,
|
||||
reason='Modern Pop action preview; ATS delays and control response remain unvalidated')
|
||||
return result
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Geometric lookahead on the current Pop path, without path extrapolation."""
|
||||
import math
|
||||
import numpy as np
|
||||
|
||||
|
||||
class LaneCenterAssist:
|
||||
"""Gradual paint guidance in the same model frame; path remains fallback."""
|
||||
def __init__(self):self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.correction=0.
|
||||
self.last_time=self.last_near=None
|
||||
self.block_until=0.
|
||||
|
||||
def apply(self,geometry,lanes,now,gain=.1254):
|
||||
dt=min(.35,max(0.,now-self.last_time)) if self.last_time is not None else .05
|
||||
if self.last_time is not None and now-self.last_time>.5:
|
||||
self.reset();dt=.05
|
||||
self.last_time=now
|
||||
wanted=weight=0.
|
||||
detail=dict(available=False,reason='Lane markings unavailable')
|
||||
try:
|
||||
x,left,right=(np.asarray(getattr(lanes,key),dtype=float) for key in ('x','left_y','right_y'))
|
||||
probs=np.asarray([lanes.left_prob,lanes.right_prob],dtype=float)
|
||||
distance=geometry['lookahead_m']
|
||||
if (any(a.shape!=(33,) or not np.isfinite(a).all() for a in (x,left,right))
|
||||
or not np.isfinite(probs).all() or np.any((probs<0)|(probs>1))
|
||||
or np.any(np.diff(x)<=0) or x[0]>5 or x[-1]<distance):
|
||||
raise ValueError('Lane geometry unavailable at current lookahead')
|
||||
if min(probs)<.55:raise ValueError('Lane markings uncertain: path fallback')
|
||||
samples=np.r_[5.,x[(x>5.)&(x<distance)],distance]
|
||||
widths=np.interp(samples,x,right-left)
|
||||
if np.any((widths<2.8)|(widths>4.5)) or np.ptp(widths)>.8:
|
||||
raise ValueError('Lane width/order inconsistent: path fallback')
|
||||
center=(left+right)*.5
|
||||
near=float(np.interp(5.,x,center))
|
||||
lateral=float(np.interp(distance,x,center))
|
||||
if abs(near)>2.:raise ValueError('Lane center outside ego corridor: path fallback')
|
||||
if self.last_near is not None and abs(near-self.last_near)>.75+dt:
|
||||
self.block_until=now+.6
|
||||
self.last_near=near
|
||||
if now<self.block_until:raise ValueError('Lane association changed: path fallback')
|
||||
weight=.65*min(1.,max(0.,(float(min(probs))-.55)/.35))
|
||||
delta=lateral-geometry['target_lateral_m']
|
||||
wanted=weight*max(-1.2,min(1.2,delta))
|
||||
detail=dict(available=True,lane_center_y_m=lateral,near_center_y_m=near,
|
||||
confidence=float(min(probs)),weight=weight,path_center_delta_m=delta)
|
||||
except (AttributeError,TypeError,ValueError,IndexError) as exc:
|
||||
detail=dict(available=False,reason=str(exc))
|
||||
# Smooth the correction itself, including fading back to the path.
|
||||
# Limit its rate so a changed line slot cannot inject a steering step.
|
||||
tau=.35 if detail['available'] else .2
|
||||
change=dt/(tau+dt)*(wanted-self.correction)
|
||||
self.correction+=max(-.6*dt,min(.6*dt,change))
|
||||
if abs(self.correction)<1e-6:self.correction=0.
|
||||
lateral=geometry['target_lateral_m']+self.correction
|
||||
distance=geometry['lookahead_m']
|
||||
curvature=2*lateral/(distance*distance+lateral*lateral)
|
||||
return dict(geometry,path_target_lateral_m=geometry['target_lateral_m'],
|
||||
target_lateral_m=lateral,curvature=curvature,undamped_axis=-curvature/gain,
|
||||
raw_axis=-curvature/gain*geometry['extent_gain_scale'],
|
||||
lane_center_assist=dict(detail,correction_m=self.correction),
|
||||
source='current-model-path-with-lane-center-assist' if self.correction else geometry['source'])
|
||||
|
||||
|
||||
def path_steering(plan, speed_mps, gain=.1254, *, lookahead_s=2.5, minimum_m=18., maximum_m=45.):
|
||||
try:
|
||||
x=np.asarray(plan.x,dtype=float)
|
||||
y=np.asarray(plan.y,dtype=float)
|
||||
if x.shape!=(33,) or y.shape!=(33,) or not np.isfinite(x).all() or not np.isfinite(y).all():
|
||||
raise ValueError('Invalid current path')
|
||||
if not math.isfinite(speed_mps) or speed_mps<0:
|
||||
raise ValueError('Invalid current speed')
|
||||
# Never sort a folded plan into a road the model did not predict.
|
||||
end=1
|
||||
while end<len(x) and x[end]>x[end-1]+1e-4:end+=1
|
||||
x,y=x[:end],y[:end]
|
||||
positive=x>=0
|
||||
x,y=x[positive],y[positive]
|
||||
if len(x)<2 or x[-1]<3:
|
||||
raise ValueError('Current forward path shorter than three metres')
|
||||
# At queue speed the model intentionally reports a short horizon. Use
|
||||
# the measured endpoint with the existing extent-gain damping; never
|
||||
# accept that shortened horizon at normal road speed.
|
||||
if x[-1] < 6 and speed_mps > 7.:
|
||||
raise ValueError('Current forward path shorter than six metres')
|
||||
requested=max(minimum_m,min(maximum_m,speed_mps*lookahead_s))
|
||||
distance=min(requested,float(x[-1]))
|
||||
lateral=float(np.interp(distance,x,y))
|
||||
curvature=2*lateral/(distance*distance+lateral*lateral)
|
||||
# A short forecast has less information, not permission for the much
|
||||
# stronger correction produced by shrinking the pursuit denominator.
|
||||
# Dampen its command; do not invent a point beyond the available path.
|
||||
extent_scale=min(1.,(distance/requested)**2)
|
||||
return dict(available=True,curvature=curvature,raw_axis=-curvature/gain*extent_scale,
|
||||
undamped_axis=-curvature/gain,extent_gain_scale=extent_scale,
|
||||
lookahead_m=distance,requested_lookahead_m=requested,
|
||||
path_extent_m=float(x[-1]),lookahead_limited=distance<requested,
|
||||
target_lateral_m=lateral,source='current-model-path-pure-pursuit')
|
||||
except (AttributeError,TypeError,ValueError,IndexError) as exc:
|
||||
return dict(available=False,reason=str(exc))
|
||||
|
||||
|
||||
def preview_curve_speed(plan,lateral_accel=2.,deceleration=1.5):
|
||||
"""Current speed bound for bends in the covered path, without extrapolation."""
|
||||
try:
|
||||
x,y=np.asarray(plan.x,dtype=float),np.asarray(plan.y,dtype=float)
|
||||
if any(a.shape!=(33,) or not np.isfinite(a).all() for a in (x,y)):
|
||||
raise ValueError('Invalid current path')
|
||||
end=1
|
||||
while end<len(x) and x[end]>x[end-1]+1e-4:end+=1
|
||||
x,y=x[:end],y[:end]
|
||||
if x[0]>10 or x[-1]<30:raise ValueError('Insufficient covered curve preview')
|
||||
samples=np.arange(10.,min(100.,x[-1])+1e-6,10.)
|
||||
points=np.column_stack((samples,np.interp(samples,x,y)))
|
||||
best=None
|
||||
for a,b,c in zip(points,points[1:],points[2:]):
|
||||
ab,ac,bc=b-a,c-a,c-b
|
||||
denom=np.linalg.norm(ab)*np.linalg.norm(ac)*np.linalg.norm(bc)
|
||||
curvature=abs(2*(ab[0]*ac[1]-ab[1]*ac[0])/denom)
|
||||
if curvature<1e-4:continue
|
||||
curve_mps=math.sqrt(lateral_accel/curvature)
|
||||
allowed_mps=math.sqrt(curve_mps**2+2*deceleration*float(b[0]))
|
||||
if best is None or allowed_mps<best['speed_limit_mph'] / 2.2369362921:
|
||||
best=dict(speed_limit_mph=allowed_mps*2.2369362921,
|
||||
bend_distance_m=float(b[0]),curvature=curvature,
|
||||
bend_speed_mph=curve_mps*2.2369362921)
|
||||
return dict(available=True,covered_distance_m=float(samples[-1]),
|
||||
braking_budget_mps2=deceleration,**(best or dict(speed_limit_mph=None)))
|
||||
except (AttributeError,TypeError,ValueError,IndexError) as exc:
|
||||
return dict(available=False,reason=str(exc),speed_limit_mph=None)
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Pure admission policy for a limited simulator steering experiment.
|
||||
|
||||
This module has no actuator access. Its descriptive 579 inverse gain is not a
|
||||
steering-angle calibration, and admission never grants production eligibility.
|
||||
The caller owns foreground/operator cancellation and actual release/measurement.
|
||||
"""
|
||||
import math
|
||||
import numbers
|
||||
import time
|
||||
|
||||
|
||||
def _finite(value):
|
||||
if isinstance(value, bool) or not isinstance(value, numbers.Real):
|
||||
return None
|
||||
value = float(value)
|
||||
return value if math.isfinite(value) else None
|
||||
|
||||
|
||||
class PopSteeringTrial:
|
||||
MAX_ACTIVE_S = 15.
|
||||
MIN_SPEED_MPH = 24.
|
||||
MAX_SPEED_MPH = 28.
|
||||
MIN_AXIS = -.05
|
||||
MAX_AXIS = .03
|
||||
RATE_PER_S = .1
|
||||
DESCRIPTIVE_579_GAIN = .1254
|
||||
MAX_AGE_S = .15
|
||||
ADMISSION_EDGE_STD_M = 1.5
|
||||
CONTINUE_EDGE_STD_M = 1.75
|
||||
|
||||
def __init__(self):
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self._armed = False
|
||||
self._started = None
|
||||
self._finished = False
|
||||
self._finish_reason = ''
|
||||
self._last_stamp = None
|
||||
self._last_sdk = None
|
||||
self._last_sdk_change = None
|
||||
self._last_output_time = None
|
||||
self._axis = 0.
|
||||
|
||||
def _result(self, reason='', allowed=False, axis=0., **extra):
|
||||
return dict(allowed_for_test=allowed, requested_axis=axis, reason=reason,
|
||||
limited_simulator_experiment=True, production_eligible=False,
|
||||
calibration=False, physical_calibration_validated=False,
|
||||
controls_applied=False, pedals_commanded=False,
|
||||
route_competence_validated=False, intersection_competence_validated=False,
|
||||
active_since_monotonic=self._started, max_active_s=self.MAX_ACTIVE_S,
|
||||
descriptive_inverse_gain=self.DESCRIPTIVE_579_GAIN,
|
||||
admission_edge_std_limit_m=self.ADMISSION_EDGE_STD_M,
|
||||
continuation_edge_std_limit_m=self.CONTINUE_EDGE_STD_M,
|
||||
phase_edge_std_limit_m=(self.CONTINUE_EDGE_STD_M if self._started is not None
|
||||
else self.ADMISSION_EDGE_STD_M),
|
||||
edge_hysteresis_scope='limited active simulator trial only',
|
||||
permitted_axis_range=[self.MIN_AXIS, self.MAX_AXIS], **extra)
|
||||
|
||||
def finish(self, reason='Operator finished trial'):
|
||||
self._finished = True
|
||||
self._armed = False
|
||||
self._finish_reason = reason
|
||||
self._axis = 0.
|
||||
return self._result(reason)
|
||||
|
||||
def _sdk_reason(self, data, camera_guard):
|
||||
if not isinstance(camera_guard, dict) or camera_guard.get('valid') is not True:
|
||||
return 'Valid baseline camera guard required'
|
||||
if not isinstance(data, dict) or data.get('valid') is not True or data.get('paused') is not False:
|
||||
return 'Fresh unpaused SDK required'
|
||||
if data.get('truck_name') != '579':
|
||||
return 'This limited experiment is restricted to truck 579'
|
||||
stamp = data.get('timestamp')
|
||||
if isinstance(stamp, bool) or not isinstance(stamp, int) or stamp <= 0:
|
||||
return 'Positive SDK timestamp required'
|
||||
age = _finite(data.get('age'))
|
||||
if age is None or not 0 <= age <= self.MAX_AGE_S:
|
||||
return 'SDK age exceeds the experiment freshness bound'
|
||||
if _finite(data.get('speed_mps')) is None:
|
||||
return 'Finite SDK speed required'
|
||||
return ''
|
||||
|
||||
def arm(self, telemetry, camera_guard, now=None):
|
||||
now = _finite(time.monotonic() if now is None else now)
|
||||
if self._started is not None or self._finished:
|
||||
return self._result('Explicit reset and parked rearm required for another trial')
|
||||
reason = self._sdk_reason(telemetry, camera_guard)
|
||||
if not reason and now is None:
|
||||
reason = 'Finite monotonic time required'
|
||||
if not reason and (telemetry.get('park_brake') is not True or telemetry.get('gear') != 0
|
||||
or abs(telemetry['speed_mps']) > .05):
|
||||
reason = 'Parked stationary neutral startup required'
|
||||
if not reason:
|
||||
for key in ('user_steering', 'user_throttle', 'user_brake'):
|
||||
value = _finite(telemetry.get(key))
|
||||
if value is None or abs(value) > .02:
|
||||
reason = 'Neutral manual inputs required before arming'
|
||||
break
|
||||
self._armed = not reason
|
||||
return self._result(reason or 'Parked baseline armed; no steering requested', armed=self._armed)
|
||||
|
||||
def start(self, now=None):
|
||||
now = _finite(time.monotonic() if now is None else now)
|
||||
if not self._armed or self._finished or self._started is not None or now is None:
|
||||
return self._result('A parked arm and a single explicit start are required')
|
||||
self._started = now
|
||||
self._last_output_time = now
|
||||
return self._result('Limited experiment clock started; awaiting guarded model frame', started=True)
|
||||
|
||||
def _moving_reason(self, data, decision, model_action, camera_guard, now):
|
||||
reason = self._sdk_reason(data, camera_guard)
|
||||
if reason:
|
||||
return reason
|
||||
if now is None:
|
||||
return 'Finite monotonic time required'
|
||||
gear = data.get('gear')
|
||||
if (isinstance(gear, bool) or not isinstance(gear, int) or gear <= 0
|
||||
or data.get('park_brake') is not False or data.get('engine_enabled') is not True):
|
||||
return 'Forward gear, released parking brake and running engine required'
|
||||
mph = data['speed_mps'] * 2.2369362921
|
||||
if not self.MIN_SPEED_MPH <= mph <= self.MAX_SPEED_MPH:
|
||||
return 'Limited experiment speed must remain within 24–28 mph'
|
||||
if (data.get('model_obstructed') is not False or data.get('model_geometry_stale') is not False
|
||||
or data.get('model_inferred_this_frame') is not True):
|
||||
return 'Fresh unobstructed inferred model frame required'
|
||||
age = _finite(data.get('model_age_s'))
|
||||
stamp = _finite(data.get('model_input_monotonic'))
|
||||
if (age is None or not 0 <= age <= self.MAX_AGE_S or stamp is None
|
||||
or not 0 <= now-stamp <= self.MAX_AGE_S):
|
||||
return 'Model frame exceeds the experiment freshness bound'
|
||||
coverage = data.get('model_temporal_coverage')
|
||||
if (not isinstance(coverage, dict) or coverage.get('complete') is not True
|
||||
or coverage.get('feature_slots_present') != 25
|
||||
or coverage.get('feature_slots_required') != 25
|
||||
or coverage.get('narrow_pair_present') is not True
|
||||
or coverage.get('wide_pair_present') is not True):
|
||||
return 'Complete actual paired Pop temporal coverage required'
|
||||
if (not isinstance(decision, dict) or decision.get('allowed') is not True
|
||||
or decision.get('steering_strategy') != 'model-yaw-action'):
|
||||
detail = decision.get('reason') if isinstance(decision, dict) else None
|
||||
return ('Trajectory not ready: ' + detail if isinstance(detail, str) and detail
|
||||
else 'Current modern-action trajectory quality must be allowed by the core')
|
||||
uncertainty = decision.get('uncertainty')
|
||||
edge_max = _finite(uncertainty.get('max_edge_lateral_std_m')) if isinstance(uncertainty, dict) else None
|
||||
configured_limit = _finite(uncertainty.get('edge_std_limit_m')) if isinstance(uncertainty, dict) else None
|
||||
phase_cap = self.CONTINUE_EDGE_STD_M if self._started is not None else self.ADMISSION_EDGE_STD_M
|
||||
if (edge_max is None or edge_max < 0 or configured_limit is None or configured_limit <= 0
|
||||
or edge_max > phase_cap or configured_limit > phase_cap or edge_max > configured_limit):
|
||||
return 'Road-edge uncertainty/configured limit exceeds the trial phase bound or is unavailable'
|
||||
context = decision.get('context')
|
||||
if not isinstance(context, dict) or context.get('model_input_monotonic') != stamp:
|
||||
return 'Core quality decision must match this exact model frame'
|
||||
if (not isinstance(model_action, dict) or model_action.get('available') is not True
|
||||
or model_action.get('should_stop') is not False):
|
||||
return 'Available modern action with no stop request required'
|
||||
curvature = _finite(model_action.get('desired_curvature'))
|
||||
acceleration = _finite(model_action.get('desired_acceleration'))
|
||||
core_curve = _finite(decision.get('curvature'))
|
||||
if curvature is None or acceleration is None or core_curve is None:
|
||||
return 'Finite modern action and matching core curvature required'
|
||||
if not math.isclose(core_curve, -curvature, rel_tol=1e-9, abs_tol=1e-12):
|
||||
return 'Core curvature does not match the modern right-positive action'
|
||||
target = -curvature / self.DESCRIPTIVE_579_GAIN
|
||||
if not self.MIN_AXIS <= target <= self.MAX_AXIS:
|
||||
return 'Requested axis outside [-0.05, 0.03]; the experiment rejects rather than clips'
|
||||
return ''
|
||||
|
||||
def preflight(self, telemetry, decision, model_action, camera_guard, now=None):
|
||||
now = _finite(time.monotonic() if now is None else now)
|
||||
if not self._armed or self._finished or self._started is not None:
|
||||
return self._result('Parked arm required before moving preflight')
|
||||
reason = self._moving_reason(telemetry, decision, model_action, camera_guard, now)
|
||||
return self._result(reason or 'Moving preflight eligible; no controls requested',
|
||||
allowed=not reason, preflight_only=True)
|
||||
|
||||
def assess(self, telemetry, decision, model_action, camera_guard, now=None):
|
||||
now = _finite(time.monotonic() if now is None else now)
|
||||
if self._finished or self._started is None:
|
||||
return self._result(self._finish_reason or 'Explicit start required')
|
||||
if now is None or now < self._started or now-self._started >= self.MAX_ACTIVE_S:
|
||||
return self.finish('Limited experiment time expired or clock invalid')
|
||||
reason = self._moving_reason(telemetry, decision, model_action, camera_guard, now)
|
||||
if reason:
|
||||
return self.finish(reason)
|
||||
stamp = float(telemetry['model_input_monotonic'])
|
||||
if self._last_stamp is not None:
|
||||
if stamp <= self._last_stamp:
|
||||
return self.finish('Duplicate or out-of-order model input frame')
|
||||
if stamp-self._last_stamp > self.MAX_AGE_S + 1e-12:
|
||||
return self.finish('Model frame gap exceeds .15 seconds')
|
||||
sdk = telemetry['timestamp']
|
||||
if self._last_sdk is not None and sdk < self._last_sdk:
|
||||
return self.finish('SDK timestamp reset during the trial')
|
||||
if sdk != self._last_sdk:
|
||||
self._last_sdk_change = now
|
||||
elif now-self._last_sdk_change > self.MAX_AGE_S:
|
||||
return self.finish('SDK distinct samples stalled during the trial')
|
||||
dt = now-self._last_output_time
|
||||
if dt < 0 or dt > self.MAX_AGE_S + 1e-12:
|
||||
return self.finish('Active output cadence exceeds .15 seconds')
|
||||
target = -float(model_action['desired_curvature']) / self.DESCRIPTIVE_579_GAIN
|
||||
change = self.RATE_PER_S * dt
|
||||
axis = min(self._axis+change, max(self._axis-change, target))
|
||||
self._last_stamp, self._last_sdk = stamp, sdk
|
||||
self._last_output_time, self._axis = now, axis
|
||||
return self._result('Guarded limited simulator steering experiment', allowed=True, axis=axis,
|
||||
target_axis=target, elapsed_active_s=now-self._started,
|
||||
model_input_monotonic=stamp, desired_curvature_right_positive=model_action['desired_curvature'])
|
||||
@@ -0,0 +1,230 @@
|
||||
"""Passive Pop trajectory admission and steering preview; no actuator access.
|
||||
|
||||
Defaults are conservative simulator preview assumptions, not calibrated road
|
||||
confidence or an approval for driving. The edge envelope and uncertainty are
|
||||
network predictions. Physical extrinsics and upstream cadence remain unverified.
|
||||
"""
|
||||
import math
|
||||
import numbers
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
|
||||
from model.perception import X_IDXS
|
||||
|
||||
|
||||
def _number(value):
|
||||
if isinstance(value, bool) or not isinstance(value, numbers.Real):
|
||||
return None
|
||||
try:
|
||||
value = float(value)
|
||||
except (ValueError, OverflowError):
|
||||
return None
|
||||
return value if math.isfinite(value) else None
|
||||
|
||||
|
||||
class PopTrajectoryController:
|
||||
"""Assess fresh local geometry and output a bounded *unapplied* preview.
|
||||
|
||||
Path-center clearance is .35m plus one predicted standard deviation from
|
||||
each path/edge. This is not a truck swept-volume or collision check. A
|
||||
.75m path-std ceiling and 1.5m edge-std ceiling are preview rejection bounds.
|
||||
Three frames and .2s are required to establish stable observations. The
|
||||
.25 steering cap and .4 units/s rate limit do not validate vehicle response.
|
||||
"""
|
||||
def __init__(self, *, path_std_limit_m=.75, edge_std_limit_m=1.5,
|
||||
corridor_margin_m=.35, uncertainty_sigma=1.,
|
||||
steering_cap=.25, steering_rate_per_s=.4,
|
||||
target_change_limit=.12, warmup_frames=3, warmup_s=.2,
|
||||
max_frame_age_s=.2, max_frame_gap_s=.2,
|
||||
max_speed_mph=30., advisory_lateral_accel_mps2=1.):
|
||||
values = (path_std_limit_m, edge_std_limit_m, corridor_margin_m,
|
||||
uncertainty_sigma, steering_cap, steering_rate_per_s,
|
||||
target_change_limit, warmup_s, max_frame_age_s,
|
||||
max_frame_gap_s, max_speed_mph, advisory_lateral_accel_mps2)
|
||||
if any(_number(v) is None or v <= 0 for v in values):
|
||||
raise ValueError('Invalid trajectory preview limits')
|
||||
if (isinstance(warmup_frames, bool) or not isinstance(warmup_frames, int)
|
||||
or warmup_frames < 3 or steering_cap > .35 or max_speed_mph > 30):
|
||||
raise ValueError('Invalid trajectory preview bounds')
|
||||
self.path_std_limit_m = float(path_std_limit_m)
|
||||
self.edge_std_limit_m = float(edge_std_limit_m)
|
||||
self.corridor_margin_m = float(corridor_margin_m)
|
||||
self.uncertainty_sigma = float(uncertainty_sigma)
|
||||
self.steering_cap = float(steering_cap)
|
||||
self.steering_rate_per_s = float(steering_rate_per_s)
|
||||
self.target_change_limit = float(target_change_limit)
|
||||
self.warmup_frames, self.warmup_s = warmup_frames, float(warmup_s)
|
||||
self.max_frame_age_s, self.max_frame_gap_s = float(max_frame_age_s), float(max_frame_gap_s)
|
||||
self.max_speed_mph = float(max_speed_mph)
|
||||
self.advisory_lateral_accel_mps2 = float(advisory_lateral_accel_mps2)
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self._last_seen = None
|
||||
self._clear_tracking()
|
||||
|
||||
def _clear_tracking(self):
|
||||
self._stable_since = None
|
||||
self._stable_frames = 0
|
||||
self._previous_target = None
|
||||
self._previous_steer = 0.
|
||||
self._previous_output_time = None
|
||||
|
||||
def assess(self, perception, speed_mps, telemetry, now=None, model_action=None):
|
||||
now = time.monotonic() if now is None else now
|
||||
result = dict(allowed=False, steer=0., target_steer=None, curvature=None,
|
||||
max_speed_mph=None, reason='', controls_applied=False,
|
||||
control_eligible=False, preview_only=True,
|
||||
physical_calibration_validated=False,
|
||||
upstream_cadence_validated=False,
|
||||
path_std_max_m=None, road_edge_std_max_m=None, lookahead_m=None,
|
||||
local_path={}, uncertainty={}, corridor={}, context={}, stability={},
|
||||
steering_strategy='position-preview', desired_acceleration=None, should_stop=None)
|
||||
|
||||
def reject(reason):
|
||||
self._clear_tracking()
|
||||
result['reason'] = reason
|
||||
return result
|
||||
|
||||
now, speed = _number(now), _number(speed_mps)
|
||||
if now is None or speed is None or speed < .5 or speed * 2.2369362921 > self.max_speed_mph:
|
||||
return reject('Invalid or unsupported preview speed/time')
|
||||
if not isinstance(telemetry, dict):
|
||||
return reject('Missing fresh model telemetry')
|
||||
if telemetry.get('valid') is not True or telemetry.get('paused') is not False:
|
||||
return reject('SDK unavailable or paused')
|
||||
if (telemetry.get('model_obstructed') is not False
|
||||
or telemetry.get('model_geometry_stale') is not False
|
||||
or telemetry.get('model_inferred_this_frame') is not True):
|
||||
return reject('Fresh unobstructed model geometry required')
|
||||
obstruction = telemetry.get('camera_obstruction')
|
||||
if obstruction is not None and (not isinstance(obstruction, dict)
|
||||
or obstruction.get('checked') is not True or obstruction.get('blocked') is not False):
|
||||
return reject('Camera obstruction check unavailable or blocked')
|
||||
age = _number(telemetry.get('model_age_s'))
|
||||
stamp = _number(telemetry.get('model_input_monotonic'))
|
||||
if (age is None or age < 0 or age > self.max_frame_age_s or stamp is None
|
||||
or now - stamp > self.max_frame_age_s or stamp - now > .05):
|
||||
return reject('Model frame timestamp is missing or stale')
|
||||
coverage = telemetry.get('model_temporal_coverage')
|
||||
if (not isinstance(coverage, dict) or coverage.get('complete') is not True
|
||||
or coverage.get('feature_slots_present') != 25
|
||||
or coverage.get('feature_slots_required') != 25
|
||||
or coverage.get('narrow_pair_present') is not True
|
||||
or (coverage.get('wide_pair_required') is True
|
||||
and coverage.get('wide_pair_present') is not True)):
|
||||
return reject('Complete actual model temporal coverage required')
|
||||
result['context'] = dict(coverage, model_input_monotonic=stamp, model_age_s=age)
|
||||
if self._last_seen is not None and stamp <= self._last_seen:
|
||||
return reject('Duplicate or out-of-order model frame')
|
||||
gap = stamp - self._last_seen if self._last_seen is not None else None
|
||||
self._last_seen = stamp
|
||||
if gap is not None and gap > self.max_frame_gap_s:
|
||||
return reject('Model inference gap; stable preview must rewarm')
|
||||
result['context']['frame_gap_s'] = gap
|
||||
|
||||
plan = getattr(perception, 'plan', None)
|
||||
try:
|
||||
x, y, z = (np.asarray(getattr(plan, name), dtype=float) for name in ('x', 'y', 'z'))
|
||||
std = np.asarray(perception.plan_std, dtype=float)
|
||||
edges = np.asarray(perception.road_edges, dtype=float)
|
||||
edge_std = np.asarray(perception.road_edge_std, dtype=float)
|
||||
edge_x = np.asarray(getattr(perception, 'road_edge_x', X_IDXS), dtype=float)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
return reject('Missing trajectory or road-edge uncertainty evidence')
|
||||
if (any(a.shape != (33,) or not np.all(np.isfinite(a)) for a in (x, y, z))
|
||||
or std.shape != (33, 15) or not np.all(np.isfinite(std)) or np.any(std < 0)
|
||||
or edges.shape != (2, 33, 2) or not np.all(np.isfinite(edges))
|
||||
or edge_std.shape != (2, 33, 2) or not np.all(np.isfinite(edge_std))
|
||||
or np.any(edge_std < 0) or edge_x.shape != (33,)
|
||||
or not np.all(np.isfinite(edge_x)) or np.any(np.diff(edge_x) <= 0)):
|
||||
return reject('Invalid trajectory or road-edge arrays')
|
||||
lookahead = float(np.clip(speed * 1.5, 8., 25.))
|
||||
result['lookahead_m'] = lookahead
|
||||
horizon = lookahead + 2.
|
||||
breaks = np.flatnonzero(np.diff(x) <= 0)
|
||||
prefix_count = int(breaks[0]) + 1 if len(breaks) else 33
|
||||
px, py, ps = x[:prefix_count], y[:prefix_count], std[:prefix_count, 1]
|
||||
result['local_path'] = dict(lookahead_m=lookahead, required_horizon_m=horizon,
|
||||
prefix_points=prefix_count,
|
||||
prefix_end_x_m=float(px[-1]),
|
||||
future_x_reversal=bool(len(breaks)),
|
||||
velocity_evidence_present=getattr(plan, 'velocity', None) is not None,
|
||||
stop_intent_assessed=False)
|
||||
if abs(x[0]) > 2 or prefix_count < 2 or px[-1] < horizon or x[0] > 1:
|
||||
return reject('Ascending local trajectory does not cover steering horizon')
|
||||
start = max(0., float(px[0]))
|
||||
grid = np.unique(np.concatenate(([start, lookahead, horizon],
|
||||
px[(px >= start) & (px <= horizon)],
|
||||
edge_x[(edge_x >= start) & (edge_x <= horizon)])))
|
||||
if edge_x[0] > start or edge_x[-1] < horizon:
|
||||
return reject('Road edges do not cover local steering horizon')
|
||||
path_y, path_std = np.interp(grid, px, py), np.interp(grid, px, ps)
|
||||
left = np.interp(grid, edge_x, edges[0, :, 0])
|
||||
right = np.interp(grid, edge_x, edges[1, :, 0])
|
||||
left_std = np.interp(grid, edge_x, edge_std[0, :, 0])
|
||||
right_std = np.interp(grid, edge_x, edge_std[1, :, 0])
|
||||
result['uncertainty'] = dict(max_path_lateral_std_m=float(path_std.max()),
|
||||
max_edge_lateral_std_m=float(max(left_std.max(), right_std.max())),
|
||||
path_std_limit_m=self.path_std_limit_m,
|
||||
edge_std_limit_m=self.edge_std_limit_m,
|
||||
probability_assessed=False)
|
||||
result['path_std_max_m'] = float(path_std.max())
|
||||
result['road_edge_std_max_m'] = float(max(left_std.max(), right_std.max()))
|
||||
if np.any(left >= right):
|
||||
return reject('Road edges are unordered in the local horizon')
|
||||
if path_std.max() > self.path_std_limit_m:
|
||||
return reject('Local path uncertainty exceeds preview bound')
|
||||
if max(left_std.max(), right_std.max()) > self.edge_std_limit_m:
|
||||
return reject('Local road-edge uncertainty exceeds preview bound')
|
||||
lower = left + self.corridor_margin_m + self.uncertainty_sigma * (left_std + path_std)
|
||||
upper = right - self.corridor_margin_m - self.uncertainty_sigma * (right_std + path_std)
|
||||
left_clearance, right_clearance = path_y - lower, upper - path_y
|
||||
result['corridor'] = dict(source='model road edges; estimated, uncalibrated',
|
||||
margin_m=self.corridor_margin_m, uncertainty_sigma=self.uncertainty_sigma,
|
||||
min_left_clearance_m=float(left_clearance.min()),
|
||||
min_right_clearance_m=float(right_clearance.min()),
|
||||
truck_swept_volume_assessed=False, traffic_assessed=False)
|
||||
if np.any(lower >= upper) or np.any(left_clearance < 0) or np.any(right_clearance < 0):
|
||||
return reject('Local path is outside the uncertainty-adjusted road envelope')
|
||||
lateral = -float(np.interp(lookahead, px, py))
|
||||
curvature = 2 * lateral / (lookahead * lookahead + lateral * lateral)
|
||||
if model_action is not None:
|
||||
if not isinstance(model_action, dict) or model_action.get('available') is not True:
|
||||
return reject('Complete modern model action required')
|
||||
model_curvature = _number(model_action.get('desired_curvature'))
|
||||
acceleration = _number(model_action.get('desired_acceleration'))
|
||||
if model_curvature is None or acceleration is None or type(model_action.get('should_stop')) is not bool:
|
||||
return reject('Invalid modern model action')
|
||||
# Modern yaw curvature is positive right; the ATS axis is positive left.
|
||||
curvature = -model_curvature
|
||||
result.update(steering_strategy='model-yaw-action',
|
||||
desired_acceleration=acceleration, should_stop=model_action['should_stop'],
|
||||
model_action=model_action)
|
||||
target = float(np.clip(math.atan(curvature * 4.5) / math.radians(35),
|
||||
-self.steering_cap, self.steering_cap))
|
||||
curve_speed = (math.sqrt(self.advisory_lateral_accel_mps2 / abs(curvature)) * 2.2369362921
|
||||
if abs(curvature) > 1e-8 else self.max_speed_mph)
|
||||
result.update(target_steer=target, curvature=curvature,
|
||||
max_speed_mph=min(self.max_speed_mph, curve_speed),
|
||||
speed_advisory_semantics='curvature-only; unassessed vehicle/road dynamics, not a speed command')
|
||||
if self._previous_target is not None and abs(target - self._previous_target) > self.target_change_limit:
|
||||
return reject('Trajectory steering target changed abruptly; rewarm')
|
||||
if self._stable_since is None:
|
||||
self._stable_since = stamp
|
||||
self._stable_frames += 1
|
||||
self._previous_target = target
|
||||
stable_s = stamp - self._stable_since
|
||||
result['stability'] = dict(unique_frames=self._stable_frames, duration_s=stable_s,
|
||||
required_frames=self.warmup_frames, required_duration_s=self.warmup_s)
|
||||
if self._stable_frames < self.warmup_frames or stable_s + 1e-9 < self.warmup_s:
|
||||
result['reason'] = 'Warming stable local trajectory preview'
|
||||
return result
|
||||
output_dt = (stamp - self._previous_output_time
|
||||
if self._previous_output_time is not None else min(gap or 0., self.max_frame_gap_s))
|
||||
change = self.steering_rate_per_s * max(0., output_dt)
|
||||
steer = float(np.clip(target, self._previous_steer - change, self._previous_steer + change))
|
||||
self._previous_steer, self._previous_output_time = steer, stamp
|
||||
result.update(allowed=True, steer=steer, reason='Stable bounded trajectory preview; active control remains ineligible')
|
||||
return result
|
||||
@@ -0,0 +1,41 @@
|
||||
"""One model-intent pulse per turn signal, solely for passive evaluation.
|
||||
|
||||
Inspired by IQ.Pilot's delay/consumed/cancel behavior. This does not establish
|
||||
adjacent-lane clearance, monitor blind spots, or command a lane change.
|
||||
"""
|
||||
import math
|
||||
|
||||
|
||||
class SignalPreview:
|
||||
def __init__(self, delay=1.0):
|
||||
if delay not in (0.05, 0.5, 1.0, 2.0, 3.0):
|
||||
raise ValueError("Unsupported signal delay")
|
||||
self.delay = delay
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.direction = "none"
|
||||
self.started = None
|
||||
self.used = False
|
||||
|
||||
def update(self, data, now):
|
||||
left, right = data.get('blinker_left', False), data.get('blinker_right', False)
|
||||
direction = 'left' if left and not right else 'right' if right and not left else 'none'
|
||||
if (not data.get('valid') or data.get('paused') or direction == 'none'
|
||||
or data.get('hazards') or not math.isfinite(now)):
|
||||
self.reset()
|
||||
return 'none'
|
||||
if direction != self.direction:
|
||||
self.direction, self.started, self.used = direction, now, False
|
||||
if now < self.started:
|
||||
self.reset()
|
||||
return 'none'
|
||||
# Braking cancels the current signal even if it is subsequently released.
|
||||
if data.get('user_brake', 0) > 0.05 or data.get('park_brake'):
|
||||
self.used = True
|
||||
speed = data.get('speed_mph', 0)
|
||||
if (not self.used and math.isfinite(speed) and speed >= 10
|
||||
and now-self.started >= self.delay):
|
||||
self.used = True
|
||||
return direction
|
||||
return 'none'
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Client for the in-game SPF semantic input bridge.
|
||||
|
||||
The bridge is optional and Windows-only. Importing this module on another
|
||||
platform remains safe; construction reports that the bridge is unavailable.
|
||||
"""
|
||||
import ctypes
|
||||
import math
|
||||
import time
|
||||
|
||||
MAPPING_NAME = 'Local\\ATSNativeInput'
|
||||
FRAME_SIZE = 64
|
||||
MAGIC = b'ATSINP01'
|
||||
VERSION = 1
|
||||
|
||||
|
||||
def command_axes(steering, action, intensity):
|
||||
"""Convert native positive-left commands to SPF semantic axes.
|
||||
|
||||
SPF's semantic ``steer`` axis uses the same positive-left convention as
|
||||
the native planner. The earlier bridge inverted this value based on the
|
||||
ETS2LA/vJoy convention; live ATS feedback showed that made every lane
|
||||
correction turn the semi away from its lane centre.
|
||||
"""
|
||||
values = [steering, intensity]
|
||||
if any(not isinstance(v, (int, float)) or not math.isfinite(float(v)) for v in values):
|
||||
raise ValueError('Non-finite SPF input')
|
||||
if action not in ('throttle', 'brake', 'coast'):
|
||||
raise ValueError('Unknown SPF pedal action')
|
||||
duty = max(0., min(1., float(intensity)))
|
||||
return (max(-1., min(1., float(steering))),
|
||||
duty if action == 'throttle' else 0.,
|
||||
duty if action == 'brake' else 0.)
|
||||
|
||||
|
||||
class _Frame(ctypes.Structure):
|
||||
_pack_ = 1
|
||||
_fields_ = [('magic', ctypes.c_char * 8), ('version', ctypes.c_uint32),
|
||||
('size', ctypes.c_uint32), ('sequence', ctypes.c_uint64),
|
||||
('steering', ctypes.c_float), ('throttle', ctypes.c_float),
|
||||
('brake', ctypes.c_float), ('left_pulse', ctypes.c_uint32),
|
||||
('right_pulse', ctypes.c_uint32), ('flags', ctypes.c_uint32),
|
||||
('reserved', ctypes.c_uint8 * 16)]
|
||||
|
||||
|
||||
assert ctypes.sizeof(_Frame) == FRAME_SIZE
|
||||
|
||||
|
||||
class SPFNativeController:
|
||||
"""Shared-memory writer with an SPF plugin acknowledgement handshake."""
|
||||
def __init__(self):
|
||||
if not hasattr(ctypes, 'WinDLL'):
|
||||
raise OSError('SPF native input requires Windows')
|
||||
self.kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
|
||||
self.kernel32.CreateFileMappingW.argtypes = [ctypes.c_void_p, ctypes.c_void_p,
|
||||
ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_wchar_p]
|
||||
self.kernel32.CreateFileMappingW.restype = ctypes.c_void_p
|
||||
self.kernel32.MapViewOfFile.argtypes = [ctypes.c_void_p, ctypes.c_uint32,
|
||||
ctypes.c_uint32, ctypes.c_uint32, ctypes.c_size_t]
|
||||
self.kernel32.MapViewOfFile.restype = ctypes.c_void_p
|
||||
self.kernel32.UnmapViewOfFile.argtypes = [ctypes.c_void_p]
|
||||
self.kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
|
||||
handle = self.kernel32.CreateFileMappingW(ctypes.c_void_p(-1), None, 0x04,
|
||||
0, FRAME_SIZE, MAPPING_NAME)
|
||||
if not handle:
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
address = self.kernel32.MapViewOfFile(handle, 0xF001F, 0, 0, FRAME_SIZE)
|
||||
if not address:
|
||||
self.kernel32.CloseHandle(handle)
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
self.handle, self.address = handle, address
|
||||
self.frame = _Frame.from_address(address)
|
||||
self.frame.magic = MAGIC
|
||||
self.frame.version = VERSION
|
||||
self.frame.size = FRAME_SIZE
|
||||
self.frame.flags = 1
|
||||
self.sequence = 0
|
||||
self.left_pulse = self.right_pulse = 0
|
||||
self.closed = False
|
||||
|
||||
def _write(self, steering, throttle, brake):
|
||||
self.sequence += 2
|
||||
self.frame.sequence = self.sequence - 1
|
||||
self.frame.steering = steering
|
||||
self.frame.throttle = throttle
|
||||
self.frame.brake = brake
|
||||
self.frame.left_pulse = self.left_pulse
|
||||
self.frame.right_pulse = self.right_pulse
|
||||
self.frame.flags = 1
|
||||
self.frame.sequence = self.sequence
|
||||
|
||||
def apply(self, steering, action, intensity):
|
||||
if self.closed:
|
||||
raise RuntimeError('SPF native input is closed')
|
||||
self._write(*command_axes(steering, action, intensity))
|
||||
|
||||
def pulse_signal(self, direction):
|
||||
if direction == 'left': self.left_pulse += 1
|
||||
elif direction == 'right': self.right_pulse += 1
|
||||
else: raise ValueError('Signal direction must be left or right')
|
||||
self._write(0., 0., 0.)
|
||||
|
||||
def probe(self, timeout=1.0):
|
||||
"""Return true only when an installed SPF plugin acknowledges a frame."""
|
||||
self.apply(0., 'coast', 0.)
|
||||
start = time.monotonic()
|
||||
while time.monotonic() - start < timeout:
|
||||
if self.frame.flags & 2:
|
||||
return True
|
||||
time.sleep(.01)
|
||||
return False
|
||||
|
||||
def neutral(self):
|
||||
if not self.closed: self._write(0., 0., 0.)
|
||||
|
||||
def close(self):
|
||||
if self.closed: return
|
||||
try: self.neutral()
|
||||
finally:
|
||||
self.kernel32.UnmapViewOfFile(self.address)
|
||||
self.kernel32.CloseHandle(self.handle)
|
||||
self.closed = True
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Verify analog input against live ATS telemetry with a stationary, parked truck."""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
from control.fsd_controller import FSDController
|
||||
from control.windows_input import ATSWindow, KeyboardInput
|
||||
from telemetry.ats_telemetry import ATSTelemetry
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def parked_reason(foreground, data):
|
||||
if not foreground:
|
||||
return "Bring ATS's driving view to the foreground"
|
||||
if not data.get("valid"):
|
||||
return data.get("reason", "Fresh telemetry is required")
|
||||
if not data.get("park_brake"):
|
||||
return "Set the parking brake for the input check"
|
||||
if data.get("gear") != 0 and data.get("engine_enabled") is not False:
|
||||
return "Select neutral or turn the engine off (E) for the input check"
|
||||
if not math.isfinite(data.get("speed_mps", float("nan"))) or abs(data["speed_mps"]) > 0.05:
|
||||
return "The truck must be stationary for the input check"
|
||||
return ""
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "diagnostics/vjoy-input-check.json")
|
||||
args = parser.parse_args()
|
||||
window, reader = ATSWindow(), ATSTelemetry()
|
||||
controller = None
|
||||
report = {"passed": False, "samples": [], "error": None}
|
||||
try:
|
||||
# Observe fresh timestamps before acquiring or altering the virtual device.
|
||||
data = reader.get_data()
|
||||
time.sleep(0.1)
|
||||
data = reader.get_data()
|
||||
reason = parked_reason(window.foreground(), data)
|
||||
if reason:
|
||||
raise RuntimeError(reason)
|
||||
baseline_head = data["head_rotation"]
|
||||
controller = FSDController(mode="vjoy", keyboard=KeyboardInput(window))
|
||||
steps = [("neutral", 0, "coast", 0), ("left", 0.2, "coast", 0),
|
||||
("right", -0.2, "coast", 0), ("throttle", 0, "throttle", 0.2),
|
||||
("brake", 0, "brake", 0.2), ("released", 0, "coast", 0)]
|
||||
for name, steering, action, intensity in steps:
|
||||
deadline = time.monotonic() + 0.7
|
||||
while time.monotonic() < deadline:
|
||||
data = reader.get_data()
|
||||
reason = parked_reason(window.foreground(), data)
|
||||
if reason:
|
||||
raise RuntimeError(reason)
|
||||
controller.apply_controls(steering, action, intensity, data["steering"])
|
||||
time.sleep(0.02)
|
||||
data = reader.get_data()
|
||||
reason = parked_reason(window.foreground(), data)
|
||||
if reason:
|
||||
raise RuntimeError(reason)
|
||||
observed = {k: data[k] for k in ("user_steering", "user_throttle", "user_brake", "steering", "speed_mps")}
|
||||
expected = (steering, intensity if action == "throttle" else 0,
|
||||
intensity if action == "brake" else 0)
|
||||
actual = (observed["user_steering"], observed["user_throttle"], observed["user_brake"])
|
||||
matches = all(math.isfinite(v) and abs(v - target) < 0.035 for v, target in zip(actual, expected))
|
||||
head_delta = max(abs(((v - start + 0.5) % 1.0) - 0.5)
|
||||
for v, start in zip(data["head_rotation"], baseline_head))
|
||||
sample = {"step": name, "expected": expected, "observed": observed,
|
||||
"camera_delta_turns": head_delta, "passed": matches and head_delta < 0.005}
|
||||
report["samples"].append(sample)
|
||||
print(json.dumps(sample))
|
||||
if not sample["passed"]:
|
||||
raise RuntimeError(f"{name}: ATS input does not match the command; check axis bindings/direction")
|
||||
report["passed"] = True
|
||||
except Exception as exc:
|
||||
report["error"] = str(exc)
|
||||
print("Input check stopped: " + str(exc))
|
||||
finally:
|
||||
try:
|
||||
if controller:
|
||||
try:
|
||||
controller.close()
|
||||
if report["passed"]:
|
||||
# The driver can reset axes after relinquishing ownership.
|
||||
# Verify actual ATS pedal release after that transition too.
|
||||
time.sleep(0.2)
|
||||
data = reader.get_data()
|
||||
reason = parked_reason(window.foreground(), data)
|
||||
released = all(math.isfinite(data.get(k, float("nan")))
|
||||
and abs(data[k]) < 0.035
|
||||
for k in ("user_steering", "user_throttle", "user_brake"))
|
||||
sample = {"step": "after_shutdown", "observed": {
|
||||
k: data.get(k) for k in ("user_steering", "user_throttle", "user_brake")},
|
||||
"passed": not reason and released}
|
||||
report["samples"].append(sample)
|
||||
if not sample["passed"]:
|
||||
report["passed"] = False
|
||||
report["error"] = reason or "ATS controls did not release after feeder shutdown"
|
||||
print(json.dumps(sample))
|
||||
except Exception as exc:
|
||||
report["passed"] = False
|
||||
report["error"] = "Could not release controls: " + str(exc)
|
||||
finally:
|
||||
reader.close()
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(json.dumps(report, indent=2), encoding="utf-8")
|
||||
print(f"Input check {'PASSED' if report['passed'] else 'NOT PASSED'}; report: {args.output}")
|
||||
return 0 if report["passed"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,187 @@
|
||||
"""vJoy cdecl SDK adapter: X steering, Y throttle, Z brake.
|
||||
|
||||
API contract: github.com/BrunnerInnovation/vJoy/SDK/inc/vjoyinterface.h.
|
||||
No driver is installed or device acquired merely by importing this module.
|
||||
"""
|
||||
import ctypes
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
X, Y, Z = 0x30, 0x31, 0x32
|
||||
DEVICE_STATUS_NAMES = {0: 'OWN', 1: 'FREE', 2: 'BUSY', 3: 'MISSING', 4: 'UNKNOWN'}
|
||||
|
||||
|
||||
def dll_path():
|
||||
# Python and DLL must have matching bitness. Prefer the installed SDK copy.
|
||||
arch = "x64" if ctypes.sizeof(ctypes.c_void_p) == 8 else "x86"
|
||||
roots = [Path(os.environ.get(name, default)) / "vJoy"
|
||||
for name, default in (("ProgramW6432", "C:/Program Files"),
|
||||
("ProgramFiles", "C:/Program Files"),
|
||||
("ProgramFiles(x86)", "C:/Program Files (x86)"))]
|
||||
for root in roots:
|
||||
for candidate in (root / arch / "vJoyInterface.dll",
|
||||
root / "SDK" / "lib" / arch / "vJoyInterface.dll"):
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def axis_value(low, high, fraction):
|
||||
if not math.isfinite(fraction):
|
||||
raise ValueError("Non-finite joystick input")
|
||||
return round(low + (high - low) * min(1.0, max(0.0, fraction)))
|
||||
|
||||
|
||||
def driver_diagnostics(device=1, dll=None):
|
||||
"""Read driver state without acquiring, relinquishing or writing a device.
|
||||
|
||||
vJoy's GetVJDStatus OWN=0 means ownership by this calling application,
|
||||
not merely that another feeder owns the device. GetOwnerPid is optional.
|
||||
"""
|
||||
report = dict(device=device, enabled=None, device_status=None,
|
||||
device_status_name='UNAVAILABLE', owner_pid=None)
|
||||
try:
|
||||
if dll is None:
|
||||
path = dll_path()
|
||||
if path is None:raise RuntimeError('vJoy interface DLL is unavailable')
|
||||
dll = ctypes.CDLL(str(path))
|
||||
for name, args in (('vJoyEnabled', []), ('GetVJDStatus', [ctypes.c_uint32])):
|
||||
function = getattr(dll, name)
|
||||
function.restype, function.argtypes = ctypes.c_int32, args
|
||||
report['enabled'] = bool(dll.vJoyEnabled())
|
||||
report['device_status'] = int(dll.GetVJDStatus(device))
|
||||
report['device_status_name'] = DEVICE_STATUS_NAMES.get(report['device_status'], 'UNKNOWN')
|
||||
owner = getattr(dll, 'GetOwnerPid', None)
|
||||
if owner is not None:
|
||||
owner.restype, owner.argtypes = ctypes.c_int32, [ctypes.c_uint32]
|
||||
report['owner_query_result'] = int(owner(device))
|
||||
if report['owner_query_result'] > 0:
|
||||
report['owner_pid'] = report['owner_query_result']
|
||||
except Exception as exc:
|
||||
report['diagnostic_error'] = str(exc)
|
||||
return report
|
||||
|
||||
|
||||
def _checked_library(device, dll):
|
||||
if not 1 <= device <= 16:
|
||||
raise ValueError("vJoy device must be 1 to 16")
|
||||
path = dll_path() if dll is None else None
|
||||
if dll is None and path is None:
|
||||
raise RuntimeError("Install signed vJoy and configure device 1 with X/Y/Z axes")
|
||||
dll = dll if dll is not None else ctypes.CDLL(str(path))
|
||||
signatures = {
|
||||
"vJoyEnabled": (ctypes.c_int32, []),
|
||||
"GetVJDStatus": (ctypes.c_int32, [ctypes.c_uint32]),
|
||||
"AcquireVJD": (ctypes.c_int32, [ctypes.c_uint32]),
|
||||
"RelinquishVJD": (None, [ctypes.c_uint32]),
|
||||
"GetVJDAxisExist": (ctypes.c_int32, [ctypes.c_uint32, ctypes.c_uint32]),
|
||||
"GetVJDAxisMin": (ctypes.c_int32, [ctypes.c_uint32, ctypes.c_uint32, ctypes.POINTER(ctypes.c_int32)]),
|
||||
"GetVJDAxisMax": (ctypes.c_int32, [ctypes.c_uint32, ctypes.c_uint32, ctypes.POINTER(ctypes.c_int32)]),
|
||||
"SetAxis": (ctypes.c_int32, [ctypes.c_int32, ctypes.c_uint32, ctypes.c_uint32]),
|
||||
}
|
||||
for name, (result, args) in signatures.items():
|
||||
function = getattr(dll, name)
|
||||
function.restype, function.argtypes = result, args
|
||||
if not dll.vJoyEnabled():
|
||||
raise RuntimeError("vJoy driver is disabled or unavailable")
|
||||
# This read does not reserve the device. Repeated before actual acquisition.
|
||||
if dll.GetVJDStatus(device) != 1:
|
||||
raise RuntimeError(f"vJoy device {device} is missing or already in use")
|
||||
ranges = {}
|
||||
for axis in (X, Y, Z):
|
||||
low, high = ctypes.c_int32(), ctypes.c_int32()
|
||||
if (not dll.GetVJDAxisExist(device, axis)
|
||||
or not dll.GetVJDAxisMin(device, axis, ctypes.byref(low))
|
||||
or not dll.GetVJDAxisMax(device, axis, ctypes.byref(high))
|
||||
or high.value <= low.value):
|
||||
raise RuntimeError("Configure vJoy device with X, Y and Z axes")
|
||||
ranges[axis] = (low.value, high.value)
|
||||
return dll, ranges
|
||||
|
||||
|
||||
def prepare_library(device=1, dll=None):
|
||||
"""Warm SDK capability queries and retain its handle without ownership/writes.
|
||||
|
||||
Call before model context begins. Passing the returned DLL to VirtualJoystick
|
||||
later repeats enabled/status/range validation and only then acquires it.
|
||||
"""
|
||||
return _checked_library(device, dll)[0]
|
||||
|
||||
|
||||
class VirtualJoystick:
|
||||
def __init__(self, device=1, dll=None):
|
||||
self.device = device
|
||||
self.acquired = False
|
||||
self.dll, self.ranges = _checked_library(device, dll)
|
||||
if not self.dll.AcquireVJD(device):
|
||||
raise RuntimeError(f"Could not acquire vJoy device {device}")
|
||||
self.acquired = True
|
||||
try:
|
||||
self.neutral()
|
||||
except Exception:
|
||||
self.dll.RelinquishVJD(device)
|
||||
self.acquired = False
|
||||
raise
|
||||
|
||||
def _set(self, axis, fraction):
|
||||
if not self.acquired:
|
||||
raise RuntimeError("vJoy device is closed")
|
||||
value = axis_value(*self.ranges[axis], fraction)
|
||||
if not self.dll.SetAxis(value, self.device, axis):
|
||||
state = driver_diagnostics(self.device, self.dll)
|
||||
retries = 0
|
||||
# A single repeat of the identical write is permitted only while
|
||||
# the SDK confirms this application still owns an enabled device.
|
||||
# Never reacquire or change a failed command's axis/value here.
|
||||
if (self.acquired and state['enabled'] is True
|
||||
and state['device_status'] == 0 and 'diagnostic_error' not in state):
|
||||
retries = 1
|
||||
if self.dll.SetAxis(value, self.device, axis):return
|
||||
state = driver_diagnostics(self.device, self.dll)
|
||||
raise OSError(f"vJoy rejected axis {axis:#x} (device={self.device}, value={value}, "
|
||||
f"enabled={state['enabled']}, device_status={state['device_status']} "
|
||||
f"{state['device_status_name']}, owner_pid={state['owner_pid']}, retries={retries}"
|
||||
+ (f", diagnostic_error={state['diagnostic_error']}" if 'diagnostic_error' in state else '') + ')')
|
||||
|
||||
def apply(self, steering, action, intensity):
|
||||
if not math.isfinite(steering) or not math.isfinite(intensity):
|
||||
raise ValueError("Non-finite joystick command")
|
||||
if action not in ("throttle", "brake", "coast"):
|
||||
raise ValueError("Unknown pedal action")
|
||||
# ATS positive steering is left: X decreases from center for a left turn.
|
||||
# ATS uses the positive half of each pedal axis: center is released.
|
||||
# vJoy returns to centered axes when no feeder owns the device.
|
||||
# Always release the opposite pedal before applying the requested pedal.
|
||||
pedal = 0.5 + min(1.0, max(0.0, intensity)) * 0.5
|
||||
if action == "throttle":
|
||||
self._set(Z, 0.5)
|
||||
self._set(Y, pedal)
|
||||
elif action == "brake":
|
||||
self._set(Y, 0.5)
|
||||
self._set(Z, pedal)
|
||||
else:
|
||||
self._set(Y, 0.5)
|
||||
self._set(Z, 0.5)
|
||||
self._set(X, (1.0 - min(1.0, max(-1.0, steering))) / 2.0)
|
||||
|
||||
def neutral(self):
|
||||
if not self.acquired:
|
||||
return
|
||||
# Try every release even when one axis call fails.
|
||||
error = None
|
||||
for axis, fraction in ((Y, 0.5), (Z, 0.5), (X, 0.5)):
|
||||
try:
|
||||
self._set(axis, fraction)
|
||||
except Exception as exc:
|
||||
error = error or exc
|
||||
if error:
|
||||
raise error
|
||||
|
||||
def close(self):
|
||||
if self.acquired:
|
||||
try:
|
||||
self.neutral()
|
||||
finally:
|
||||
self.dll.RelinquishVJD(self.device)
|
||||
self.acquired = False
|
||||
@@ -0,0 +1,322 @@
|
||||
"""Win32 input, ATS window discovery, and manual takeover monitoring."""
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import threading
|
||||
import time
|
||||
|
||||
INPUT_TAG = 0x41545346
|
||||
DWORD = ctypes.c_uint32
|
||||
ULONG_PTR = ctypes.c_size_t
|
||||
|
||||
|
||||
def configure_non_activating_window(title):
|
||||
"""Keep a diagnostic window from taking ATS foreground on mouse clicks.
|
||||
|
||||
The gameplay loop intentionally releases controls when ATS is not the
|
||||
foreground window. OpenCV's normal top-level window is otherwise able to
|
||||
steal that foreground when the user clicks the HUD, which looks like a
|
||||
random autopilot dropout. Applying ``WS_EX_NOACTIVATE`` leaves the HUD
|
||||
visible while preserving the ATS-focus safety gate. A missing window is a
|
||||
normal retryable condition because ``cv.imshow`` creates it lazily.
|
||||
"""
|
||||
if not isinstance(title, str) or not title:
|
||||
return False
|
||||
try:
|
||||
user32 = ctypes.WinDLL("user32", use_last_error=True)
|
||||
user32.FindWindowW.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR]
|
||||
user32.FindWindowW.restype = wintypes.HWND
|
||||
user32.GetWindowLongPtrW.argtypes = [wintypes.HWND, ctypes.c_int]
|
||||
user32.GetWindowLongPtrW.restype = ctypes.c_ssize_t
|
||||
user32.SetWindowLongPtrW.argtypes = [wintypes.HWND, ctypes.c_int, ctypes.c_ssize_t]
|
||||
user32.SetWindowLongPtrW.restype = ctypes.c_ssize_t
|
||||
hwnd = user32.FindWindowW(None, title)
|
||||
if not hwnd:
|
||||
return False
|
||||
exstyle_offset = -20 # GWL_EXSTYLE
|
||||
no_activate = 0x08000000 # WS_EX_NOACTIVATE
|
||||
current = int(user32.GetWindowLongPtrW(hwnd, exstyle_offset))
|
||||
desired = current | no_activate
|
||||
if desired != current:
|
||||
user32.SetWindowLongPtrW(hwnd, exstyle_offset, desired)
|
||||
return bool(int(user32.GetWindowLongPtrW(hwnd, exstyle_offset)) & no_activate)
|
||||
except (AttributeError, OSError, TypeError, ValueError):
|
||||
# The HUD is optional and this helper must never interrupt capture or
|
||||
# release a controller because a desktop window API is unavailable.
|
||||
return False
|
||||
|
||||
class MOUSEINPUT(ctypes.Structure):
|
||||
_fields_ = [("dx", ctypes.c_int32), ("dy", ctypes.c_int32),
|
||||
("mouseData", DWORD), ("dwFlags", DWORD),
|
||||
("time", DWORD), ("dwExtraInfo", ULONG_PTR)]
|
||||
|
||||
class KEYBDINPUT(ctypes.Structure):
|
||||
_fields_ = [("wVk", ctypes.c_uint16), ("wScan", ctypes.c_uint16),
|
||||
("dwFlags", DWORD), ("time", DWORD), ("dwExtraInfo", ULONG_PTR)]
|
||||
|
||||
class HARDWAREINPUT(ctypes.Structure):
|
||||
_fields_ = [("uMsg", DWORD), ("wParamL", ctypes.c_uint16), ("wParamH", ctypes.c_uint16)]
|
||||
|
||||
class INPUTUNION(ctypes.Union):
|
||||
_fields_ = [("mi", MOUSEINPUT), ("ki", KEYBDINPUT), ("hi", HARDWAREINPUT)]
|
||||
|
||||
class INPUT(ctypes.Structure):
|
||||
_anonymous_ = ("data",)
|
||||
_fields_ = [("type", DWORD), ("data", INPUTUNION)]
|
||||
|
||||
class ATSWindow:
|
||||
def __init__(self):
|
||||
self.user32 = ctypes.WinDLL("user32", use_last_error=True)
|
||||
self.kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
self.user32.GetForegroundWindow.restype = wintypes.HWND
|
||||
self.user32.IsWindow.argtypes = [wintypes.HWND]
|
||||
self.user32.IsWindowVisible.argtypes = [wintypes.HWND]
|
||||
self.user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(DWORD)]
|
||||
self.user32.GetWindowTextLengthW.argtypes = [wintypes.HWND]
|
||||
self.user32.GetWindowTextLengthW.restype = ctypes.c_int
|
||||
self.user32.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]
|
||||
self.user32.GetWindowTextW.restype = ctypes.c_int
|
||||
self.user32.GetClientRect.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.RECT)]
|
||||
self.user32.ClientToScreen.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.POINT)]
|
||||
self.user32.IsIconic.argtypes = [wintypes.HWND]
|
||||
self.kernel32.OpenProcess.argtypes = [DWORD, wintypes.BOOL, DWORD]
|
||||
self.kernel32.OpenProcess.restype = wintypes.HANDLE
|
||||
self.kernel32.QueryFullProcessImageNameW.argtypes = [wintypes.HANDLE, DWORD, wintypes.LPWSTR, ctypes.POINTER(DWORD)]
|
||||
self.kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
|
||||
self.hwnd = None
|
||||
self._last_search = 0.0
|
||||
|
||||
def find(self):
|
||||
if self.hwnd and self.user32.IsWindow(self.hwnd):
|
||||
return self.hwnd
|
||||
if time.monotonic() - self._last_search < 1.0:
|
||||
return None
|
||||
self._last_search = time.monotonic()
|
||||
callback_type = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
|
||||
def visit(hwnd, _):
|
||||
pid = DWORD()
|
||||
self.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
|
||||
process = self.kernel32.OpenProcess(0x1000, False, pid.value)
|
||||
if not process:
|
||||
return True
|
||||
try:
|
||||
name = ctypes.create_unicode_buffer(1024)
|
||||
length = DWORD(len(name))
|
||||
if self.kernel32.QueryFullProcessImageNameW(process, 0, name, ctypes.byref(length)):
|
||||
if name.value.lower().endswith("\\amtrucks.exe") and self.user32.IsWindowVisible(hwnd):
|
||||
self.hwnd = hwnd
|
||||
return False
|
||||
finally:
|
||||
self.kernel32.CloseHandle(process)
|
||||
return True
|
||||
self.user32.EnumWindows(callback_type(visit), 0)
|
||||
return self.hwnd
|
||||
|
||||
def foreground(self):
|
||||
hwnd = self.find()
|
||||
return bool(hwnd and hwnd == self.user32.GetForegroundWindow() and not self.user32.IsIconic(hwnd))
|
||||
|
||||
def focus_snapshot(self):
|
||||
"""Return the ATS/focused-window state for diagnosing a lease release.
|
||||
|
||||
The control gate intentionally remains a boolean safety check. This
|
||||
companion read adds the owning window and process to the release log
|
||||
so an external overlay, launcher, or ATS dialog can be distinguished
|
||||
from a panel interaction after the fact.
|
||||
"""
|
||||
ats = self.find()
|
||||
foreground = self.user32.GetForegroundWindow()
|
||||
|
||||
def title(hwnd):
|
||||
if not hwnd:
|
||||
return ''
|
||||
length = self.user32.GetWindowTextLengthW(hwnd)
|
||||
if length <= 0:
|
||||
return ''
|
||||
text = ctypes.create_unicode_buffer(length + 1)
|
||||
self.user32.GetWindowTextW(hwnd, text, len(text))
|
||||
return text.value
|
||||
|
||||
def process_info(hwnd):
|
||||
if not hwnd:
|
||||
return 0, ''
|
||||
pid = DWORD()
|
||||
self.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
|
||||
if not pid.value:
|
||||
return 0, ''
|
||||
handle = self.kernel32.OpenProcess(0x1000, False, pid.value)
|
||||
if not handle:
|
||||
return int(pid.value), ''
|
||||
try:
|
||||
name = ctypes.create_unicode_buffer(1024)
|
||||
length = DWORD(len(name))
|
||||
if self.kernel32.QueryFullProcessImageNameW(handle, 0, name, ctypes.byref(length)):
|
||||
return int(pid.value), name.value
|
||||
finally:
|
||||
self.kernel32.CloseHandle(handle)
|
||||
return int(pid.value), ''
|
||||
|
||||
pid, executable = process_info(foreground)
|
||||
return dict(
|
||||
ats_hwnd=int(ats or 0),
|
||||
ats_title=title(ats),
|
||||
ats_minimized=bool(ats and self.user32.IsIconic(ats)),
|
||||
foreground_hwnd=int(foreground or 0),
|
||||
foreground_title=title(foreground),
|
||||
foreground_pid=pid,
|
||||
foreground_exe=executable,
|
||||
ats_foreground=bool(ats and ats == foreground and not self.user32.IsIconic(ats)),
|
||||
)
|
||||
|
||||
def client_region(self):
|
||||
hwnd = self.find()
|
||||
if not hwnd or self.user32.IsIconic(hwnd):
|
||||
raise RuntimeError("ATS window is missing or minimized")
|
||||
rect, origin = wintypes.RECT(), wintypes.POINT()
|
||||
if not self.user32.GetClientRect(hwnd, ctypes.byref(rect)) or not self.user32.ClientToScreen(hwnd, ctypes.byref(origin)):
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
if rect.right < 640 or rect.bottom < 360:
|
||||
raise RuntimeError("ATS window is too small for road capture")
|
||||
return {"left": origin.x, "top": origin.y, "width": rect.right, "height": rect.bottom}
|
||||
|
||||
class KeyboardInput:
|
||||
def __init__(self, window=None):
|
||||
self.window = window or ATSWindow()
|
||||
self.user32 = ctypes.WinDLL("user32", use_last_error=True)
|
||||
self.user32.SendInput.argtypes = [wintypes.UINT, ctypes.POINTER(INPUT), ctypes.c_int]
|
||||
self.user32.SendInput.restype = wintypes.UINT
|
||||
self.held = set()
|
||||
|
||||
def send_key(self, scan_code, is_press):
|
||||
if is_press and not self.window.foreground():
|
||||
raise RuntimeError("ATS lost foreground focus")
|
||||
if (scan_code in self.held) == is_press:
|
||||
return
|
||||
inp = INPUT(type=1)
|
||||
inp.ki = KEYBDINPUT(0, scan_code, 0x0008 | (0 if is_press else 0x0002), 0, INPUT_TAG)
|
||||
if self.user32.SendInput(1, ctypes.byref(inp), ctypes.sizeof(INPUT)) != 1:
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
if is_press:
|
||||
self.held.add(scan_code)
|
||||
else:
|
||||
self.held.discard(scan_code)
|
||||
|
||||
def release_all(self):
|
||||
errors = []
|
||||
for scan in tuple(self.held):
|
||||
try:
|
||||
self.send_key(scan, False)
|
||||
except OSError as exc:
|
||||
errors.append(exc)
|
||||
if errors:
|
||||
raise errors[0]
|
||||
|
||||
def tap_key(self, scan_code):
|
||||
self.send_key(scan_code, True)
|
||||
try:
|
||||
time.sleep(0.04)
|
||||
finally:
|
||||
self.send_key(scan_code, False)
|
||||
|
||||
class TakeoverMonitor:
|
||||
"""Observe human controls without treating our own injected keys as takeover."""
|
||||
TAKEOVER_KEYS = {0x1B, 0x20, 0x57, 0x41, 0x53, 0x44, 0x25, 0x26, 0x27, 0x28,
|
||||
0x0C, 0x21, 0x22, 0x23, 0x24, 0x2D, 0x2E,
|
||||
*range(0x31, 0x3A), *range(0x60, 0x6A)}
|
||||
|
||||
def __init__(self, ignore_pedals=False, speed_window=None):
|
||||
self._lock = threading.Lock()
|
||||
self.set_ignore_pedals(ignore_pedals)
|
||||
self.reason = None
|
||||
self.f8_count = 0
|
||||
self.escape_count = 0
|
||||
self.speed_steps = 0
|
||||
self.speed_window = speed_window
|
||||
self.ready = threading.Event()
|
||||
self._held = set()
|
||||
self._thread = threading.Thread(target=self._run, name="ATS takeover", daemon=True)
|
||||
self._thread.start()
|
||||
if not self.ready.wait(2.0):
|
||||
raise RuntimeError("Could not start takeover monitor")
|
||||
if self.reason:
|
||||
raise RuntimeError(self.reason)
|
||||
|
||||
def set_ignore_pedals(self, ignore_pedals):
|
||||
with self._lock:
|
||||
self.takeover_keys = self.TAKEOVER_KEYS.copy()
|
||||
if ignore_pedals:
|
||||
self.takeover_keys -= {0x57, 0x53, 0x26, 0x28}
|
||||
|
||||
def _run(self):
|
||||
user32 = ctypes.WinDLL("user32", use_last_error=True)
|
||||
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
callback_type = ctypes.WINFUNCTYPE(ctypes.c_ssize_t, ctypes.c_int, wintypes.WPARAM, wintypes.LPARAM)
|
||||
class KBDLLHOOKSTRUCT(ctypes.Structure):
|
||||
_fields_ = [("vkCode", DWORD), ("scanCode", DWORD), ("flags", DWORD),
|
||||
("time", DWORD), ("dwExtraInfo", ULONG_PTR)]
|
||||
user32.SetWindowsHookExW.argtypes = [ctypes.c_int, callback_type, wintypes.HINSTANCE, DWORD]
|
||||
user32.SetWindowsHookExW.restype = wintypes.HANDLE
|
||||
user32.CallNextHookEx.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.WPARAM, wintypes.LPARAM]
|
||||
user32.CallNextHookEx.restype = ctypes.c_ssize_t
|
||||
kernel32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR]
|
||||
kernel32.GetModuleHandleW.restype = wintypes.HMODULE
|
||||
def callback(code, message, data):
|
||||
if code >= 0:
|
||||
event = ctypes.cast(data, ctypes.POINTER(KBDLLHOOKSTRUCT)).contents
|
||||
if event.dwExtraInfo != INPUT_TAG:
|
||||
down = message in (0x100, 0x104)
|
||||
with self._lock:
|
||||
if down and event.vkCode not in self._held:
|
||||
self._held.add(event.vkCode)
|
||||
if event.vkCode == 0x1B:
|
||||
self.escape_count += 1
|
||||
if event.vkCode == 0x77:
|
||||
self.f8_count += 1
|
||||
elif event.vkCode in (0x24,0x23) and self.speed_window is not None and self.speed_window.foreground():
|
||||
self.speed_steps += 1 if event.vkCode == 0x24 else -1
|
||||
elif event.vkCode in self.takeover_keys:
|
||||
self.reason = "Manual control or camera change"
|
||||
elif not down:
|
||||
self._held.discard(event.vkCode)
|
||||
return user32.CallNextHookEx(None, code, message, data)
|
||||
self._callback = callback_type(callback)
|
||||
self._thread_id = kernel32.GetCurrentThreadId()
|
||||
hook = user32.SetWindowsHookExW(13, self._callback, kernel32.GetModuleHandleW(None), 0)
|
||||
if not hook:
|
||||
self.reason = "Takeover hook failed: " + str(ctypes.get_last_error())
|
||||
self.ready.set()
|
||||
if not hook:
|
||||
return
|
||||
msg = wintypes.MSG()
|
||||
try:
|
||||
while user32.GetMessageW(ctypes.byref(msg), None, 0, 0) > 0:
|
||||
user32.TranslateMessage(ctypes.byref(msg))
|
||||
user32.DispatchMessageW(ctypes.byref(msg))
|
||||
finally:
|
||||
user32.UnhookWindowsHookEx.argtypes = [wintypes.HANDLE]
|
||||
user32.UnhookWindowsHookEx(hook)
|
||||
|
||||
def close(self):
|
||||
user32 = ctypes.WinDLL("user32", use_last_error=True)
|
||||
user32.PostThreadMessageW.argtypes = [DWORD, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
|
||||
user32.PostThreadMessageW(self._thread_id, 0x12, 0, 0)
|
||||
self._thread.join(timeout=1.0)
|
||||
|
||||
def consume(self):
|
||||
with self._lock:
|
||||
result = self.f8_count, self.reason
|
||||
self.f8_count, self.reason = 0, None
|
||||
return result
|
||||
|
||||
def consume_escape(self):
|
||||
"""Consume complete Escape presses independently of legacy takeover events."""
|
||||
with self._lock:
|
||||
count = self.escape_count
|
||||
self.escape_count = 0
|
||||
return count
|
||||
|
||||
def consume_speed_steps(self):
|
||||
"""Home/End presses in ATS; independent of F8/manual takeover."""
|
||||
with self._lock:
|
||||
steps=self.speed_steps
|
||||
self.speed_steps=0
|
||||
return steps
|
||||
@@ -0,0 +1,10 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
echo Close ATS first. Windows will ask for administrator approval.
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0install_plugin.ps1"
|
||||
if errorlevel 1 (
|
||||
echo Installation failed or was cancelled. See install_log.txt.
|
||||
) else (
|
||||
echo Telemetry installed and verified. Restart ATS, then launch Tesla Semi FSD.
|
||||
)
|
||||
pause
|
||||
@@ -0,0 +1,31 @@
|
||||
param([string]$GameDirectory = "C:\Program Files (x86)\DODI-Repacks\American Truck Simulator")
|
||||
$ErrorActionPreference = "Stop"
|
||||
$taskPrincipal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
|
||||
if (-not $taskPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
|
||||
$taskArgs = "-NoProfile -ExecutionPolicy Bypass -File ""$PSCommandPath"" -GameDirectory ""$GameDirectory"""
|
||||
$taskProcess = Start-Process -FilePath "powershell.exe" -Verb RunAs -WindowStyle Hidden -ArgumentList $taskArgs -Wait -PassThru
|
||||
exit $taskProcess.ExitCode
|
||||
}
|
||||
try {
|
||||
$taskSource = Join-Path $PSScriptRoot "telemetry_plugin\release_v_1_12_1\Win64\scs-telemetry.dll"
|
||||
$taskBinary = Join-Path $GameDirectory "bin\win_x64\amtrucks.exe"
|
||||
if (-not (Test-Path -LiteralPath $taskSource)) { throw "Bundled telemetry DLL is missing." }
|
||||
if (-not (Test-Path -LiteralPath $taskBinary)) { throw "ATS was not found at $taskBinary." }
|
||||
if (Get-Process -Name amtrucks -ErrorAction SilentlyContinue) { throw "Close ATS before installing, then run the installer again." }
|
||||
$taskPluginDirectory = Join-Path $GameDirectory "bin\win_x64\plugins"
|
||||
$taskDestination = Join-Path $taskPluginDirectory "scs-telemetry.dll"
|
||||
New-Item -ItemType Directory -Path $taskPluginDirectory -Force | Out-Null
|
||||
$taskSourceHash = (Get-FileHash -LiteralPath $taskSource -Algorithm SHA256).Hash
|
||||
if (Test-Path -LiteralPath $taskDestination) {
|
||||
if ((Get-FileHash -LiteralPath $taskDestination -Algorithm SHA256).Hash -ne $taskSourceHash) {
|
||||
Copy-Item -LiteralPath $taskDestination -Destination "$taskDestination.backup"
|
||||
}
|
||||
}
|
||||
Copy-Item -LiteralPath $taskSource -Destination $taskDestination -Force
|
||||
if ((Get-FileHash -LiteralPath $taskDestination -Algorithm SHA256).Hash -ne $taskSourceHash) { throw "DLL verification failed." }
|
||||
Add-Content -LiteralPath (Join-Path $PSScriptRoot "install_log.txt") -Value ("SUCCESS " + (Get-Date).ToString("o") + " " + $taskDestination + " " + $taskSourceHash)
|
||||
exit 0
|
||||
} catch {
|
||||
Add-Content -LiteralPath (Join-Path $PSScriptRoot "install_log.txt") -Value ("FAILED " + (Get-Date).ToString("o") + " " + $_.Exception.Message)
|
||||
exit 1
|
||||
}
|
||||
@@ -0,0 +1,743 @@
|
||||
"""ATS Supercombo driving loop with verified telemetry and supervised engagement."""
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import time
|
||||
import cv2
|
||||
import numpy as np
|
||||
from datetime import datetime
|
||||
|
||||
from control.windows_input import ATSWindow, KeyboardInput, TakeoverMonitor
|
||||
from control.fsd_controller import FSDController
|
||||
from control.path_preview import path_reason, preview_steering
|
||||
from control.pop_trajectory import PopTrajectoryController
|
||||
from control.pop_model_actions import PopModelActions
|
||||
from control.signal_preview import SignalPreview
|
||||
from control.navigation_preview import route_preview
|
||||
from control.lane_choice_preview import lane_choice_preview
|
||||
from control.virtual_joystick import dll_path
|
||||
from telemetry.ats_telemetry import ATSTelemetry
|
||||
from telemetry.gps_route_reader import GPSRouteReader
|
||||
from telemetry.nearby_traffic import NearbyTrafficReader
|
||||
from telemetry.traffic_tracker import TrafficTracker
|
||||
from telemetry.road_geometry import RoadGeometryReader
|
||||
from telemetry.junction_paths import JunctionPathReader
|
||||
from model.runner import create_brain
|
||||
from model.registry import ModelRegistry
|
||||
from vision.screen_capture import ScreenCapture
|
||||
from vision.calibration_recorder import CalibrationRecorder
|
||||
from vision.auxiliary_camera_health import AuxiliaryCameraHealth
|
||||
from vision.scene_frame import scene_perception, load_scene_origin
|
||||
from vision.camera_obstruction import guarded_model_step
|
||||
from vision.preview_clock import MotionRecordingClock
|
||||
from ui.tesla_fsd_hud import TeslaFSDHUD
|
||||
from audio.chimes import TeslaChimes
|
||||
from runtime_checks import readiness_reason, LaneConfidenceGrace, inset_cruise_test_reason, parked_setting_reason
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
TITLE = "Tesla Semi FSD - OpenPilot"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--diagnose", action="store_true", help="Report health without injecting controls")
|
||||
parser.add_argument("--dry-run", action="store_true", help="Show requested controls without injecting them")
|
||||
parser.add_argument("--record-calibration", action="store_true",
|
||||
help="Record exact inset frames and model outputs; requires auxiliary dry run")
|
||||
parser.add_argument('--record-image-hz', type=int, choices=range(1, 21), default=1,
|
||||
help='Maximum saved camera frames per second for passive calibration (1 to 20)')
|
||||
parser.add_argument("--duration", type=float, help="Exit after this many seconds")
|
||||
parser.add_argument('--duration-after-motion', action='store_true',
|
||||
help='Passive recording: wait for forward motion before starting --duration')
|
||||
parser.add_argument("--no-hud", action="store_true")
|
||||
parser.add_argument("--hud-mode", choices=("dashboard", "cockpit_screen"), default="dashboard",
|
||||
help="Panel layout: dashboard includes the model camera preview")
|
||||
parser.add_argument("--speed", type=float, default=15.0, help="Cruise speed MPH (5 to 55; default 15)")
|
||||
parser.add_argument("--lane-only", action="store_true", help="Validate lane keeping with manual speed control")
|
||||
parser.add_argument("--driving-mode", choices=("manual", "cruise", "chill"),
|
||||
help="Manual pedals, speed cruise, or gentler cruise with a longer following gap")
|
||||
parser.add_argument("--model", default="supercombo-6409", help="Registered local model ID")
|
||||
parser.add_argument("--list-models", action="store_true", help="List local models without acquiring controls")
|
||||
parser.add_argument("--path-preview", action="store_true", help="Passive laneless trajectory evaluation; requires --dry-run")
|
||||
parser.add_argument("--signal-preview", action="store_true", help="Passive turn-signal model-intent evaluation; requires --dry-run")
|
||||
parser.add_argument("--navigation-preview", action="store_true", help="Live GPS route/map preview; requires --dry-run, sends no navigation commands")
|
||||
parser.add_argument("--navigation-observe", action="store_true", help="Show and record read-only GPS beside existing inset driving")
|
||||
parser.add_argument("--navigation-driving-test", action="store_true", help="Bounded GPS-assisted inset steering and Chill cruise trial")
|
||||
parser.add_argument("--signal-delay", type=float, choices=(0.05, 0.5, 1.0, 2.0, 3.0), default=1.0)
|
||||
parser.add_argument("--inset-cruise-test", action="store_true",
|
||||
help="Bounded inset cruise validation after steering checks; max 15 MPH, 120 seconds")
|
||||
parser.add_argument("--camera", choices=("bumper", "cabin", "auxiliary"), default="bumper",
|
||||
help="Model camera: validated bumper, experimental cabin, or configured road inset")
|
||||
parser.add_argument("--backend", choices=("auto", "vjoy", "keyboard"), default="auto",
|
||||
help="Analog vJoy when installed, otherwise keyboard feedback")
|
||||
parser.add_argument("--inference-provider", choices=("auto", "cpu", "directml"), default="auto",
|
||||
help="Model runner; CPU avoids contention with ATS rendering on this system")
|
||||
args = parser.parse_args()
|
||||
registry = ModelRegistry(ROOT / "models")
|
||||
if args.list_models:
|
||||
print(json.dumps(registry.inventory(), indent=2))
|
||||
return
|
||||
if args.lane_only and args.driving_mode not in (None, "manual"):
|
||||
parser.error("--lane-only requires manual driving mode")
|
||||
args.driving_mode = args.driving_mode or ("manual" if args.lane_only else "cruise")
|
||||
args.lane_only = args.driving_mode == "manual"
|
||||
if args.navigation_driving_test:
|
||||
if args.dry_run or args.navigation_preview:
|
||||
parser.error("Navigation driving test is an active bounded trial; use --navigation-preview for passive evaluation")
|
||||
args.navigation_observe = True
|
||||
args.inset_cruise_test = True
|
||||
if args.driving_mode != 'chill':
|
||||
parser.error('Navigation driving test requires --driving-mode chill')
|
||||
if args.navigation_observe and args.camera != "auxiliary":
|
||||
parser.error("Navigation observation requires the configured auxiliary camera")
|
||||
if (args.path_preview or args.signal_preview or args.navigation_preview) and not args.dry_run:
|
||||
parser.error("Path, signal and navigation previews require --dry-run; they cannot control the truck")
|
||||
try:
|
||||
selected_model = registry.select(args.model)
|
||||
except (ValueError, OSError, KeyError) as exc:
|
||||
parser.error(str(exc))
|
||||
model_manifest = selected_model["metadata"]
|
||||
if model_manifest.get('preview_only') and not args.dry_run and not args.diagnose:
|
||||
parser.error('Pop v2 requires --dry-run until its wide camera and trajectory control are validated')
|
||||
baseline_hash = json.loads((ROOT / "models/manifest.json").read_text())["sha256"]
|
||||
if not args.dry_run and args.camera != "auxiliary" and model_manifest["sha256"] != baseline_hash:
|
||||
parser.error("New models require passive evaluation and camera calibration before control")
|
||||
if args.record_calibration and (not args.dry_run or args.camera != "auxiliary"):
|
||||
parser.error("--record-calibration requires --camera auxiliary --dry-run")
|
||||
if args.record_image_hz > 1 and not (args.record_calibration and args.dry_run):
|
||||
parser.error('High-rate images require --record-calibration --dry-run')
|
||||
if args.duration_after_motion:
|
||||
if not (args.dry_run and args.record_calibration and args.duration is not None):
|
||||
parser.error('--duration-after-motion requires --dry-run --record-calibration --duration')
|
||||
try:
|
||||
motion_clock = MotionRecordingClock(args.duration)
|
||||
except ValueError as exc:
|
||||
parser.error(str(exc))
|
||||
else:
|
||||
motion_clock = None
|
||||
if args.inset_cruise_test:
|
||||
test_reason = inset_cruise_test_reason(args.camera, args.backend, args.lane_only,
|
||||
args.dry_run, args.duration, args.speed)
|
||||
if test_reason:
|
||||
parser.error(test_reason)
|
||||
os.chdir(ROOT)
|
||||
(ROOT / "diagnostics").mkdir(exist_ok=True)
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s",
|
||||
handlers=[logging.StreamHandler(),
|
||||
logging.FileHandler(ROOT / "diagnostics/session.log", encoding="utf-8")])
|
||||
log = logging.getLogger("ats-fsd")
|
||||
window = ATSWindow()
|
||||
brain = create_brain(selected_model, use_gpu=args.inference_provider != "cpu")
|
||||
telemetry = ATSTelemetry()
|
||||
if args.inference_provider == "directml" and brain.active_provider != "DmlExecutionProvider":
|
||||
telemetry.close()
|
||||
raise RuntimeError("DirectML was requested but is not available")
|
||||
backend = args.backend
|
||||
if backend == "auto":
|
||||
backend = "vjoy" if dll_path() else "keyboard"
|
||||
log.info("Model provider=%s; backend=%s; dry_run=%s", brain.active_provider, backend, args.dry_run)
|
||||
log.info("Model id=%s hash=%s driving_mode=%s", args.model, model_manifest["sha256"], args.driving_mode)
|
||||
if args.diagnose:
|
||||
data = telemetry.get_data()
|
||||
time.sleep(0.1)
|
||||
data = telemetry.get_data()
|
||||
output = {"ats_window": bool(window.find()), "ats_foreground": window.foreground(),
|
||||
"provider": brain.active_provider, "telemetry": data,
|
||||
"backend": backend, "vjoy_dll": str(dll_path()) if dll_path() else None}
|
||||
print(json.dumps(output, indent=2))
|
||||
telemetry.close()
|
||||
return
|
||||
|
||||
capture = ScreenCapture(window=window, camera_view=args.camera)
|
||||
scene_configs = {
|
||||
'Pinnacle': load_scene_origin(capture.auxiliary, ROOT / 'diagnostics' / 'scene-origin.json'),
|
||||
'579': load_scene_origin(capture.auxiliary, ROOT / 'diagnostics' / 'scene-origin-579.json'),
|
||||
}
|
||||
scene_config = scene_configs.get(telemetry.get_data().get('truck_name'), scene_configs['Pinnacle'])
|
||||
if args.camera == "auxiliary" and not args.dry_run and not capture.auxiliary.get("calibrated"):
|
||||
capture.close()
|
||||
telemetry.close()
|
||||
raise RuntimeError("Road inset needs passive calibration first; use --camera auxiliary --dry-run")
|
||||
camera_health = None
|
||||
if args.camera == "auxiliary" and not args.dry_run:
|
||||
camera_health = AuxiliaryCameraHealth(capture.auxiliary,
|
||||
model_manifest["sha256"], args.lane_only,
|
||||
cruise_test=args.inset_cruise_test)
|
||||
if camera_health.startup_reason:
|
||||
capture.close()
|
||||
telemetry.close()
|
||||
raise RuntimeError(camera_health.startup_reason)
|
||||
if args.camera == "auxiliary":
|
||||
log.warning("Experimental road inset: verify ForwardCamera operation and passive calibration before active control")
|
||||
# Passive dry runs never acquire or alter virtual-controller axes.
|
||||
controller = FSDController(mode="keyboard" if args.dry_run else backend,
|
||||
keyboard=KeyboardInput(window), camera_view=args.camera,
|
||||
driving_mode=args.driving_mode)
|
||||
controller.cruise_set_speed = min(55.0, max(5.0, args.speed))
|
||||
monitor = TakeoverMonitor(ignore_pedals=args.lane_only or args.dry_run)
|
||||
chimes = TeslaChimes()
|
||||
hud = TeslaFSDHUD(width=1280, height=720)
|
||||
hud.mode = args.hud_mode
|
||||
if not args.no_hud:
|
||||
cv2.namedWindow(TITLE, cv2.WINDOW_NORMAL)
|
||||
cv2.resizeWindow(TITLE, 1280, 720)
|
||||
# Put diagnostics on a second monitor when one is available.
|
||||
if len(capture.sct.monitors) > 2:
|
||||
second = capture.sct.monitors[2]
|
||||
cv2.moveWindow(TITLE, second["left"], second["top"])
|
||||
|
||||
engaged = False
|
||||
pending_until = None
|
||||
stable_frames = 0
|
||||
status = "Bring ATS to the foreground; F8 engages"
|
||||
last_status = None
|
||||
started = last_report = time.monotonic()
|
||||
next_idle_record_at = 0.
|
||||
next_hud_render_at = 0.
|
||||
last_perception_report = started
|
||||
perception = brain.step(np.zeros((1, 12, 128, 256), np.float32))
|
||||
camera = np.zeros((256, 512, 3), np.uint8)
|
||||
last_inference_ms = 0.0
|
||||
last_inference_at = None
|
||||
obstruction_report = dict(checked=False, blocked=False, inference_skipped=True,
|
||||
reason='Waiting for a fresh forward camera frame')
|
||||
inference_telemetry = None
|
||||
recorder = None
|
||||
confidence_grace = LaneConfidenceGrace()
|
||||
holding_vision = False
|
||||
signal_preview = SignalPreview(args.signal_delay) if args.signal_preview else None
|
||||
navigation = GPSRouteReader() if args.navigation_preview or args.navigation_observe else None
|
||||
navigation_driver = None
|
||||
if args.navigation_driving_test:
|
||||
from control.navigation_driver import NavigationDriver
|
||||
navigation_driver = NavigationDriver()
|
||||
navigation_decision = None
|
||||
pop_controller = (PopTrajectoryController()
|
||||
if args.path_preview and selected_model.get('id') == 'pop-v2' else None)
|
||||
pop_actions = PopModelActions() if pop_controller else None
|
||||
pop_decision = None
|
||||
last_control_command = None
|
||||
traffic = NearbyTrafficReader()
|
||||
traffic_tracker = TrafficTracker()
|
||||
road_geometry = RoadGeometryReader()
|
||||
junction_paths = JunctionPathReader(road_geometry)
|
||||
last_navigation_label = None
|
||||
|
||||
def refresh_scene(data, original, route):
|
||||
nonlocal scene_config
|
||||
# Display copies only: steering and paired model evidence retain the
|
||||
# original camera-frame perception and their existing calibration.
|
||||
data['camera_mode'] = args.camera
|
||||
scene_config = scene_configs.get(data.get('truck_name'), scene_configs['Pinnacle'])
|
||||
scene, alignment = scene_perception(original, data, scene_config)
|
||||
if (data.get('model_obstructed') is not False
|
||||
or data.get('model_geometry_stale') is True):
|
||||
alignment.update(available=False,
|
||||
reason=(data.get('camera_obstruction', {}).get('reason')
|
||||
if data.get('model_obstructed') is True else
|
||||
'Fresh unobstructed model geometry is unavailable'))
|
||||
data['scene_alignment'] = alignment
|
||||
traffic_for_lanes = data['nearby_traffic'] if alignment['available'] else {
|
||||
'available': False, 'reason': 'Camera-to-truck alignment unavailable'}
|
||||
data['lane_choice_preview'] = lane_choice_preview(scene.lanes,
|
||||
traffic_for_lanes, data['road_geometry'], route if navigation else None,
|
||||
data, data['junction_paths'])
|
||||
data['lane_choice_preview']['scene_alignment_estimated'] = alignment['available']
|
||||
return scene
|
||||
|
||||
def disengage(reason):
|
||||
nonlocal engaged, pending_until, stable_frames, status, holding_vision, last_control_command
|
||||
was_active = engaged or pending_until is not None
|
||||
engaged, pending_until, stable_frames = False, None, 0
|
||||
controller.release_all_controls()
|
||||
last_control_command = None
|
||||
confidence_grace.reset()
|
||||
if navigation_driver:
|
||||
navigation_driver.reset()
|
||||
if pop_controller:
|
||||
pop_controller.reset()
|
||||
pop_actions.reset()
|
||||
holding_vision = False
|
||||
status = "Disengaged: " + reason
|
||||
if was_active:
|
||||
chimes.play_disengage()
|
||||
log.info("DISENGAGED: %s", reason)
|
||||
|
||||
log.info("GPS preview: driving controls OFF; F8 does not enable driving." if args.navigation_preview else
|
||||
"F8 toggles. Physical driving/camera controls or Escape take over. Tab belongs to ATS.")
|
||||
try:
|
||||
if args.record_calibration or args.navigation_observe:
|
||||
prefix = 'navigation-drive-' if args.navigation_driving_test else 'navigation-observe-' if args.navigation_observe else 'inset-cal-'
|
||||
directory = ROOT / "diagnostics" / (prefix + datetime.now().strftime("%Y%m%d-%H%M%S-%f"))
|
||||
recorder = CalibrationRecorder(directory, dict(
|
||||
camera=scene_config, provider=brain.active_provider,
|
||||
model=model_manifest,
|
||||
image_save_hz=args.record_image_hz,
|
||||
async_write=bool(pop_controller), async_queue_capacity=8,
|
||||
auxiliary_camera=capture.auxiliary,
|
||||
duration_clock='first_forward_motion' if motion_clock else 'startup',
|
||||
dry_run=args.dry_run, path_preview=args.path_preview, signal_preview=args.signal_preview,
|
||||
navigation_preview=args.navigation_preview, navigation_observe=args.navigation_observe,
|
||||
navigation_driving=args.navigation_driving_test,
|
||||
projection="Historical MED calibration frame: lane z already includes height; visual alignment check"))
|
||||
log.info("PAIRED recording to %s; driving controls %s; GPS mode=%s", directory,
|
||||
'OFF' if args.dry_run else 'available through F8',
|
||||
'driving trial' if args.navigation_driving_test else 'observation')
|
||||
previous_loop_start = None
|
||||
while (not motion_clock.expired(time.monotonic()) if motion_clock else
|
||||
args.duration is None or time.monotonic() - started < args.duration):
|
||||
loop_start = time.monotonic()
|
||||
loop_fps = (1.0 / max(0.001, loop_start - previous_loop_start)
|
||||
if previous_loop_start is not None else 0.0)
|
||||
previous_loop_start = loop_start
|
||||
toggles, takeover = monitor.consume()
|
||||
data = telemetry.get_data()
|
||||
data['nearby_traffic'] = traffic_tracker.snapshot(traffic.snapshot(data), data)
|
||||
if navigation:
|
||||
route = navigation.snapshot(data)
|
||||
data['navigation_preview'] = route_preview(route, data)
|
||||
data['navigation_route'] = route
|
||||
data['navigation_observer'] = args.navigation_observe
|
||||
data['navigation_driving'] = args.navigation_driving_test
|
||||
data['road_geometry'] = road_geometry.snapshot(data, route if navigation else None)
|
||||
data['junction_paths'] = junction_paths.snapshot(data, data['road_geometry'])
|
||||
foreground = window.foreground()
|
||||
if takeover and (engaged or pending_until is not None):
|
||||
disengage(takeover)
|
||||
if toggles % 2 and not args.navigation_preview:
|
||||
if engaged or pending_until is not None:
|
||||
disengage("Disengaged with F8")
|
||||
else:
|
||||
# Only reset camera after game and telemetry are live.
|
||||
reason = readiness_reason(foreground, data,
|
||||
independent_camera=camera_health is not None)
|
||||
if not reason and camera_health:
|
||||
reason = camera_health.reason(data)
|
||||
if not reason and obstruction_report.get('blocked'):
|
||||
reason = obstruction_report['reason']
|
||||
if reason == "Look straight ahead through the windshield":
|
||||
reason = ""
|
||||
if reason:
|
||||
status = "Engagement blocked: " + reason
|
||||
log.info(status)
|
||||
else:
|
||||
if navigation_driver:
|
||||
navigation_driver.reset()
|
||||
if not args.dry_run:
|
||||
controller.reset()
|
||||
else:
|
||||
controller.fault = None
|
||||
# The corrected inset has not changed when F8 centers
|
||||
# the driver's view. Keep its recent recurrent context;
|
||||
# reset after a pause/focus gap or for other camera modes.
|
||||
if not (camera_health and last_inference_at is not None
|
||||
and time.monotonic() - last_inference_at < 0.25):
|
||||
brain.reset_state()
|
||||
capture.reset_history()
|
||||
pending_until = loop_start + 3.0
|
||||
stable_frames = 0
|
||||
status = "Checking forward road view"
|
||||
|
||||
vision_reason = "Waiting for forward camera"
|
||||
inferred_this_loop = False
|
||||
captured_this_loop = False
|
||||
pop_decision = None
|
||||
obstruction_report = dict(checked=False, blocked=False, inference_skipped=True,
|
||||
reason='No fresh forward camera frame')
|
||||
if signal_preview and not (foreground and data.get("valid")):
|
||||
signal_preview.reset()
|
||||
if foreground and data.get("valid"):
|
||||
try:
|
||||
imgs, camera, _ = capture.get_model_input(inset_only=True) if args.camera == 'auxiliary' else capture.get_model_input()
|
||||
if hasattr(brain, 'set_wide_input'):
|
||||
brain.set_wide_input(capture.wide_input)
|
||||
captured_this_loop = True
|
||||
# Head look can cross into the window animation during
|
||||
# capture. Check its latest pose before feeding this frame.
|
||||
data.update(telemetry.get_data())
|
||||
before = time.perf_counter()
|
||||
if signal_preview:
|
||||
pulse = signal_preview.update(data, loop_start)
|
||||
brain.set_desire(pulse)
|
||||
data["model_desire_pulse"] = pulse
|
||||
if pulse != "none":
|
||||
log.info("SIGNAL PREVIEW desire=%s; driving controls OFF; adjacent traffic unverified", pulse)
|
||||
fresh_perception, obstruction_report = guarded_model_step(
|
||||
brain, imgs, camera, enabled=args.camera == 'auxiliary',
|
||||
report_sink=obstruction_report, telemetry=data,
|
||||
wide_image=getattr(capture, 'wide_camera', None))
|
||||
data['camera_obstruction'] = obstruction_report
|
||||
data['model_obstructed'] = (obstruction_report['blocked']
|
||||
if obstruction_report.get('checked') else None)
|
||||
if fresh_perception is None:
|
||||
# Retain the previous actual model arrays as stale evidence.
|
||||
# Reset image/recurrent history so the blocked frame cannot
|
||||
# become the next clear frame's temporal context.
|
||||
vision_reason = obstruction_report['reason']
|
||||
capture.reset_history()
|
||||
confidence_grace.reset()
|
||||
navigation_decision = None
|
||||
if signal_preview:
|
||||
signal_preview.reset()
|
||||
data['model_desire_pulse'] = 'none'
|
||||
if navigation_driver:
|
||||
navigation_driver.reset()
|
||||
if engaged or pending_until is not None:
|
||||
disengage(vision_reason)
|
||||
else:
|
||||
perception = fresh_perception
|
||||
last_inference_ms = (time.perf_counter() - before) * 1000
|
||||
last_inference_at = time.monotonic()
|
||||
vision_reason = (path_reason(perception.plan, data["speed_mps"]) if args.path_preview
|
||||
else controller.vision_reason(perception))
|
||||
if navigation_driver:
|
||||
navigation_decision = navigation_driver.assess(perception, data['speed_mps'],
|
||||
route, data['navigation_preview'], data, now=loop_start)
|
||||
vision_reason = '' if navigation_decision['allowed'] else navigation_decision['reason']
|
||||
data['navigation_driver'] = navigation_decision
|
||||
inferred_this_loop = True
|
||||
data['model_age_s'] = 0.0
|
||||
data['model_inferred_this_frame'] = True
|
||||
data['model_geometry_stale'] = False
|
||||
if hasattr(brain, 'camera_input_mode'):
|
||||
data['model_camera_input_mode'] = brain.camera_input_mode
|
||||
data['model_temporal_ready'] = brain.temporal_ready
|
||||
data['model_input_monotonic'] = brain.last_timestamp
|
||||
data['model_temporal_coverage'] = brain.temporal_coverage
|
||||
if pop_controller:
|
||||
data['pop_model_actions'] = pop_actions.assess(perception, data['speed_mps'])
|
||||
data['camera_projection'] = capture.auxiliary.get('projection')
|
||||
pop_decision = pop_controller.assess(perception, data['speed_mps'],
|
||||
data, now=time.monotonic(), model_action=data['pop_model_actions'])
|
||||
data['pop_trajectory_controller'] = pop_decision
|
||||
vision_reason = '' if pop_decision['allowed'] else pop_decision['reason']
|
||||
if args.path_preview:
|
||||
data['trajectory_preview'] = dict(
|
||||
applied=False, reason=vision_reason,
|
||||
requested_steering=(pop_decision['steer'] if pop_decision and pop_decision['allowed']
|
||||
else preview_steering(perception.plan, data['speed_mps'])
|
||||
if not pop_controller and not vision_reason else None),
|
||||
confidence_unassessed=True)
|
||||
refresh_scene(data, perception, route if navigation else None)
|
||||
except (RuntimeError, ValueError, cv2.error) as exc:
|
||||
vision_reason = "Camera/model failure: " + str(exc)
|
||||
if pop_controller and not inferred_this_loop:
|
||||
pop_controller.reset()
|
||||
pop_actions.reset()
|
||||
data.update(camera_obstruction=obstruction_report,
|
||||
model_obstructed=(obstruction_report.get('blocked') if obstruction_report.get('checked') else None),
|
||||
model_inferred_this_frame=inferred_this_loop,
|
||||
model_geometry_stale=not inferred_this_loop,
|
||||
model_age_s=(max(0., time.monotonic()-last_inference_at)
|
||||
if last_inference_at is not None else 1e6))
|
||||
if captured_this_loop:
|
||||
if not inferred_this_loop:
|
||||
refresh_scene(data, perception, route if navigation else None)
|
||||
inference_telemetry = dict(data)
|
||||
# Inference can wait on the game's GPU. Recheck game state before
|
||||
# publishing a command, rather than using the pre-inference sample.
|
||||
data = telemetry.get_data()
|
||||
if inferred_this_loop and inference_telemetry:
|
||||
for key in ('model_camera_input_mode', 'model_temporal_ready',
|
||||
'model_input_monotonic', 'model_temporal_coverage',
|
||||
'trajectory_preview', 'pop_trajectory_controller', 'pop_model_actions',
|
||||
'camera_projection'):
|
||||
if key in inference_telemetry:
|
||||
data[key] = inference_telemetry[key]
|
||||
data.update(camera_obstruction=obstruction_report,
|
||||
model_obstructed=(obstruction_report.get('blocked') if obstruction_report.get('checked') else None),
|
||||
model_inferred_this_frame=inferred_this_loop,
|
||||
model_geometry_stale=not inferred_this_loop)
|
||||
data['nearby_traffic'] = traffic_tracker.snapshot(traffic.snapshot(data), data)
|
||||
if navigation:
|
||||
route = navigation.snapshot(data)
|
||||
data['navigation_preview'] = route_preview(route, data)
|
||||
data['navigation_route'] = route
|
||||
data['navigation_observer'] = args.navigation_observe
|
||||
data['navigation_driving'] = args.navigation_driving_test
|
||||
data['navigation_driver'] = navigation_decision
|
||||
nav_label = (data['navigation_preview']['label'], data['navigation_preview']['reason'])
|
||||
if nav_label != last_navigation_label:
|
||||
log.info('GPS: %s; %s; navigation mode=%s', *nav_label,
|
||||
'trial' if navigation_driver else 'observation')
|
||||
last_navigation_label = nav_label
|
||||
data['road_geometry'] = road_geometry.snapshot(data, route if navigation else None)
|
||||
data['junction_paths'] = junction_paths.snapshot(data, data['road_geometry'])
|
||||
data['model_age_s'] = (max(0., time.monotonic()-last_inference_at)
|
||||
if last_inference_at is not None else 1e6)
|
||||
display_perception = refresh_scene(data, perception, route if navigation else None)
|
||||
foreground = window.foreground()
|
||||
reason = readiness_reason(foreground, data, actuator_fault=controller.fault,
|
||||
independent_camera=camera_health is not None)
|
||||
if not reason and camera_health:
|
||||
reason = camera_health.reason(data)
|
||||
if not reason and obstruction_report.get('blocked'):
|
||||
reason = obstruction_report['reason']
|
||||
if not reason and navigation_driver and not data['navigation_preview']['available']:
|
||||
reason = 'GPS driving trial: ' + data['navigation_preview']['reason']
|
||||
if not reason and navigation_driver and not navigation_decision:
|
||||
reason = 'Waiting for fresh GPS driving decision'
|
||||
if navigation_driver and navigation_decision and navigation_decision['allowed']:
|
||||
controller.cruise_set_speed = min(args.speed, navigation_decision['max_speed_mph'])
|
||||
if not reason and camera_health:
|
||||
reason = camera_health.speed_reason(data)
|
||||
if (not reason and not args.lane_only and not args.dry_run and not engaged
|
||||
and max(data.get("user_throttle",0),data.get("user_brake",0)) > 0.05):
|
||||
reason = "Release manual pedals before engaging cruise"
|
||||
hold_vision = False
|
||||
if engaged and camera_health:
|
||||
hold_vision = confidence_grace.allow_hold(time.monotonic(), vision_reason,
|
||||
(perception.lanes.left_prob, perception.lanes.right_prob), healthy=not reason)
|
||||
else:
|
||||
confidence_grace.reset()
|
||||
if not reason and not hold_vision:
|
||||
reason = vision_reason
|
||||
if hold_vision and not holding_vision:
|
||||
log.info("VISION_GRACE holding previous steering, pedals released; lane_prob=%.3f/%.3f",
|
||||
perception.lanes.left_prob, perception.lanes.right_prob)
|
||||
elif holding_vision and not hold_vision and not reason:
|
||||
log.info("VISION_GRACE recovered")
|
||||
holding_vision = hold_vision
|
||||
if not reason and camera_health and pending_until is not None:
|
||||
reason = controller.engagement_reason(perception)
|
||||
if (args.dry_run or args.camera == "auxiliary") and foreground and data.get("valid") and loop_start - last_perception_report > 1.0:
|
||||
log.info("PERCEPTION speed=%.1f lane_prob=%.2f/%.2f width=%.2f path_forward=%.1f inference=%.1fms reason=%s",
|
||||
data["speed_mph"], perception.lanes.left_prob, perception.lanes.right_prob,
|
||||
float(np.median(perception.lanes.right_y[:10] - perception.lanes.left_y[:10])),
|
||||
float(perception.plan.x[-1]), last_inference_ms, vision_reason or "usable")
|
||||
last_perception_report = loop_start
|
||||
if engaged and reason:
|
||||
disengage(reason)
|
||||
# Controls are already released. Preserve the last actual
|
||||
# model input/output so a dropout can be inspected afterward.
|
||||
if (camera_health and inference_telemetry is not None
|
||||
and last_inference_at is not None and last_inference_at >= loop_start):
|
||||
release_recorder = None
|
||||
try:
|
||||
directory = ROOT / "diagnostics" / ("inset-release-" + datetime.now().strftime("%Y%m%d-%H%M%S-%f"))
|
||||
release_recorder = CalibrationRecorder(directory, dict(
|
||||
camera=scene_config, provider=brain.active_provider,
|
||||
model=model_manifest,
|
||||
controls_released=True, release_reason=reason,
|
||||
input_age_seconds=time.monotonic()-last_inference_at,
|
||||
release_telemetry=data,
|
||||
projection="Historical MED calibration frame; last inferred input/output"))
|
||||
release_recorder.record(camera, perception, inference_telemetry,
|
||||
last_inference_ms, vision_reason)
|
||||
log.info("Release evidence saved to %s", directory)
|
||||
except Exception:
|
||||
log.exception("Could not save release evidence; controls remain released")
|
||||
finally:
|
||||
if release_recorder:
|
||||
try:
|
||||
release_recorder.close()
|
||||
except Exception:
|
||||
log.exception("Could not close release evidence")
|
||||
if pending_until is not None:
|
||||
if not foreground or not data.get("valid") or controller.fault:
|
||||
disengage(reason)
|
||||
elif reason:
|
||||
stable_frames = 0
|
||||
status = "Checking road: " + reason
|
||||
else:
|
||||
stable_frames += 1
|
||||
if stable_frames >= 10:
|
||||
engaged = True
|
||||
pending_until = None
|
||||
confidence_grace.allow_hold(time.monotonic(), "",
|
||||
(perception.lanes.left_prob, perception.lanes.right_prob))
|
||||
chimes.play_engage()
|
||||
status = ("GPS-assisted steering and Chill cruise trial" if navigation_driver else
|
||||
"DRY RUN" if args.dry_run else
|
||||
f"Lane keeping active; manual speed ({backend})" if args.lane_only else
|
||||
f"Lane keeping and cruise active ({backend})")
|
||||
log.info("ENGAGED speed=%.1f MPH lane_prob=%.2f/%.2f", data["speed_mph"],
|
||||
perception.lanes.left_prob, perception.lanes.right_prob)
|
||||
if pending_until is not None and loop_start > pending_until:
|
||||
disengage("Engagement blocked: " + (reason or "Road view did not stabilize"))
|
||||
|
||||
if engaged:
|
||||
if args.path_preview:
|
||||
steer = (pop_decision['steer'] if pop_controller and pop_decision
|
||||
else preview_steering(perception.plan, data["speed_mps"]))
|
||||
action, intensity = "coast", 0.0
|
||||
elif hold_vision:
|
||||
steer = controller.current_steer
|
||||
action, intensity = "coast", 0.0
|
||||
controller.cruise.reset()
|
||||
else:
|
||||
steer = (navigation_decision['steer'] if navigation_driver and navigation_decision
|
||||
else controller.compute_lateral(perception, data["speed_mps"]))
|
||||
action, intensity = controller.compute_longitudinal(perception, data["speed_mph"])
|
||||
if args.lane_only:
|
||||
action, intensity = "coast", 0.0
|
||||
command_issued_at = time.monotonic()
|
||||
if not args.dry_run:
|
||||
controller.apply_controls(steer, action, intensity, data["steering"])
|
||||
last_control_command = dict(steering=steer, action=action, intensity=intensity,
|
||||
applied=not args.dry_run, monotonic=command_issued_at,
|
||||
loop_monotonic=loop_start,
|
||||
enqueued_monotonic=time.monotonic() if not args.dry_run else None,
|
||||
timing_source='host command enqueue; not driver acknowledgment')
|
||||
if loop_start - last_report > 1.0:
|
||||
log.info("CONTROL steer=%.3f actual=%.3f pedal=%s duty=%.2f input_pedals=%.2f/%.2f speed=%.1f lane_prob=%.2f/%.2f width=%.2f inference=%.0fms head_deg=%.1f/%.1f/%.1f",
|
||||
steer, data["steering"], action, intensity, data["user_throttle"], data["user_brake"], data["speed_mph"],
|
||||
perception.lanes.left_prob, perception.lanes.right_prob,
|
||||
float(np.median(perception.lanes.right_y[:10] - perception.lanes.left_y[:10])), last_inference_ms,
|
||||
*[(((v + 0.5) % 1.0) - 0.5) * 360 for v in data['head_rotation']])
|
||||
last_report = loop_start
|
||||
elif pending_until is None and not status.startswith(("Disengaged", "Engagement blocked", "Manual")):
|
||||
status = reason or "Ready: F8 engages"
|
||||
|
||||
if args.navigation_preview:
|
||||
status = ('GPS preview: you control the truck; F8 does not enable driving'
|
||||
if foreground and data.get('valid') else
|
||||
data.get('reason') or 'Bring ATS to the foreground for the road model preview')
|
||||
if obstruction_report.get('blocked'):
|
||||
status = obstruction_report['reason'] + '; inference skipped'
|
||||
if motion_clock:
|
||||
previous_start = motion_clock.started_at
|
||||
motion_clock.update(loop_start, data, fresh_camera=inferred_this_loop and foreground)
|
||||
data['preview_recording'] = motion_clock.snapshot(loop_start)
|
||||
if previous_start is None and motion_clock.started_at is not None:
|
||||
log.info('DRIVE RECORDING started at %.1f MPH; duration %.0fs; controls OFF',
|
||||
data['speed_mph'], motion_clock.duration)
|
||||
recorder.next_image = 0.
|
||||
recorder.image_interval = 1 / args.record_image_hz
|
||||
if (motion_clock.started_at is None and foreground and data.get('valid')
|
||||
and not obstruction_report.get('blocked')):
|
||||
status = 'Pop preview ready: recording starts when you drive; controls OFF'
|
||||
data.update(cruise_speed_mph=controller.cruise_set_speed, status=status,
|
||||
provider=brain.active_provider, dry_run=args.dry_run, camera_mode=args.camera,
|
||||
model_label=selected_model["label"], driving_mode=controller.driving_mode)
|
||||
data['fsd_engaged'] = engaged
|
||||
save_idle = (not motion_clock or motion_clock.started_at is not None
|
||||
or loop_start >= next_idle_record_at)
|
||||
if recorder and captured_this_loop and save_idle:
|
||||
if motion_clock and motion_clock.started_at is None:
|
||||
# Waiting is indefinite; save only sparse parked evidence.
|
||||
recorder.image_interval = 1.
|
||||
next_idle_record_at = loop_start + 1.
|
||||
paired_data = dict(inference_telemetry, fsd_engaged=engaged,
|
||||
control_command=last_control_command, status=status,
|
||||
driving_mode=controller.driving_mode,
|
||||
control_telemetry={key:data.get(key) for key in (
|
||||
'timestamp', 'valid', 'speed_mph', 'engine_rpm', 'gear', 'park_brake',
|
||||
'steering', 'throttle', 'brake', 'user_steering', 'user_throttle', 'user_brake')})
|
||||
if motion_clock:
|
||||
paired_data['preview_recording'] = data['preview_recording']
|
||||
if pop_controller:
|
||||
paired_data['evidence_writer'] = recorder.get_status()
|
||||
recorder.record(camera, perception, paired_data,
|
||||
last_inference_ms if inferred_this_loop else None, vision_reason,
|
||||
wide_image=getattr(capture, 'wide_camera', None))
|
||||
if pop_controller:
|
||||
data['evidence_writer'] = recorder.get_status()
|
||||
if args.path_preview:
|
||||
data["driving_mode"] = "path-preview"
|
||||
if status != last_status:
|
||||
log.info("STATUS: %s", status)
|
||||
last_status = status
|
||||
if not args.no_hud:
|
||||
# Passive Pop rendering is budgeted at 5 Hz. Input events
|
||||
# still run each loop; model capture keeps its 20 Hz target.
|
||||
hud_now = time.monotonic()
|
||||
if not pop_controller or hud_now >= next_hud_render_at:
|
||||
frame = hud.render(display_perception, data, engaged, camera,
|
||||
fps=loop_fps,
|
||||
inference_ms=last_inference_ms)
|
||||
cv2.imshow(TITLE, frame)
|
||||
next_hud_render_at = hud_now + .2
|
||||
# pollKey handles panel events without adding the Windows
|
||||
# waitKey timer delay to every passive model frame.
|
||||
key = (cv2.pollKey() if pop_controller else cv2.waitKey(1)) & 0xFF
|
||||
if key in (ord("m"), ord("M")):
|
||||
hud.toggle_mode()
|
||||
if key in (ord("c"), ord("C")):
|
||||
setting_reason = parked_setting_reason(data, engaged, pending_until is not None)
|
||||
if setting_reason:
|
||||
status = "Manual settings: " + setting_reason
|
||||
elif navigation_driver:
|
||||
status = 'GPS driving trial uses Chill mode; exit the trial to change modes'
|
||||
elif args.camera == "auxiliary" and not (args.dry_run or args.inset_cruise_test):
|
||||
status = "Inset supports manual pedals; cruise needs the bounded test launcher"
|
||||
else:
|
||||
modes = ("manual", "cruise", "chill")
|
||||
controller.release_all_controls()
|
||||
args.driving_mode = modes[(modes.index(controller.driving_mode)+1) % len(modes)]
|
||||
controller.set_driving_mode(args.driving_mode)
|
||||
args.lane_only = args.driving_mode == "manual"
|
||||
monitor.set_ignore_pedals(args.lane_only or args.dry_run)
|
||||
status = "Manual settings: driving mode " + args.driving_mode
|
||||
log.info("Driving mode changed while parked: %s", args.driving_mode)
|
||||
if key in (ord("n"), ord("N")):
|
||||
setting_reason = parked_setting_reason(data, engaged, pending_until is not None)
|
||||
compatible = [e for e in registry.inventory() if e["compatible"]]
|
||||
if setting_reason:
|
||||
status = "Manual settings: " + setting_reason
|
||||
elif recorder:
|
||||
status = "Manual settings: finish the calibration recording before changing model"
|
||||
elif len(compatible) < 2:
|
||||
status = "Manual settings: only one compatible model is installed"
|
||||
else:
|
||||
try:
|
||||
ids = [e["id"] for e in compatible]
|
||||
candidate = registry.select(ids[(ids.index(args.model)+1) % len(ids)])
|
||||
digest = candidate["metadata"]["sha256"]
|
||||
if not args.dry_run and digest != model_manifest["sha256"]:
|
||||
raise ValueError("New model requires passive evaluation and camera recalibration")
|
||||
controller.release_all_controls()
|
||||
if candidate['metadata'].get('preview_only') and not args.dry_run:
|
||||
raise ValueError('Selected model is currently preview only')
|
||||
candidate_brain = create_brain(candidate,
|
||||
use_gpu=args.inference_provider != "cpu")
|
||||
if args.inference_provider == "directml" and candidate_brain.active_provider != "DmlExecutionProvider":
|
||||
raise ValueError("DirectML is unavailable")
|
||||
candidate_perception = candidate_brain.step(np.zeros((1,12,128,256), np.float32))
|
||||
capture.reset_history()
|
||||
brain, perception, selected_model = candidate_brain, candidate_perception, candidate
|
||||
args.model, model_manifest = candidate["id"], candidate["metadata"]
|
||||
last_inference_at, inference_telemetry = None, None
|
||||
pop_controller = (PopTrajectoryController()
|
||||
if args.path_preview and selected_model.get('id') == 'pop-v2' else None)
|
||||
pop_actions = PopModelActions() if pop_controller else None
|
||||
pop_decision = None
|
||||
if signal_preview:
|
||||
signal_preview.reset()
|
||||
status = "Manual settings: model " + candidate["label"]
|
||||
log.info("Parked model change: id=%s hash=%s", args.model, digest)
|
||||
except Exception as exc:
|
||||
log.exception("Model change failed; keeping the previous model")
|
||||
status = "Manual settings: model change blocked: " + str(exc)
|
||||
if key in (ord("q"), ord("Q")):
|
||||
break
|
||||
if cv2.getWindowProperty(TITLE, cv2.WND_PROP_VISIBLE) < 1:
|
||||
break
|
||||
time.sleep(max(0.0, 0.05 - (time.monotonic() - loop_start)))
|
||||
except KeyboardInterrupt:
|
||||
log.info("Stopped")
|
||||
except Exception:
|
||||
log.exception("Runtime stopped; releasing controls")
|
||||
raise
|
||||
finally:
|
||||
traffic.close()
|
||||
road_geometry.close()
|
||||
if navigation:
|
||||
navigation.close()
|
||||
if recorder:
|
||||
try:
|
||||
recorder.close()
|
||||
except Exception:
|
||||
log.exception("Could not close calibration recorder")
|
||||
for cleanup in (controller.close, monitor.close, telemetry.close,
|
||||
capture.close, cv2.destroyAllWindows):
|
||||
try:
|
||||
cleanup()
|
||||
except Exception:
|
||||
log.exception("Cleanup failed: %s", cleanup)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,19 @@
|
||||
SiiNunit
|
||||
{
|
||||
ui::text_template : txt.atsop_tesla.speed {
|
||||
name: "ATS OP Tesla speed"
|
||||
text: "<align hstyle=center><color value=ffececec><font face=/font/big.font xscale=12 yscale=12>%0</font></align>"
|
||||
}
|
||||
ui::text_template : txt.atsop_tesla.value {
|
||||
name: "ATS OP Tesla value"
|
||||
text: "<align hstyle=center><color value=ffececec><font face=/font/big.font xscale=4.5 yscale=4.5>%0</font></align>"
|
||||
}
|
||||
ui::text_template : txt.atsop_tesla.unit {
|
||||
name: "ATS OP Tesla value with unit"
|
||||
text: "<align hstyle=center><color value=ffececec><font face=/font/big.font xscale=3 yscale=3>%0 %1</font></align>"
|
||||
}
|
||||
ui::text_template : txt.atsop_tesla.clock {
|
||||
name: "ATS OP Tesla clock"
|
||||
text: "<align hstyle=center><color value=ffececec><font face=/font/big.font xscale=2 yscale=2>%0</font></align>"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
"""
|
||||
OpenPilot Neural Perception Brain
|
||||
Runs comma.ai's Supercombo ONNX driving model on AMD Radeon GPU using DirectML.
|
||||
Parses full 3D trajectory plans, lane lines, road edges, lead cars, and meta predictions.
|
||||
"""
|
||||
|
||||
import os
|
||||
import hashlib
|
||||
import json
|
||||
import numpy as np
|
||||
import onnxruntime as ort
|
||||
|
||||
# Re-export the old public imports for existing decoder clients.
|
||||
from model.perception import (Perception, OpenPilotPerception, TrajectoryPlan,
|
||||
LaneLines, LeadVehicle, X_IDXS)
|
||||
|
||||
class OpenPilotBrain:
|
||||
def __init__(self, model_path="models/supercombo.onnx", use_gpu=True, manifest_path=None):
|
||||
self.model_path = os.path.abspath(model_path)
|
||||
if not os.path.exists(self.model_path):
|
||||
raise FileNotFoundError(f"Model file not found at {self.model_path}")
|
||||
|
||||
manifest_path = manifest_path or os.path.join(os.path.dirname(self.model_path), "manifest.json")
|
||||
with open(manifest_path, encoding="utf-8") as manifest_file:
|
||||
manifest = json.load(manifest_file)
|
||||
if manifest.get("output_layout") != "historical supercombo 6409":
|
||||
raise ValueError("Unsupported model decoder layout")
|
||||
with open(self.model_path, "rb") as model_file:
|
||||
digest = hashlib.file_digest(model_file, "sha256").hexdigest()
|
||||
if digest != manifest["sha256"]:
|
||||
raise ValueError("Model hash differs from the pinned 6409-output model")
|
||||
|
||||
# Choose execution providers
|
||||
providers = [p for p in ['DmlExecutionProvider', 'CPUExecutionProvider']
|
||||
if p in ort.get_available_providers()] if use_gpu else ['CPUExecutionProvider']
|
||||
|
||||
# Session options for low latency
|
||||
opts = ort.SessionOptions()
|
||||
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
||||
opts.enable_mem_pattern = False
|
||||
opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
|
||||
|
||||
self.session = ort.InferenceSession(self.model_path, sess_options=opts, providers=providers)
|
||||
self.active_provider = self.session.get_providers()[0]
|
||||
expected = {'input_imgs': [1, 12, 128, 256], 'desire': [1, 8],
|
||||
'traffic_convention': [1, 2], 'initial_state': [1, 512]}
|
||||
outputs = self.session.get_outputs()
|
||||
if ({i.name: i.shape for i in self.session.get_inputs()} != expected
|
||||
or len(outputs) != 1 or outputs[0].shape != [1, 6409]
|
||||
or any(i.type != 'tensor(float)' for i in self.session.get_inputs()+outputs)):
|
||||
raise ValueError("Unsupported model tensor contract")
|
||||
|
||||
# State tensors
|
||||
self.recurrent_state = np.zeros((1, 512), dtype=np.float32)
|
||||
self.desire = np.zeros((1, 8), dtype=np.float32)
|
||||
# Historical model consumes rising-edge desire pulses; keep lane is zero.
|
||||
self.traffic_convention = np.array([[1.0, 0.0]], dtype=np.float32) # Right-hand traffic (US / ATS)
|
||||
|
||||
def set_desire(self, desire_type="none"):
|
||||
"""
|
||||
Sets lane change intent: 'none', 'left', 'right'
|
||||
"""
|
||||
self.desire.fill(0.0)
|
||||
if desire_type == "left":
|
||||
self.desire[0, 3] = 1.0 # laneChangeLeft
|
||||
elif desire_type == "right":
|
||||
self.desire[0, 4] = 1.0 # laneChangeRight
|
||||
|
||||
def reset_state(self):
|
||||
"""Resets recurrent hidden state (e.g. on new trip or disengagement)."""
|
||||
self.recurrent_state.fill(0.0)
|
||||
self.desire.fill(0.0)
|
||||
|
||||
def step(self, input_imgs):
|
||||
"""
|
||||
Runs one step of perception on (1, 12, 128, 256) image input.
|
||||
Returns OpenPilotPerception dataclass.
|
||||
"""
|
||||
inputs = {
|
||||
'input_imgs': input_imgs,
|
||||
'desire': self.desire,
|
||||
'traffic_convention': self.traffic_convention,
|
||||
'initial_state': self.recurrent_state
|
||||
}
|
||||
|
||||
res = self.session.run(None, inputs)[0][0]
|
||||
self.desire.fill(0.0)
|
||||
return self.parse_outputs(res)
|
||||
|
||||
def parse_outputs(self, res):
|
||||
"""Decode the historical 6409 layout in reference/driving.cc."""
|
||||
res = np.asarray(res, dtype=np.float32)
|
||||
if res.shape != (6409,) or not np.all(np.isfinite(res)):
|
||||
raise ValueError("Model returned invalid outputs")
|
||||
|
||||
# Update recurrent state for next frame (last 512 floats)
|
||||
self.recurrent_state[0, :] = res[5897:6409]
|
||||
|
||||
# 1. Parse 5 Trajectory Plans (0 to 4955)
|
||||
# Each plan has 991 floats: mean (33*15), std (33*15), prob (1)
|
||||
plan_len = 991
|
||||
best_hyp = 0
|
||||
best_prob = -1e9
|
||||
for i in range(5):
|
||||
prob = res[i * plan_len + 990]
|
||||
if prob > best_prob:
|
||||
best_prob = prob
|
||||
best_hyp = i
|
||||
|
||||
best_offset = best_hyp * plan_len
|
||||
logits = np.array([res[i * plan_len + 990] for i in range(5)])
|
||||
weights = np.exp(logits - np.max(logits))
|
||||
best_weight = weights[best_hyp] / weights.sum()
|
||||
# Mean trajectory: 33 points x 15 elements
|
||||
# Columns: pos(x,y,z)=0..2, vel(x,y,z)=3..5, acc(x,y,z)=6..8
|
||||
mean_data = res[best_offset : best_offset + 33 * 15].reshape((33, 15))
|
||||
pos_x = mean_data[:, 0]
|
||||
pos_y = mean_data[:, 1]
|
||||
pos_z = mean_data[:, 2]
|
||||
vel_x = mean_data[:, 3]
|
||||
|
||||
# Compute curvature at ~12m lookahead (waypoint idx 8)
|
||||
lookahead_idx = 8
|
||||
lx = max(3.0, pos_x[lookahead_idx])
|
||||
ly = pos_y[lookahead_idx]
|
||||
curv = 2.0 * ly / (lx * lx)
|
||||
|
||||
plan = TrajectoryPlan(
|
||||
x=pos_x,
|
||||
y=pos_y,
|
||||
z=pos_z,
|
||||
velocity=vel_x,
|
||||
curvature=curv,
|
||||
prob=float(best_weight)
|
||||
)
|
||||
|
||||
# 2. Parse Lane Lines (4955 to 5483)
|
||||
# 4 lines x 33 points x 2 (y, z) = 264 for mean
|
||||
lanes_mean = res[4955 : 4955 + 264].reshape((4, 33, 2))
|
||||
# Line 1: left near, Line 2: right near
|
||||
left_y = lanes_mean[1, :, 0]
|
||||
left_z = lanes_mean[1, :, 1]
|
||||
right_y = lanes_mean[2, :, 0]
|
||||
right_z = lanes_mean[2, :, 1]
|
||||
|
||||
# Lane probabilities (5483 to 5491)
|
||||
lane_probs = res[5483 : 5491]
|
||||
# Sigmoid on probabilities
|
||||
lp_sig = 1.0 / (1.0 + np.exp(-np.clip(lane_probs, -80.0, 80.0)))
|
||||
left_prob = float(lp_sig[3])
|
||||
right_prob = float(lp_sig[5])
|
||||
|
||||
lanes = LaneLines(
|
||||
left_y=left_y,
|
||||
left_z=left_z,
|
||||
right_y=right_y,
|
||||
right_z=right_z,
|
||||
left_prob=left_prob,
|
||||
right_prob=right_prob,
|
||||
x=X_IDXS.copy(),
|
||||
all_y=lanes_mean[:, :, 0].copy(),
|
||||
all_z=lanes_mean[:, :, 1].copy(),
|
||||
probabilities=lp_sig[1::2].copy()
|
||||
)
|
||||
|
||||
# 3. Parse Lead Vehicle (around 5755 to 5850)
|
||||
# Five hypotheses describe alternatives for ONE lead; selection column
|
||||
# 8 is t=0. Columns 9/10 predict that lead at t=2/4, not other cars.
|
||||
leads = res[5755:5810].reshape((5, 11))
|
||||
lead_slice = leads[int(np.argmax(leads[:, 8]))]
|
||||
lead_dist = float(lead_slice[0])
|
||||
lead_v = float(lead_slice[2])
|
||||
# Lead probability in lead prediction
|
||||
lead_prob = 1.0 / (1.0 + np.exp(-float(np.clip(res[5810], -80.0, 80.0))))
|
||||
lead_detected = bool(lead_prob > 0.6 and 0.0 < lead_dist < 120.0 and abs(float(lead_slice[1])) < 2.5)
|
||||
|
||||
lead = LeadVehicle(
|
||||
detected=lead_detected,
|
||||
distance=max(0.0, lead_dist) if lead_detected else 999.0,
|
||||
rel_speed=lead_v if lead_detected else 0.0,
|
||||
prob=float(lead_prob),
|
||||
lateral_offset=float(lead_slice[1])
|
||||
)
|
||||
|
||||
return OpenPilotPerception(
|
||||
plan=plan,
|
||||
lanes=lanes,
|
||||
lead=lead,
|
||||
raw_outputs=res
|
||||
)
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Shared driving observations, independent of any model inference runtime.
|
||||
|
||||
The legacy sample grid remains the fallback for observations without their own
|
||||
longitudinal coordinates. Adapters may attach additional evidence to Perception
|
||||
as before; this module neither loads a model nor chooses a driving policy.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
# Legacy 33-point longitudinal sampling, in metres. Keep the original dtype and
|
||||
# values: existing lane and road-edge fallback geometry relies on this grid.
|
||||
X_IDXS = np.array([
|
||||
0.0, 0.1875, 0.75, 1.6875, 3.0, 4.6875,
|
||||
6.75, 9.1875, 12.0, 15.1875, 18.75, 22.6875,
|
||||
27.0, 31.6875, 36.75, 42.1875, 48.0, 54.1875,
|
||||
60.75, 67.6875, 75.0, 82.6875, 90.75, 99.1875,
|
||||
108.0, 117.1875, 126.75, 136.6875, 147.0, 157.6875,
|
||||
168.75, 180.1875, 192.0
|
||||
], dtype=np.float32)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TrajectoryPlan:
|
||||
x: np.ndarray # 33 waypoints longitudinal (m)
|
||||
y: np.ndarray # 33 waypoints lateral (m)
|
||||
z: np.ndarray # 33 waypoints vertical (m)
|
||||
velocity: np.ndarray # 33 waypoints speed (m/s)
|
||||
curvature: float # target steering curvature at lookahead
|
||||
prob: float # confidence of chosen plan hypothesis
|
||||
|
||||
|
||||
@dataclass
|
||||
class LaneLines:
|
||||
left_y: np.ndarray
|
||||
left_z: np.ndarray
|
||||
right_y: np.ndarray
|
||||
right_z: np.ndarray
|
||||
left_prob: float
|
||||
right_prob: float
|
||||
x: np.ndarray = None
|
||||
# Official v0.8.5 order: outer left, ego left, ego right, outer right.
|
||||
# These are observed lines, not proof of four drivable lanes.
|
||||
all_y: np.ndarray = None
|
||||
all_z: np.ndarray = None
|
||||
probabilities: np.ndarray = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class LeadVehicle:
|
||||
detected: bool
|
||||
distance: float # meters ahead
|
||||
rel_speed: float # m/s relative speed
|
||||
prob: float
|
||||
lateral_offset: float = 0.0 # model coordinates: positive is right
|
||||
|
||||
|
||||
@dataclass
|
||||
class Perception:
|
||||
plan: TrajectoryPlan
|
||||
lanes: LaneLines
|
||||
lead: LeadVehicle
|
||||
raw_outputs: np.ndarray
|
||||
|
||||
|
||||
# Existing callers and old serialized class references resolve to the same type.
|
||||
OpenPilotPerception = Perception
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
"""Pinned Pop v2 split ONNX runner; experimental simulator preview only.
|
||||
|
||||
The default MED inset is duplicated for comparison. Callers may provide a
|
||||
separate SBIG frame, explicitly not proof of camera calibration.
|
||||
Temporal sampling uses timestamps rather than assuming the ATS loop is 20 Hz.
|
||||
"""
|
||||
from collections import deque
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import onnxruntime as ort
|
||||
|
||||
from model.perception import (Perception, OpenPilotPerception, TrajectoryPlan, LaneLines,
|
||||
LeadVehicle, X_IDXS)
|
||||
|
||||
CONTRACT = "pop-v2-split-1576-1000"
|
||||
|
||||
|
||||
class PopV2Brain:
|
||||
def __init__(self, model_path, use_gpu=True, manifest_path=None):
|
||||
self.model_path = str(Path(model_path).resolve())
|
||||
parent = Path(self.model_path).parent
|
||||
manifest = json.loads(Path(manifest_path or parent / 'manifest.json').read_text())
|
||||
if manifest.get('output_layout') != CONTRACT:
|
||||
raise ValueError('Unsupported Pop v2 model layout')
|
||||
policy = (parent / manifest['policy_file']).resolve()
|
||||
if not policy.is_relative_to(parent):
|
||||
raise ValueError('Pop v2 policy must be inside its model directory')
|
||||
for path, key in ((Path(self.model_path), 'sha256'), (policy, 'policy_sha256')):
|
||||
with path.open('rb') as stream:
|
||||
digest = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
if digest != manifest[key]:
|
||||
raise ValueError('Pop v2 model hash differs from its manifest')
|
||||
providers = ([p for p in ('DmlExecutionProvider', 'CPUExecutionProvider')
|
||||
if p in ort.get_available_providers()] if use_gpu
|
||||
else ['CPUExecutionProvider'])
|
||||
options = ort.SessionOptions()
|
||||
options.enable_mem_pattern = False
|
||||
options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
|
||||
# Avoid competing with ATS across every CPU core.
|
||||
options.intra_op_num_threads = 2
|
||||
self.vision = ort.InferenceSession(self.model_path, options, providers=providers)
|
||||
self.policy = ort.InferenceSession(str(policy), options, providers=providers)
|
||||
self.active_provider = self.vision.get_providers()[0]
|
||||
if self.active_provider != self.policy.get_providers()[0]:
|
||||
raise ValueError('Pop v2 sessions use different providers')
|
||||
expected_vision = {'img': ([1, 12, 128, 256], 'tensor(uint8)'),
|
||||
'big_img': ([1, 12, 128, 256], 'tensor(uint8)')}
|
||||
expected_policy = {'desire_pulse': ([1, 25, 8], 'tensor(float16)'),
|
||||
'traffic_convention': ([1, 2], 'tensor(float16)'),
|
||||
'features_buffer': ([1, 25, 512], 'tensor(float16)')}
|
||||
for session, expected, output_size in ((self.vision, expected_vision, 1576),
|
||||
(self.policy, expected_policy, 1000)):
|
||||
outputs = session.get_outputs()
|
||||
if ({i.name: (i.shape, i.type) for i in session.get_inputs()} != expected
|
||||
or len(outputs) != 1 or outputs[0].shape != [1, output_size]
|
||||
or outputs[0].type != 'tensor(float16)'):
|
||||
raise ValueError('Unsupported Pop v2 tensor contract')
|
||||
self.desire = np.zeros(8, np.float16)
|
||||
self.traffic_convention = np.array([[1, 0]], np.float16)
|
||||
self.reset_state()
|
||||
|
||||
def reset_state(self):
|
||||
self.images = deque()
|
||||
self.wide_images = deque()
|
||||
self.pending_wide_input = None
|
||||
self.camera_input_mode = 'narrow-duplicated'
|
||||
self.features = deque()
|
||||
self.pulses = deque()
|
||||
self.desire.fill(0)
|
||||
self.last_timestamp = None
|
||||
self.temporal_ready = False
|
||||
self.temporal_coverage = {}
|
||||
|
||||
def set_wide_input(self, parsed):
|
||||
"""Supply one current SBIG frame; consumed by the next step only.
|
||||
|
||||
The caller derives MED separately from the same source exposure. The
|
||||
supplied projection is not independently validated by this adapter.
|
||||
"""
|
||||
self.pending_wide_input = None
|
||||
if parsed is None:
|
||||
return
|
||||
frame = np.asarray(parsed)
|
||||
if (frame.shape != (6, 128, 256)
|
||||
or frame.dtype not in (np.dtype(np.uint8), np.dtype(np.float32))
|
||||
or not np.all(np.isfinite(frame))
|
||||
or frame.min() < 0 or frame.max() > 255):
|
||||
raise ValueError('Invalid Pop v2 wide image input')
|
||||
self.pending_wide_input = frame.astype(np.uint8, copy=True)
|
||||
|
||||
def set_desire(self, desire_type='none'):
|
||||
self.desire.fill(0)
|
||||
if desire_type in ('left', 'right'):
|
||||
self.desire[3 if desire_type == 'left' else 4] = 1
|
||||
|
||||
@staticmethod
|
||||
def _sample_entry(history, timestamp):
|
||||
for t, value in reversed(history):
|
||||
if t <= timestamp + 1e-6:
|
||||
# Never fill a missing temporal interval with a stale image.
|
||||
if timestamp - t <= 0.10:
|
||||
return t, value
|
||||
break
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _sample(history, timestamp, width):
|
||||
entry = PopV2Brain._sample_entry(history, timestamp)
|
||||
if entry is not None:
|
||||
return entry[1]
|
||||
return np.zeros(width, np.float16)
|
||||
|
||||
def _feature_gap_limit(self):
|
||||
"""Permit continuous CPU cadence without bridging a dropped interval.
|
||||
|
||||
The policy grid is 5 Hz even when inference runs slightly below 5 Hz.
|
||||
A past-only 100 ms lookup leaves roughly half of that real history zero.
|
||||
Resampling must still reject a gap that is abnormal for this run, and
|
||||
never bridge more than 250 ms regardless of the observed cadence.
|
||||
"""
|
||||
gaps = np.diff([entry[0] for entry in self.features])
|
||||
if not gaps.size:
|
||||
return .10
|
||||
return min(.25, max(.10, 1.75 * float(np.median(gaps))))
|
||||
|
||||
def _feature_sample(self, timestamp, gap_limit):
|
||||
"""Return a real sample or bounded interpolation of two real features.
|
||||
|
||||
Historical targets may use a later recorded feature, already available
|
||||
at the current inference. No extrapolation, stale repetition, pixel
|
||||
interpolation, or fabricated inference is allowed. The explicit sample
|
||||
kind and bracket width are included in coverage evidence below.
|
||||
"""
|
||||
earlier = None
|
||||
for t, value in self.features:
|
||||
if abs(t - timestamp) <= 1e-6:
|
||||
return value, 'observed', 0., 0.
|
||||
if t < timestamp:
|
||||
earlier = (t, value)
|
||||
continue
|
||||
if earlier is None:
|
||||
return None
|
||||
before, left = earlier
|
||||
gap = t - before
|
||||
if gap > gap_limit + 1e-6:
|
||||
return None
|
||||
alpha = (timestamp - before) / gap
|
||||
# Float32 avoids cancellation/overflow during half-precision math.
|
||||
sampled = (left.astype(np.float32) * (1. - alpha)
|
||||
+ value.astype(np.float32) * alpha).astype(np.float16)
|
||||
return sampled, 'interpolated', max(timestamp - before, t - timestamp), gap
|
||||
return None
|
||||
|
||||
def _feature_context(self, timestamp):
|
||||
limit = self._feature_gap_limit()
|
||||
return ([self._feature_sample(timestamp - .2*i, limit)
|
||||
for i in range(24, -1, -1)], limit)
|
||||
|
||||
def _context_coverage(self, timestamp):
|
||||
"""Measure availability independently of tensor values or elapsed time.
|
||||
|
||||
Complete bounded context does not validate the upstream 20 Hz cadence
|
||||
or rendered camera calibration. Interpolated slots are reported apart
|
||||
from observed slots. Zero-valued real features remain valid.
|
||||
"""
|
||||
entries, gap_limit = self._feature_context(timestamp)
|
||||
present = sum(entry is not None for entry in entries)
|
||||
narrow_present = self._sample_entry(self.images, timestamp - .2) is not None
|
||||
wide_required = self.camera_input_mode == 'sbig-with-derived-med'
|
||||
wide_present = (self._sample_entry(self.wide_images, timestamp - .2) is not None
|
||||
if wide_required else narrow_present)
|
||||
ages = [entry[2] for entry in entries if entry is not None]
|
||||
brackets = [entry[3] for entry in entries if entry is not None]
|
||||
gaps = [right[0] - left[0] for left, right in zip(self.features,
|
||||
list(self.features)[1:])]
|
||||
span = (timestamp - self.features[0][0]) if self.features else 0.
|
||||
return dict(feature_slots_present=present, feature_slots_required=25,
|
||||
feature_slots_observed=sum(e is not None and e[1] == 'observed'
|
||||
for e in entries),
|
||||
feature_slots_interpolated=sum(e is not None and e[1] == 'interpolated'
|
||||
for e in entries),
|
||||
feature_sampling='bounded-linear-between-real-features',
|
||||
feature_bracket_limit_s=gap_limit,
|
||||
max_feature_bracket_s=max(brackets) if brackets else None,
|
||||
real_feature_samples=len(self.features),
|
||||
narrow_pair_present=narrow_present, wide_pair_present=wide_present,
|
||||
wide_pair_required=wide_required,
|
||||
complete=present == 25 and narrow_present and wide_present,
|
||||
max_sample_age_s=max(ages) if ages else None,
|
||||
sample_age_limit_s=gap_limit, camera_sample_age_limit_s=.10,
|
||||
expected_run_hz=20,
|
||||
observed_run_hz=(len(self.features)-1)/span if span > 0 else None,
|
||||
max_inference_gap_s=max(gaps) if gaps else None,
|
||||
upstream_cadence_validated=False)
|
||||
|
||||
def step(self, input_imgs, timestamp=None):
|
||||
wide_current = self.pending_wide_input
|
||||
self.pending_wide_input = None
|
||||
timestamp = time.monotonic() if timestamp is None else float(timestamp)
|
||||
imgs = np.asarray(input_imgs)
|
||||
if (imgs.shape != (1, 12, 128, 256) or not np.isfinite(timestamp)
|
||||
or not np.all(np.isfinite(imgs)) or imgs.min() < 0 or imgs.max() > 255):
|
||||
raise ValueError('Invalid Pop v2 image input')
|
||||
if self.last_timestamp is not None:
|
||||
delta = timestamp - self.last_timestamp
|
||||
if delta <= 0:
|
||||
raise ValueError('Pop v2 timestamps must increase')
|
||||
# A brief missing camera frame leaves an unsupported interval in
|
||||
# the bounded sampler; it need not discard all earlier evidence.
|
||||
# Long pauses still start a completely new temporal context.
|
||||
if delta >= .5:
|
||||
self.reset_state()
|
||||
mode = ('sbig-with-derived-med' if wide_current is not None
|
||||
else 'narrow-duplicated')
|
||||
if self.last_timestamp is not None and mode != self.camera_input_mode:
|
||||
# A change of projection must not share a policy feature history.
|
||||
self.reset_state()
|
||||
self.camera_input_mode = mode
|
||||
current = imgs[0, 6:].astype(np.uint8)
|
||||
self.images.append((timestamp, current))
|
||||
if wide_current is not None:
|
||||
self.wide_images.append((timestamp, wide_current))
|
||||
else:
|
||||
self.wide_images.clear()
|
||||
for history in (self.images, self.wide_images, self.features, self.pulses):
|
||||
while history and history[0][0] < timestamp - 5.1:
|
||||
history.popleft()
|
||||
old = self._sample(self.images, timestamp - .2, current.shape).astype(np.uint8)
|
||||
image_pair = np.concatenate((old, current), axis=0)[None]
|
||||
wide_pair = image_pair
|
||||
if wide_current is not None:
|
||||
wide_old = self._sample(self.wide_images, timestamp - .2,
|
||||
wide_current.shape).astype(np.uint8)
|
||||
wide_pair = np.concatenate((wide_old, wide_current), axis=0)[None]
|
||||
v = self.vision.run(None, {'img': image_pair, 'big_img': wide_pair})[0][0]
|
||||
if v.shape != (1576,) or not np.all(np.isfinite(v)):
|
||||
raise ValueError('Pop v2 returned invalid vision outputs')
|
||||
self.features.append((timestamp, v[1064:1576].copy()))
|
||||
self.pulses.append((timestamp, self.desire.copy()))
|
||||
feature_context, _ = self._feature_context(timestamp)
|
||||
feature_input = np.stack([entry[0] if entry is not None else np.zeros(512, np.float16)
|
||||
for entry in feature_context])[None].astype(np.float16)
|
||||
pulse_input = np.zeros((1, 25, 8), np.float16)
|
||||
for i in range(25):
|
||||
end = timestamp - .2*(24-i)
|
||||
for t, pulse in self.pulses:
|
||||
if end - .2 < t <= end + 1e-6:
|
||||
pulse_input[0, i] = np.maximum(pulse_input[0, i], pulse)
|
||||
p = self.policy.run(None, {'features_buffer': feature_input,
|
||||
'desire_pulse': pulse_input,
|
||||
'traffic_convention': self.traffic_convention})[0][0]
|
||||
self.desire.fill(0)
|
||||
self.temporal_coverage = self._context_coverage(timestamp)
|
||||
self.temporal_ready = self.temporal_coverage['complete']
|
||||
self.last_timestamp = timestamp
|
||||
return self.parse_outputs(v, p)
|
||||
|
||||
def parse_outputs(self, vision, policy):
|
||||
v, p = np.asarray(vision, np.float32), np.asarray(policy, np.float32)
|
||||
if (v.shape != (1576,) or p.shape != (1000,)
|
||||
or not np.all(np.isfinite(v)) or not np.all(np.isfinite(p))):
|
||||
raise ValueError('Pop v2 returned invalid outputs')
|
||||
mean = p[:495].reshape(33, 15)
|
||||
lx, ly = max(3., float(mean[8, 0])), float(mean[8, 1])
|
||||
plan = TrajectoryPlan(mean[:, 0].copy(), mean[:, 1].copy(), mean[:, 2].copy(),
|
||||
mean[:, 3].copy(), 2*ly/(lx*lx), None)
|
||||
lane_mean = v[117:381].reshape(4, 33, 2)
|
||||
probabilities = (1/(1+np.exp(np.clip(-v[645:653], -np.inf, 11))))[1::2]
|
||||
lanes = LaneLines(lane_mean[1, :, 0].copy(), lane_mean[1, :, 1].copy(),
|
||||
lane_mean[2, :, 0].copy(), lane_mean[2, :, 1].copy(),
|
||||
float(probabilities[1]), float(probabilities[2]),
|
||||
X_IDXS.copy(), lane_mean[:, :, 0].copy(),
|
||||
lane_mean[:, :, 1].copy(), probabilities.copy())
|
||||
# Three temporal predictions of one lead, not three nearby vehicles.
|
||||
first_lead = v[917:989].reshape(3, 6, 4)[0, 0]
|
||||
prob = float(1/(1+math.exp(min(-float(v[1061]), 11))))
|
||||
dist, lateral, velocity = map(float, first_lead[:3])
|
||||
detected = prob > .6 and 0 < dist < 120 and abs(lateral) < 2.5
|
||||
lead = LeadVehicle(detected, dist if detected else 999., 0., prob, lateral)
|
||||
perception = Perception(plan, lanes, lead, np.concatenate((v, p)))
|
||||
# Keep uncertainty and road edges available for future trajectory gates.
|
||||
perception.road_edges = v[653:785].reshape(2, 33, 2).copy()
|
||||
perception.road_edge_std = np.exp(np.clip(v[785:917].reshape(2, 33, 2), -np.inf, 11))
|
||||
perception.plan_std = np.exp(np.clip(p[495:990].reshape(33, 15), -np.inf, 11))
|
||||
# Modern unary plan columns from the pinned ModelConstants/Plan layout.
|
||||
# Additive evidence only: preserve the legacy TrajectoryPlan interface.
|
||||
perception.velocity_xyz = mean[:, 3:6].copy()
|
||||
perception.acceleration_xyz = mean[:, 6:9].copy()
|
||||
perception.orientation_xyz = mean[:, 9:12].copy()
|
||||
perception.orientation_rate_xyz = mean[:, 12:15].copy()
|
||||
perception.plan_times = 10. * (np.arange(33, dtype=np.float64) / 32.) ** 2
|
||||
perception.pop_plan_contract = CONTRACT
|
||||
perception.lead_speed_mps = velocity
|
||||
perception.lead_velocity_semantics = 'upstream lead.v; relativity not validated'
|
||||
perception.camera_input_mode = self.camera_input_mode
|
||||
return perception
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Explicit local model selection; each entry keeps its own pinned manifest."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
CONTRACT = "historical supercombo 6409"
|
||||
POP_CONTRACT = "pop-v2-split-1576-1000"
|
||||
|
||||
|
||||
class ModelRegistry:
|
||||
def __init__(self, directory):
|
||||
self.directory = Path(directory).resolve()
|
||||
self.entries = json.loads((self.directory / "registry.json").read_text(encoding="utf-8"))
|
||||
ids = [entry["id"] for entry in self.entries]
|
||||
if len(ids) != len(set(ids)) or not ids:
|
||||
raise ValueError("Model registry needs unique model IDs")
|
||||
|
||||
def select(self, model_id):
|
||||
entry = next((e for e in self.entries if e["id"] == model_id), None)
|
||||
if entry is None:
|
||||
raise ValueError("Unknown model ID: " + model_id)
|
||||
paths = []
|
||||
for field in ("file", "manifest"):
|
||||
path = (self.directory / entry[field]).resolve()
|
||||
if not path.is_relative_to(self.directory):
|
||||
raise ValueError("Registered model files must be inside models/")
|
||||
paths.append(path)
|
||||
model_path, manifest_path = paths
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
if manifest.get("output_layout") not in (CONTRACT, POP_CONTRACT):
|
||||
raise ValueError("Model needs a different decoder/runner adapter")
|
||||
digest = manifest.get("sha256", "")
|
||||
if not re.fullmatch("[0-9a-f]{64}", digest):
|
||||
raise ValueError("Model manifest needs a SHA-256 pin")
|
||||
with model_path.open("rb") as stream:
|
||||
actual = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if actual != digest:
|
||||
raise ValueError("Registered model hash differs from its manifest")
|
||||
if manifest['output_layout'] == POP_CONTRACT:
|
||||
policy = (model_path.parent / manifest['policy_file']).resolve()
|
||||
if not policy.is_relative_to(model_path.parent):
|
||||
raise ValueError('Registered policy must be inside its model directory')
|
||||
pin = manifest.get('policy_sha256', '')
|
||||
if not re.fullmatch('[0-9a-f]{64}', pin):
|
||||
raise ValueError('Policy manifest needs a SHA-256 pin')
|
||||
with policy.open('rb') as stream:
|
||||
actual = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
if actual != pin:
|
||||
raise ValueError('Registered policy hash differs from its manifest')
|
||||
return dict(entry, path=model_path, manifest_path=manifest_path, metadata=manifest)
|
||||
|
||||
def inventory(self):
|
||||
result = []
|
||||
for entry in self.entries:
|
||||
try:
|
||||
selected = self.select(entry["id"])
|
||||
result.append(dict(id=entry["id"], label=entry["label"],
|
||||
compatible=True, sha256=selected["metadata"]["sha256"],
|
||||
preview_only=bool(selected['metadata'].get('preview_only'))))
|
||||
except (OSError, ValueError, KeyError) as exc:
|
||||
result.append(dict(id=entry.get("id"), label=entry.get("label"),
|
||||
compatible=False, reason=str(exc)))
|
||||
return result
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Select a decoder only after the registry has verified its pinned contract."""
|
||||
from model.registry import POP_CONTRACT as CONTRACT
|
||||
|
||||
|
||||
def create_brain(selected, use_gpu=True):
|
||||
if selected['metadata']['output_layout'] == CONTRACT:
|
||||
from model.pop_v2 import PopV2Brain
|
||||
runner = PopV2Brain
|
||||
else:
|
||||
from model.openpilot_brain import OpenPilotBrain
|
||||
runner = OpenPilotBrain
|
||||
return runner(str(selected['path']), use_gpu=use_gpu,
|
||||
manifest_path=selected['manifest_path'])
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"sha256": "77a31e5a3a70c39a3fcb07e939a668baf80b1eb778fe792fbe256de983fab5cd",
|
||||
"output_layout": "historical supercombo 6409",
|
||||
"parser_reference": "https://github.com/commaai/openpilot/blob/v0.8.5/selfdrive/modeld/models/driving.cc",
|
||||
"provenance": "Existing local PyTorch-exported model; original training/export version unrecorded",
|
||||
"validated": "Tensor contract, finite inference, historical decoder layout; road performance requires replay and driving validation"
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
{
|
||||
"repository": "commaai/openpilot",
|
||||
"revision": "62bf6fb072880905a4c490f0f4f4a6b3c23346ec",
|
||||
"catalog_commit": "9850fb07544b3c1f8c21b793c454e606dbb7fdca",
|
||||
"catalog_ref": "PMV2",
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "driving_vision.onnx",
|
||||
"url": "https://media.githubusercontent.com/media/commaai/openpilot/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/modeld/models/driving_vision.onnx",
|
||||
"sha256": "940e9006a25f27f0b6e85da798e6a8fd1f6dd492dd7d0b9ff1a9436460f46129",
|
||||
"bytes": 46887794,
|
||||
"seconds": 1.35
|
||||
},
|
||||
{
|
||||
"name": "driving_policy.onnx",
|
||||
"url": "https://media.githubusercontent.com/media/commaai/openpilot/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/modeld/models/driving_policy.onnx",
|
||||
"sha256": "853c6634746ff439a848349d00e4d5581cd941f13f7c1862c31b72a31cc24858",
|
||||
"bytes": 14061595,
|
||||
"seconds": 0.86
|
||||
}
|
||||
],
|
||||
"pickle_executed": false,
|
||||
"runtime_changed": false,
|
||||
"source_files": [
|
||||
{
|
||||
"file": "source/catalog-identity.json",
|
||||
"sha256": "1d5f0ab6ef037096f8ddcb976cfed0b81c122415e3b6e095797631beefa15cef",
|
||||
"bytes": 173
|
||||
},
|
||||
{
|
||||
"file": "source/comma-common_transformations_camera.py",
|
||||
"sha256": "3ac87fd236aa9c9e284059c47c9eb96a7c6e0be5106f514a95e6ec06e1060fb5",
|
||||
"bytes": 6141
|
||||
},
|
||||
{
|
||||
"file": "source/comma-common_transformations_model.py",
|
||||
"sha256": "c87aad27074362fe9fe361a71da92c1fc90daf63bcfd4d8c47d65d3a936ec15e",
|
||||
"bytes": 2766
|
||||
},
|
||||
{
|
||||
"file": "source/comma-selfdrive_modeld_compile_warp.py",
|
||||
"sha256": "574aa090de6fa272f95b00e039b1467d60c6d9445ee8d774e8529369648fcf0f",
|
||||
"bytes": 8372
|
||||
},
|
||||
{
|
||||
"file": "source/comma-selfdrive_modeld_constants.py",
|
||||
"sha256": "e1e3a01ea31dd57dbd9ffd588ff1f2ab22e6088a558c65ad68bf20678552c00c",
|
||||
"bytes": 2145
|
||||
},
|
||||
{
|
||||
"file": "source/comma-selfdrive_modeld_fill_model_msg.py",
|
||||
"sha256": "d99289ee16ddbcc286abc7184f1de55ad4378d860092ec896d1cdc4cf4f12799",
|
||||
"bytes": 9415
|
||||
},
|
||||
{
|
||||
"file": "source/comma-selfdrive_modeld_get_model_metadata.py",
|
||||
"sha256": "045d9fd4b10ff989adc5837b9a5dfad2b961b890f46f0bbe995335dae5e68789",
|
||||
"bytes": 1855
|
||||
},
|
||||
{
|
||||
"file": "source/comma-selfdrive_modeld_modeld.py",
|
||||
"sha256": "571496f6e8b8364d90d0e2dddcb2a6f375ecbb434927e11078f40084e56f3b66",
|
||||
"bytes": 19621
|
||||
},
|
||||
{
|
||||
"file": "source/comma-selfdrive_modeld_models_driving_policy.onnx",
|
||||
"sha256": "37629fbdf9fd80ad6d00bc02d6f85024820cb941727d9810cca3c75cf47e3fb3",
|
||||
"bytes": 133
|
||||
},
|
||||
{
|
||||
"file": "source/comma-selfdrive_modeld_models_driving_vision.onnx",
|
||||
"sha256": "806ec3815cbc3c58fc93c0c5c8d09f0a093a6d8a61d6e34a461fb6759040f796",
|
||||
"bytes": 133
|
||||
},
|
||||
{
|
||||
"file": "source/comma-selfdrive_modeld_models_README.md",
|
||||
"sha256": "f2613800954f09805728228efd51cd16025c8bd18e569cd1fba42b7b75691a8b",
|
||||
"bytes": 3417
|
||||
},
|
||||
{
|
||||
"file": "source/comma-selfdrive_modeld_parse_model_outputs.py",
|
||||
"sha256": "82d5eb5391f2c02c187adb3ad9ae6ad9d97fd0ae681d54e808a438f415802ed4",
|
||||
"bytes": 5592
|
||||
},
|
||||
{
|
||||
"file": "source/comma-selfdrive_modeld_SConscript",
|
||||
"sha256": "a24250835b2d34bfcdad95fffe0dc96809c95850178c461e9b1943826d683e1b",
|
||||
"bytes": 3429
|
||||
},
|
||||
{
|
||||
"file": "source/driving_models_chestnut_v25.json",
|
||||
"sha256": "152db3f375fa02cef5211a06e14a83c52461b0fe32a3f04a8570d52829c69b8c",
|
||||
"bytes": 100628
|
||||
},
|
||||
{
|
||||
"file": "source/driving_models_v22.json",
|
||||
"sha256": "a4b5bd581bd252218d7dc6c9c146d2b13bfecc677a10a153ef55060d96a74e1b",
|
||||
"bytes": 119213
|
||||
},
|
||||
{
|
||||
"file": "source/driving_policy.onnx.output_slices.pickle-dis.txt",
|
||||
"sha256": "36b7df7c5062ba16e0daf1a75fa06dc27b1ce3fa06d348063db336b12c0543f1",
|
||||
"bytes": 1340
|
||||
},
|
||||
{
|
||||
"file": "source/driving_vision.onnx.output_slices.pickle-dis.txt",
|
||||
"sha256": "0f24e89ab286c42d6c7ae1ebc64dab0ec52013e2a6dc27d5d75ae8dc0502ff11",
|
||||
"bytes": 4219
|
||||
},
|
||||
{
|
||||
"file": "source/sunnypilot-models-fetcher.py",
|
||||
"sha256": "8f600cc803250ca34d8a86904af5812e0d17a6e600c72d96a14c69fd2f2fce29",
|
||||
"bytes": 11102
|
||||
},
|
||||
{
|
||||
"file": "source/sunnypilot-models-helpers.py",
|
||||
"sha256": "369e1e0e81d617c57e61116041728f50ce4fe66458c725558fa0093cfb34c3bd",
|
||||
"bytes": 8531
|
||||
},
|
||||
{
|
||||
"file": "source/sunnypilot-models-manager.py",
|
||||
"sha256": "39cbfbeefe0f0b7b42bc8ca0ea3238e52028f7503ec416653f312c99e74eb1cc",
|
||||
"bytes": 16737
|
||||
},
|
||||
{
|
||||
"file": "source/sunnypilot-models-model_name.py",
|
||||
"sha256": "89059f73cc2272141fcf0b5ac0d3b7c9d87565760c4d52db6af779e0ae86d442",
|
||||
"bytes": 193
|
||||
},
|
||||
{
|
||||
"file": "source/sunnypilot-models-README.md",
|
||||
"sha256": "5b0cf47f9893488977c2169878117b9bfc9ecd096d31a7f2f262ec3b45ab626b",
|
||||
"bytes": 3409
|
||||
},
|
||||
{
|
||||
"file": "source/sunnypilot-models-runners_constants.py",
|
||||
"sha256": "e737aeb63a3b125ac5b62d5e21fe1cf3e635553802caf1d8bec6add9710b6942",
|
||||
"bytes": 411
|
||||
},
|
||||
{
|
||||
"file": "source/sunnypilot-models-split_model_constants.py",
|
||||
"sha256": "3d374354b182d388e413556f3f06b58aabf32700e14bc6e5744980fa48d7cb07",
|
||||
"bytes": 2320
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "Pop Model v2 (March 24, 2026)",
|
||||
"model_id": "pop-v2",
|
||||
"output_layout": "pop-v2-split-1576-1000",
|
||||
"model_file": "driving_vision.onnx",
|
||||
"sha256": "940e9006a25f27f0b6e85da798e6a8fd1f6dd492dd7d0b9ff1a9436460f46129",
|
||||
"policy_file": "driving_policy.onnx",
|
||||
"policy_sha256": "853c6634746ff439a848349d00e4d5581cd941f13f7c1862c31b72a31cc24858",
|
||||
"source_repository": "commaai/openpilot",
|
||||
"source_revision": "62bf6fb072880905a4c490f0f4f4a6b3c23346ec",
|
||||
"catalog_repository": "sunnypilot/sunnypilot-models",
|
||||
"catalog_commit": "9850fb07544b3c1f8c21b793c454e606dbb7fdca",
|
||||
"catalog_short_name": "PMV2",
|
||||
"experimental": true,
|
||||
"preview_only": true,
|
||||
"camera_validated": false,
|
||||
"usable_for_control": false,
|
||||
"expected_run_hz": 20,
|
||||
"context_hz": 5,
|
||||
"image_pair_separation_s": 0.2,
|
||||
"feature_context_samples": 25,
|
||||
"feature_context_span_s": 4.8,
|
||||
"plan_confidence": "unassessed: unary mean/logstd plan has no selection probability",
|
||||
"camera_approximation": "pop-wide-sbig supplies an ATS wide SBIG render and derived narrow MED crop; other captures duplicate narrow input. Physical camera calibration remains unvalidated; recording rows identify the actual mode.",
|
||||
"source_urls": {
|
||||
"catalog": "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/9850fb07544b3c1f8c21b793c454e606dbb7fdca/docs/driving_models_v22.json",
|
||||
"vision": "https://media.githubusercontent.com/media/commaai/openpilot/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/modeld/models/driving_vision.onnx",
|
||||
"policy": "https://media.githubusercontent.com/media/commaai/openpilot/62bf6fb072880905a4c490f0f4f4a6b3c23346ec/selfdrive/modeld/models/driving_policy.onnx"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"vision": {
|
||||
"meta": [
|
||||
0,
|
||||
55
|
||||
],
|
||||
"desire_pred": [
|
||||
55,
|
||||
87
|
||||
],
|
||||
"pose": [
|
||||
87,
|
||||
99
|
||||
],
|
||||
"wide_from_device_euler": [
|
||||
99,
|
||||
105
|
||||
],
|
||||
"road_transform": [
|
||||
105,
|
||||
117
|
||||
],
|
||||
"lane_lines": [
|
||||
117,
|
||||
645
|
||||
],
|
||||
"lane_lines_prob": [
|
||||
645,
|
||||
653
|
||||
],
|
||||
"road_edges": [
|
||||
653,
|
||||
917
|
||||
],
|
||||
"lead": [
|
||||
917,
|
||||
1061
|
||||
],
|
||||
"lead_prob": [
|
||||
1061,
|
||||
1064
|
||||
],
|
||||
"hidden_state": [
|
||||
1064,
|
||||
1576
|
||||
]
|
||||
},
|
||||
"policy": {
|
||||
"plan": [
|
||||
0,
|
||||
990
|
||||
],
|
||||
"desire_state": [
|
||||
990,
|
||||
998
|
||||
]
|
||||
},
|
||||
"lane_probability_logit_indices": [
|
||||
1,
|
||||
3,
|
||||
5,
|
||||
7
|
||||
],
|
||||
"plan_mean_shape": [
|
||||
33,
|
||||
15
|
||||
],
|
||||
"plan_std_encoding": "second495 values exp(logstd), exponent clipped11 upstream",
|
||||
"extraction": "manually transcribed from pickletools opcode disassembly; no pickle execution"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"repository": "sunnypilot/sunnypilot-models",
|
||||
"commit": "9850fb07544b3c1f8c21b793c454e606dbb7fdca",
|
||||
"source_commit": "a5f44653d7f43ad57fef2f546f3916ec4cbf3c56"
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import itertools
|
||||
import numpy as np
|
||||
from dataclasses import dataclass
|
||||
|
||||
import openpilot.common.transformations.orientation as orient
|
||||
|
||||
## -- hardcoded hardware params --
|
||||
@dataclass(frozen=True)
|
||||
class CameraConfig:
|
||||
width: int
|
||||
height: int
|
||||
focal_length: float
|
||||
|
||||
@property
|
||||
def size(self):
|
||||
return (self.width, self.height)
|
||||
|
||||
@property
|
||||
def intrinsics(self):
|
||||
# aka 'K' aka camera_frame_from_view_frame
|
||||
return np.array([
|
||||
[self.focal_length, 0.0, float(self.width)/2],
|
||||
[0.0, self.focal_length, float(self.height)/2],
|
||||
[0.0, 0.0, 1.0]
|
||||
])
|
||||
|
||||
@property
|
||||
def intrinsics_inv(self):
|
||||
# aka 'K_inv' aka view_frame_from_camera_frame
|
||||
return np.linalg.inv(self.intrinsics)
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _NoneCameraConfig(CameraConfig):
|
||||
width: int = 0
|
||||
height: int = 0
|
||||
focal_length: float = 0
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeviceCameraConfig:
|
||||
fcam: CameraConfig
|
||||
dcam: CameraConfig
|
||||
ecam: CameraConfig
|
||||
|
||||
def all_cams(self):
|
||||
for cam in ['fcam', 'dcam', 'ecam']:
|
||||
if not isinstance(getattr(self, cam), _NoneCameraConfig):
|
||||
yield cam, getattr(self, cam)
|
||||
|
||||
_ar_ox_fisheye = CameraConfig(1928, 1208, 567.0) # focal length probably wrong? magnification is not consistent across frame
|
||||
_os_fisheye = CameraConfig(2688 // 2, 1520 // 2, 567.0 / 4 * 3)
|
||||
_ar_ox_config = DeviceCameraConfig(CameraConfig(1928, 1208, 2648.0), _ar_ox_fisheye, _ar_ox_fisheye)
|
||||
_os_config = DeviceCameraConfig(CameraConfig(2688 // 2, 1520 // 2, 1522.0 * 3 / 4), _os_fisheye, _os_fisheye)
|
||||
_neo_config = DeviceCameraConfig(CameraConfig(1164, 874, 910.0), CameraConfig(816, 612, 650.0), _NoneCameraConfig())
|
||||
|
||||
DEVICE_CAMERAS = {
|
||||
# A "device camera" is defined by a device type and sensor
|
||||
|
||||
# sensor type was never set on eon/neo/two
|
||||
("neo", "unknown"): _neo_config,
|
||||
# unknown here is AR0231, field was added with OX03C10 support
|
||||
("tici", "unknown"): _ar_ox_config,
|
||||
|
||||
# before deviceState.deviceType was set, assume tici AR config
|
||||
("unknown", "ar0231"): _ar_ox_config,
|
||||
("unknown", "ox03c10"): _ar_ox_config,
|
||||
|
||||
# simulator (emulates a tici)
|
||||
("pc", "unknown"): _ar_ox_config,
|
||||
}
|
||||
prods = itertools.product(('tici', 'tizi', 'mici'), (('ar0231', _ar_ox_config), ('ox03c10', _ar_ox_config), ('os04c10', _os_config)))
|
||||
DEVICE_CAMERAS.update({(d, c[0]): c[1] for d, c in prods})
|
||||
|
||||
# device/mesh : x->forward, y-> right, z->down
|
||||
# view : x->right, y->down, z->forward
|
||||
device_frame_from_view_frame = np.array([
|
||||
[ 0., 0., 1.],
|
||||
[ 1., 0., 0.],
|
||||
[ 0., 1., 0.]
|
||||
])
|
||||
view_frame_from_device_frame = device_frame_from_view_frame.T
|
||||
|
||||
|
||||
# aka 'extrinsic_matrix'
|
||||
# road : x->forward, y -> left, z->up
|
||||
def get_view_frame_from_road_frame(roll, pitch, yaw, height):
|
||||
device_from_road = orient.rot_from_euler([roll, pitch, yaw]).dot(np.diag([1, -1, -1]))
|
||||
view_from_road = view_frame_from_device_frame.dot(device_from_road)
|
||||
return np.hstack((view_from_road, [[0], [height], [0]]))
|
||||
|
||||
|
||||
|
||||
# aka 'extrinsic_matrix'
|
||||
def get_view_frame_from_calib_frame(roll, pitch, yaw, height):
|
||||
device_from_calib= orient.rot_from_euler([roll, pitch, yaw])
|
||||
view_from_calib = view_frame_from_device_frame.dot(device_from_calib)
|
||||
return np.hstack((view_from_calib, [[0], [height], [0]]))
|
||||
|
||||
|
||||
def vp_from_ke(m):
|
||||
"""
|
||||
Computes the vanishing point from the product of the intrinsic and extrinsic
|
||||
matrices C = KE.
|
||||
|
||||
The vanishing point is defined as lim x->infinity C (x, 0, 0, 1).T
|
||||
"""
|
||||
return (m[0, 0]/m[2, 0], m[1, 0]/m[2, 0])
|
||||
|
||||
|
||||
def roll_from_ke(m):
|
||||
# note: different from calibration.h/RollAnglefromKE: i think that one's just wrong
|
||||
return np.arctan2(-(m[1, 0] - m[1, 1] * m[2, 0] / m[2, 1]),
|
||||
-(m[0, 0] - m[0, 1] * m[2, 0] / m[2, 1]))
|
||||
|
||||
|
||||
def normalize(img_pts, intrinsics):
|
||||
# normalizes image coordinates
|
||||
# accepts single pt or array of pts
|
||||
intrinsics_inv = np.linalg.inv(intrinsics)
|
||||
img_pts = np.array(img_pts)
|
||||
input_shape = img_pts.shape
|
||||
img_pts = np.atleast_2d(img_pts)
|
||||
img_pts = np.hstack((img_pts, np.ones((img_pts.shape[0], 1))))
|
||||
img_pts_normalized = img_pts.dot(intrinsics_inv.T)
|
||||
img_pts_normalized[(img_pts < 0).any(axis=1)] = np.nan
|
||||
return img_pts_normalized[:, :2].reshape(input_shape)
|
||||
|
||||
|
||||
def denormalize(img_pts, intrinsics, width=np.inf, height=np.inf):
|
||||
# denormalizes image coordinates
|
||||
# accepts single pt or array of pts
|
||||
img_pts = np.array(img_pts)
|
||||
input_shape = img_pts.shape
|
||||
img_pts = np.atleast_2d(img_pts)
|
||||
img_pts = np.hstack((img_pts, np.ones((img_pts.shape[0], 1), dtype=img_pts.dtype)))
|
||||
img_pts_denormalized = img_pts.dot(intrinsics.T)
|
||||
if np.isfinite(width):
|
||||
img_pts_denormalized[img_pts_denormalized[:, 0] > width] = np.nan
|
||||
img_pts_denormalized[img_pts_denormalized[:, 0] < 0] = np.nan
|
||||
if np.isfinite(height):
|
||||
img_pts_denormalized[img_pts_denormalized[:, 1] > height] = np.nan
|
||||
img_pts_denormalized[img_pts_denormalized[:, 1] < 0] = np.nan
|
||||
return img_pts_denormalized[:, :2].reshape(input_shape)
|
||||
|
||||
|
||||
def get_calib_from_vp(vp, intrinsics):
|
||||
vp_norm = normalize(vp, intrinsics)
|
||||
yaw_calib = np.arctan(vp_norm[0])
|
||||
pitch_calib = -np.arctan(vp_norm[1]*np.cos(yaw_calib))
|
||||
roll_calib = 0
|
||||
return roll_calib, pitch_calib, yaw_calib
|
||||
|
||||
|
||||
def device_from_ecef(pos_ecef, orientation_ecef, pt_ecef):
|
||||
# device from ecef frame
|
||||
# device frame is x -> forward, y-> right, z -> down
|
||||
# accepts single pt or array of pts
|
||||
input_shape = pt_ecef.shape
|
||||
pt_ecef = np.atleast_2d(pt_ecef)
|
||||
ecef_from_device_rot = orient.rotations_from_quats(orientation_ecef)
|
||||
device_from_ecef_rot = ecef_from_device_rot.T
|
||||
pt_ecef_rel = pt_ecef - pos_ecef
|
||||
pt_device = np.einsum('jk,ik->ij', device_from_ecef_rot, pt_ecef_rel)
|
||||
return pt_device.reshape(input_shape)
|
||||
|
||||
|
||||
def img_from_device(pt_device):
|
||||
# img coordinates from pts in device frame
|
||||
# first transforms to view frame, then to img coords
|
||||
# accepts single pt or array of pts
|
||||
input_shape = pt_device.shape
|
||||
pt_device = np.atleast_2d(pt_device)
|
||||
pt_view = np.einsum('jk,ik->ij', view_frame_from_device_frame, pt_device)
|
||||
|
||||
# This function should never return negative depths
|
||||
pt_view[pt_view[:, 2] < 0] = np.nan
|
||||
|
||||
pt_img = pt_view/pt_view[:, 2:3]
|
||||
return pt_img.reshape(input_shape)[:, :2]
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import numpy as np
|
||||
|
||||
from openpilot.common.transformations.orientation import rot_from_euler
|
||||
from openpilot.common.transformations.camera import get_view_frame_from_calib_frame, view_frame_from_device_frame, _ar_ox_fisheye
|
||||
|
||||
# segnet
|
||||
SEGNET_SIZE = (512, 384)
|
||||
|
||||
# MED model
|
||||
MEDMODEL_INPUT_SIZE = (512, 256)
|
||||
MEDMODEL_YUV_SIZE = (MEDMODEL_INPUT_SIZE[0], MEDMODEL_INPUT_SIZE[1] * 3 // 2)
|
||||
MEDMODEL_CY = 47.6
|
||||
|
||||
medmodel_fl = 910.0
|
||||
medmodel_intrinsics = np.array([
|
||||
[medmodel_fl, 0.0, 0.5 * MEDMODEL_INPUT_SIZE[0]],
|
||||
[0.0, medmodel_fl, MEDMODEL_CY],
|
||||
[0.0, 0.0, 1.0]])
|
||||
|
||||
|
||||
# BIG model
|
||||
BIGMODEL_INPUT_SIZE = (1024, 512)
|
||||
BIGMODEL_YUV_SIZE = (BIGMODEL_INPUT_SIZE[0], BIGMODEL_INPUT_SIZE[1] * 3 // 2)
|
||||
|
||||
bigmodel_fl = 910.0
|
||||
bigmodel_intrinsics = np.array([
|
||||
[bigmodel_fl, 0.0, 0.5 * BIGMODEL_INPUT_SIZE[0]],
|
||||
[0.0, bigmodel_fl, 256 + MEDMODEL_CY],
|
||||
[0.0, 0.0, 1.0]])
|
||||
|
||||
|
||||
# SBIG model (big model with the size of small model)
|
||||
SBIGMODEL_INPUT_SIZE = (512, 256)
|
||||
SBIGMODEL_YUV_SIZE = (SBIGMODEL_INPUT_SIZE[0], SBIGMODEL_INPUT_SIZE[1] * 3 // 2)
|
||||
|
||||
sbigmodel_fl = 455.0
|
||||
sbigmodel_intrinsics = np.array([
|
||||
[sbigmodel_fl, 0.0, 0.5 * SBIGMODEL_INPUT_SIZE[0]],
|
||||
[0.0, sbigmodel_fl, 0.5 * (256 + MEDMODEL_CY)],
|
||||
[0.0, 0.0, 1.0]])
|
||||
|
||||
DM_INPUT_SIZE = (1440, 960)
|
||||
dmonitoringmodel_fl = _ar_ox_fisheye.focal_length
|
||||
dmonitoringmodel_intrinsics = np.array([
|
||||
[dmonitoringmodel_fl, 0.0, DM_INPUT_SIZE[0]/2],
|
||||
[0.0, dmonitoringmodel_fl, DM_INPUT_SIZE[1]/2 - (_ar_ox_fisheye.height - DM_INPUT_SIZE[1])/2],
|
||||
[0.0, 0.0, 1.0]])
|
||||
|
||||
bigmodel_frame_from_calib_frame = np.dot(bigmodel_intrinsics,
|
||||
get_view_frame_from_calib_frame(0, 0, 0, 0))
|
||||
|
||||
|
||||
sbigmodel_frame_from_calib_frame = np.dot(sbigmodel_intrinsics,
|
||||
get_view_frame_from_calib_frame(0, 0, 0, 0))
|
||||
|
||||
medmodel_frame_from_calib_frame = np.dot(medmodel_intrinsics,
|
||||
get_view_frame_from_calib_frame(0, 0, 0, 0))
|
||||
|
||||
medmodel_frame_from_bigmodel_frame = np.dot(medmodel_intrinsics, np.linalg.inv(bigmodel_intrinsics))
|
||||
|
||||
calib_from_medmodel = np.linalg.inv(medmodel_frame_from_calib_frame[:, :3])
|
||||
calib_from_sbigmodel = np.linalg.inv(sbigmodel_frame_from_calib_frame[:, :3])
|
||||
|
||||
# This function is verified to give similar results to xx.uncommon.utils.transform_img
|
||||
def get_warp_matrix(device_from_calib_euler: np.ndarray, intrinsics: np.ndarray, bigmodel_frame: bool = False) -> np.ndarray:
|
||||
calib_from_model = calib_from_sbigmodel if bigmodel_frame else calib_from_medmodel
|
||||
device_from_calib = rot_from_euler(device_from_calib_euler)
|
||||
camera_from_calib = intrinsics @ view_frame_from_device_frame @ device_from_calib
|
||||
warp_matrix: np.ndarray = camera_from_calib @ calib_from_model
|
||||
return warp_matrix
|
||||
@@ -0,0 +1,77 @@
|
||||
import os
|
||||
import glob
|
||||
from openpilot.common.file_chunker import chunk_file, get_chunk_paths
|
||||
|
||||
Import('env', 'arch')
|
||||
chunker_file = File("#common/file_chunker.py")
|
||||
lenv = env.Clone()
|
||||
|
||||
tinygrad_root = env.Dir("#").abspath
|
||||
tinygrad_files = ["#"+x for x in glob.glob(env.Dir("#tinygrad_repo").relpath + "/**", recursive=True, root_dir=tinygrad_root)
|
||||
if 'pycache' not in x and os.path.isfile(os.path.join(tinygrad_root, x))]
|
||||
|
||||
def estimate_pickle_max_size(onnx_size):
|
||||
return 1.2 * onnx_size + 10 * 1024 * 1024 # 20% + 10MB is plenty
|
||||
|
||||
# compile warp
|
||||
# THREADS=0 is need to prevent bug: https://github.com/tinygrad/tinygrad/issues/14689
|
||||
tg_flags = {
|
||||
'larch64': 'DEV=QCOM FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0',
|
||||
'Darwin': f'DEV=CPU THREADS=0 HOME={os.path.expanduser("~")}', # tinygrad calls brew which needs a $HOME in the env
|
||||
}.get(arch, 'DEV=CPU CPU_LLVM=1 THREADS=0')
|
||||
|
||||
# Get model metadata
|
||||
for model_name in ['driving_vision', 'driving_policy', 'dmonitoring_model']:
|
||||
fn = File(f"models/{model_name}").abspath
|
||||
script_files = [File(Dir("#selfdrive/modeld").File("get_model_metadata.py").abspath)]
|
||||
cmd = f'{tg_flags} python3 {Dir("#selfdrive/modeld").abspath}/get_model_metadata.py {fn}.onnx'
|
||||
lenv.Command(fn + "_metadata.pkl", [fn + ".onnx"] + tinygrad_files + script_files, cmd)
|
||||
|
||||
image_flag = {
|
||||
'larch64': 'IMAGE=2',
|
||||
}.get(arch, 'IMAGE=0')
|
||||
script_files = [File(Dir("#selfdrive/modeld").File("compile_warp.py").abspath)]
|
||||
compile_warp_cmd = f'{tg_flags} python3 {Dir("#selfdrive/modeld").abspath}/compile_warp.py '
|
||||
from openpilot.common.transformations.camera import _ar_ox_fisheye, _os_fisheye
|
||||
warp_targets = []
|
||||
for cam in [_ar_ox_fisheye, _os_fisheye]:
|
||||
w, h = cam.width, cam.height
|
||||
warp_targets += [File(f"models/warp_{w}x{h}_tinygrad.pkl").abspath, File(f"models/dm_warp_{w}x{h}_tinygrad.pkl").abspath]
|
||||
lenv.Command(warp_targets, tinygrad_files + script_files, compile_warp_cmd)
|
||||
|
||||
def tg_compile(flags, model_name):
|
||||
pythonpath_string = 'PYTHONPATH="${PYTHONPATH}:' + env.Dir("#tinygrad_repo").abspath + '"'
|
||||
fn = File(f"models/{model_name}").abspath
|
||||
pkl = fn + "_tinygrad.pkl"
|
||||
onnx_path = fn + ".onnx"
|
||||
chunk_targets = get_chunk_paths(pkl, estimate_pickle_max_size(os.path.getsize(onnx_path)))
|
||||
compile_node = lenv.Command(
|
||||
pkl,
|
||||
[onnx_path] + tinygrad_files + [chunker_file],
|
||||
f'{pythonpath_string} {flags} {image_flag} python3 {Dir("#tinygrad_repo").abspath}/examples/openpilot/compile3.py {fn}.onnx {pkl}',
|
||||
)
|
||||
def do_chunk(target, source, env):
|
||||
chunk_file(pkl, chunk_targets)
|
||||
return lenv.Command(
|
||||
chunk_targets,
|
||||
compile_node,
|
||||
do_chunk,
|
||||
)
|
||||
|
||||
# Compile small models
|
||||
for model_name in ['driving_vision', 'driving_policy', 'dmonitoring_model']:
|
||||
tg_compile(tg_flags, model_name)
|
||||
|
||||
# Compile BIG model if USB GPU is available
|
||||
if "USBGPU" in os.environ:
|
||||
import subprocess
|
||||
# because tg doesn't support multi-process
|
||||
devs = subprocess.check_output('python3 -c "from tinygrad import Device; print(list(Device.get_available_devices()))"', shell=True, cwd=env.Dir('#').abspath)
|
||||
if b"AMD" in devs:
|
||||
print("USB GPU detected... building")
|
||||
flags = "DEV=AMD AMD_IFACE=USB AMD_LLVM=1 NOLOCALS=0 IMAGE=0"
|
||||
bp = tg_compile(flags, "big_driving_policy")
|
||||
bv = tg_compile(flags, "big_driving_vision")
|
||||
lenv.SideEffect('lock', [bp, bv]) # tg doesn't support multi-process so build serially
|
||||
else:
|
||||
print("USB GPU not detected... skipping")
|
||||
@@ -0,0 +1,209 @@
|
||||
#!/usr/bin/env python3
|
||||
import time
|
||||
import pickle
|
||||
import numpy as np
|
||||
from pathlib import Path
|
||||
from tinygrad.tensor import Tensor
|
||||
from tinygrad.helpers import Context
|
||||
from tinygrad.device import Device
|
||||
from tinygrad.engine.jit import TinyJit
|
||||
|
||||
from openpilot.system.camerad.cameras.nv12_info import get_nv12_info
|
||||
from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE, DM_INPUT_SIZE
|
||||
from openpilot.common.transformations.camera import _ar_ox_fisheye, _os_fisheye
|
||||
|
||||
MODELS_DIR = Path(__file__).parent / 'models'
|
||||
|
||||
CAMERA_CONFIGS = [
|
||||
(_ar_ox_fisheye.width, _ar_ox_fisheye.height), # tici: 1928x1208
|
||||
(_os_fisheye.width, _os_fisheye.height), # mici: 1344x760
|
||||
]
|
||||
|
||||
UV_SCALE_MATRIX = np.array([[0.5, 0, 0], [0, 0.5, 0], [0, 0, 1]], dtype=np.float32)
|
||||
UV_SCALE_MATRIX_INV = np.linalg.inv(UV_SCALE_MATRIX)
|
||||
|
||||
IMG_BUFFER_SHAPE = (30, MEDMODEL_INPUT_SIZE[1] // 2, MEDMODEL_INPUT_SIZE[0] // 2)
|
||||
|
||||
|
||||
def warp_pkl_path(w, h):
|
||||
return MODELS_DIR / f'warp_{w}x{h}_tinygrad.pkl'
|
||||
|
||||
|
||||
def dm_warp_pkl_path(w, h):
|
||||
return MODELS_DIR / f'dm_warp_{w}x{h}_tinygrad.pkl'
|
||||
|
||||
|
||||
def warp_perspective_tinygrad(src_flat, M_inv, dst_shape, src_shape, stride_pad):
|
||||
w_dst, h_dst = dst_shape
|
||||
h_src, w_src = src_shape
|
||||
|
||||
x = Tensor.arange(w_dst).reshape(1, w_dst).expand(h_dst, w_dst).reshape(-1)
|
||||
y = Tensor.arange(h_dst).reshape(h_dst, 1).expand(h_dst, w_dst).reshape(-1)
|
||||
|
||||
# inline 3x3 matmul as elementwise to avoid reduce op (enables fusion with gather)
|
||||
src_x = M_inv[0, 0] * x + M_inv[0, 1] * y + M_inv[0, 2]
|
||||
src_y = M_inv[1, 0] * x + M_inv[1, 1] * y + M_inv[1, 2]
|
||||
src_w = M_inv[2, 0] * x + M_inv[2, 1] * y + M_inv[2, 2]
|
||||
|
||||
src_x = src_x / src_w
|
||||
src_y = src_y / src_w
|
||||
|
||||
x_nn_clipped = Tensor.round(src_x).clip(0, w_src - 1).cast('int')
|
||||
y_nn_clipped = Tensor.round(src_y).clip(0, h_src - 1).cast('int')
|
||||
idx = y_nn_clipped * (w_src + stride_pad) + x_nn_clipped
|
||||
|
||||
return src_flat[idx]
|
||||
|
||||
|
||||
def frames_to_tensor(frames, model_w, model_h):
|
||||
H = (frames.shape[0] * 2) // 3
|
||||
W = frames.shape[1]
|
||||
in_img1 = Tensor.cat(frames[0:H:2, 0::2],
|
||||
frames[1:H:2, 0::2],
|
||||
frames[0:H:2, 1::2],
|
||||
frames[1:H:2, 1::2],
|
||||
frames[H:H+H//4].reshape((H//2, W//2)),
|
||||
frames[H+H//4:H+H//2].reshape((H//2, W//2)), dim=0).reshape((6, H//2, W//2))
|
||||
return in_img1
|
||||
|
||||
|
||||
def make_frame_prepare(cam_w, cam_h, model_w, model_h):
|
||||
stride, y_height, uv_height, _ = get_nv12_info(cam_w, cam_h)
|
||||
uv_offset = stride * y_height
|
||||
stride_pad = stride - cam_w
|
||||
|
||||
def frame_prepare_tinygrad(input_frame, M_inv):
|
||||
# UV_SCALE @ M_inv @ UV_SCALE_INV simplifies to elementwise scaling
|
||||
M_inv_uv = M_inv * Tensor([[1.0, 1.0, 0.5], [1.0, 1.0, 0.5], [2.0, 2.0, 1.0]])
|
||||
# deinterleave NV12 UV plane (UVUV... -> separate U, V)
|
||||
uv = input_frame[uv_offset:uv_offset + uv_height * stride].reshape(uv_height, stride)
|
||||
with Context(SPLIT_REDUCEOP=0):
|
||||
y = warp_perspective_tinygrad(input_frame[:cam_h*stride],
|
||||
M_inv, (model_w, model_h),
|
||||
(cam_h, cam_w), stride_pad).realize()
|
||||
u = warp_perspective_tinygrad(uv[:cam_h//2, :cam_w:2].flatten(),
|
||||
M_inv_uv, (model_w//2, model_h//2),
|
||||
(cam_h//2, cam_w//2), 0).realize()
|
||||
v = warp_perspective_tinygrad(uv[:cam_h//2, 1:cam_w:2].flatten(),
|
||||
M_inv_uv, (model_w//2, model_h//2),
|
||||
(cam_h//2, cam_w//2), 0).realize()
|
||||
yuv = y.cat(u).cat(v).reshape((model_h * 3 // 2, model_w))
|
||||
tensor = frames_to_tensor(yuv, model_w, model_h)
|
||||
return tensor
|
||||
return frame_prepare_tinygrad
|
||||
|
||||
|
||||
def make_update_img_input(frame_prepare, model_w, model_h):
|
||||
def update_img_input_tinygrad(tensor, frame, M_inv):
|
||||
M_inv = M_inv.to(Device.DEFAULT)
|
||||
new_img = frame_prepare(frame, M_inv)
|
||||
full_buffer = tensor[6:].cat(new_img, dim=0).contiguous()
|
||||
return full_buffer, Tensor.cat(full_buffer[:6], full_buffer[-6:], dim=0).contiguous().reshape(1, 12, model_h//2, model_w//2)
|
||||
return update_img_input_tinygrad
|
||||
|
||||
|
||||
def make_update_both_imgs(frame_prepare, model_w, model_h):
|
||||
update_img = make_update_img_input(frame_prepare, model_w, model_h)
|
||||
|
||||
def update_both_imgs_tinygrad(calib_img_buffer, new_img, M_inv,
|
||||
calib_big_img_buffer, new_big_img, M_inv_big):
|
||||
calib_img_buffer, calib_img_pair = update_img(calib_img_buffer, new_img, M_inv)
|
||||
calib_big_img_buffer, calib_big_img_pair = update_img(calib_big_img_buffer, new_big_img, M_inv_big)
|
||||
return calib_img_buffer, calib_img_pair, calib_big_img_buffer, calib_big_img_pair
|
||||
return update_both_imgs_tinygrad
|
||||
|
||||
|
||||
def make_warp_dm(cam_w, cam_h, dm_w, dm_h):
|
||||
stride, y_height, _, _ = get_nv12_info(cam_w, cam_h)
|
||||
stride_pad = stride - cam_w
|
||||
|
||||
def warp_dm(input_frame, M_inv):
|
||||
M_inv = M_inv.to(Device.DEFAULT)
|
||||
result = warp_perspective_tinygrad(input_frame[:cam_h*stride], M_inv, (dm_w, dm_h), (cam_h, cam_w), stride_pad).reshape(-1, dm_h * dm_w)
|
||||
return result
|
||||
return warp_dm
|
||||
|
||||
|
||||
def compile_modeld_warp(cam_w, cam_h):
|
||||
model_w, model_h = MEDMODEL_INPUT_SIZE
|
||||
_, _, _, yuv_size = get_nv12_info(cam_w, cam_h)
|
||||
|
||||
print(f"Compiling modeld warp for {cam_w}x{cam_h}...")
|
||||
|
||||
frame_prepare = make_frame_prepare(cam_w, cam_h, model_w, model_h)
|
||||
update_both_imgs = make_update_both_imgs(frame_prepare, model_w, model_h)
|
||||
update_img_jit = TinyJit(update_both_imgs, prune=True)
|
||||
|
||||
full_buffer = Tensor.zeros(IMG_BUFFER_SHAPE, dtype='uint8').contiguous().realize()
|
||||
big_full_buffer = Tensor.zeros(IMG_BUFFER_SHAPE, dtype='uint8').contiguous().realize()
|
||||
full_buffer_np = np.zeros(IMG_BUFFER_SHAPE, dtype=np.uint8)
|
||||
big_full_buffer_np = np.zeros(IMG_BUFFER_SHAPE, dtype=np.uint8)
|
||||
|
||||
for i in range(10):
|
||||
new_frame_np = (32 * np.random.randn(yuv_size).astype(np.float32) + 128).clip(0, 255).astype(np.uint8)
|
||||
img_inputs = [full_buffer,
|
||||
Tensor.from_blob(new_frame_np.ctypes.data, (yuv_size,), dtype='uint8').realize(),
|
||||
Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY')]
|
||||
new_big_frame_np = (32 * np.random.randn(yuv_size).astype(np.float32) + 128).clip(0, 255).astype(np.uint8)
|
||||
big_img_inputs = [big_full_buffer,
|
||||
Tensor.from_blob(new_big_frame_np.ctypes.data, (yuv_size,), dtype='uint8').realize(),
|
||||
Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY')]
|
||||
inputs = img_inputs + big_img_inputs
|
||||
Device.default.synchronize()
|
||||
|
||||
inputs_np = [x.numpy() for x in inputs]
|
||||
inputs_np[0] = full_buffer_np
|
||||
inputs_np[3] = big_full_buffer_np
|
||||
|
||||
st = time.perf_counter()
|
||||
out = update_img_jit(*inputs)
|
||||
full_buffer = out[0].contiguous().realize().clone()
|
||||
big_full_buffer = out[2].contiguous().realize().clone()
|
||||
mt = time.perf_counter()
|
||||
Device.default.synchronize()
|
||||
et = time.perf_counter()
|
||||
print(f" [{i+1}/10] enqueue {(mt-st)*1e3:6.2f} ms -- total {(et-st)*1e3:6.2f} ms")
|
||||
|
||||
pkl_path = warp_pkl_path(cam_w, cam_h)
|
||||
with open(pkl_path, "wb") as f:
|
||||
pickle.dump(update_img_jit, f)
|
||||
print(f" Saved to {pkl_path}")
|
||||
|
||||
jit = pickle.load(open(pkl_path, "rb"))
|
||||
jit(*inputs)
|
||||
|
||||
|
||||
def compile_dm_warp(cam_w, cam_h):
|
||||
dm_w, dm_h = DM_INPUT_SIZE
|
||||
_, _, _, yuv_size = get_nv12_info(cam_w, cam_h)
|
||||
|
||||
print(f"Compiling DM warp for {cam_w}x{cam_h}...")
|
||||
|
||||
warp_dm = make_warp_dm(cam_w, cam_h, dm_w, dm_h)
|
||||
warp_dm_jit = TinyJit(warp_dm, prune=True)
|
||||
|
||||
for i in range(10):
|
||||
inputs = [Tensor.from_blob((32 * Tensor.randn(yuv_size,) + 128).cast(dtype='uint8').realize().numpy().ctypes.data, (yuv_size,), dtype='uint8'),
|
||||
Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY')]
|
||||
Device.default.synchronize()
|
||||
st = time.perf_counter()
|
||||
warp_dm_jit(*inputs)
|
||||
mt = time.perf_counter()
|
||||
Device.default.synchronize()
|
||||
et = time.perf_counter()
|
||||
print(f" [{i+1}/10] enqueue {(mt-st)*1e3:6.2f} ms -- total {(et-st)*1e3:6.2f} ms")
|
||||
|
||||
pkl_path = dm_warp_pkl_path(cam_w, cam_h)
|
||||
with open(pkl_path, "wb") as f:
|
||||
pickle.dump(warp_dm_jit, f)
|
||||
print(f" Saved to {pkl_path}")
|
||||
|
||||
|
||||
def run_and_save_pickle():
|
||||
for cam_w, cam_h in CAMERA_CONFIGS:
|
||||
compile_modeld_warp(cam_w, cam_h)
|
||||
compile_dm_warp(cam_w, cam_h)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_and_save_pickle()
|
||||
@@ -0,0 +1,87 @@
|
||||
import numpy as np
|
||||
|
||||
def index_function(idx, max_val=192, max_idx=32):
|
||||
return (max_val) * ((idx/max_idx)**2)
|
||||
|
||||
class ModelConstants:
|
||||
# time and distance indices
|
||||
IDX_N = 33
|
||||
T_IDXS = [index_function(idx, max_val=10.0) for idx in range(IDX_N)]
|
||||
X_IDXS = [index_function(idx, max_val=192.0) for idx in range(IDX_N)]
|
||||
LEAD_T_IDXS = [0., 2., 4., 6., 8., 10.]
|
||||
LEAD_T_OFFSETS = [0., 2., 4.]
|
||||
META_T_IDXS = [2., 4., 6., 8., 10.]
|
||||
|
||||
# model inputs constants
|
||||
N_FRAMES = 2
|
||||
MODEL_RUN_FREQ = 20
|
||||
MODEL_CONTEXT_FREQ = 5 # "model_trained_fps"
|
||||
|
||||
FEATURE_LEN = 512
|
||||
|
||||
DESIRE_LEN = 8
|
||||
TRAFFIC_CONVENTION_LEN = 2
|
||||
LAT_PLANNER_STATE_LEN = 4
|
||||
LATERAL_CONTROL_PARAMS_LEN = 2
|
||||
PREV_DESIRED_CURV_LEN = 1
|
||||
|
||||
# model outputs constants
|
||||
FCW_THRESHOLDS_5MS2 = np.array([.05, .05, .15, .15, .15], dtype=np.float32)
|
||||
FCW_THRESHOLDS_3MS2 = np.array([.7, .7], dtype=np.float32)
|
||||
FCW_5MS2_PROBS_WIDTH = 5
|
||||
FCW_3MS2_PROBS_WIDTH = 2
|
||||
|
||||
DISENGAGE_WIDTH = 5
|
||||
POSE_WIDTH = 6
|
||||
WIDE_FROM_DEVICE_WIDTH = 3
|
||||
LEAD_WIDTH = 4
|
||||
LANE_LINES_WIDTH = 2
|
||||
ROAD_EDGES_WIDTH = 2
|
||||
PLAN_WIDTH = 15
|
||||
DESIRE_PRED_WIDTH = 8
|
||||
LAT_PLANNER_SOLUTION_WIDTH = 4
|
||||
DESIRED_CURV_WIDTH = 1
|
||||
|
||||
NUM_LANE_LINES = 4
|
||||
NUM_ROAD_EDGES = 2
|
||||
|
||||
LEAD_TRAJ_LEN = 6
|
||||
DESIRE_PRED_LEN = 4
|
||||
|
||||
PLAN_MHP_N = 5
|
||||
LEAD_MHP_N = 2
|
||||
PLAN_MHP_SELECTION = 1
|
||||
LEAD_MHP_SELECTION = 3
|
||||
|
||||
FCW_THRESHOLD_5MS2_HIGH = 0.15
|
||||
FCW_THRESHOLD_5MS2_LOW = 0.05
|
||||
FCW_THRESHOLD_3MS2 = 0.7
|
||||
|
||||
CONFIDENCE_BUFFER_LEN = 5
|
||||
RYG_GREEN = 0.01165
|
||||
RYG_YELLOW = 0.06157
|
||||
|
||||
POLY_PATH_DEGREE = 4
|
||||
|
||||
# model outputs slices
|
||||
class Plan:
|
||||
POSITION = slice(0, 3)
|
||||
VELOCITY = slice(3, 6)
|
||||
ACCELERATION = slice(6, 9)
|
||||
T_FROM_CURRENT_EULER = slice(9, 12)
|
||||
ORIENTATION_RATE = slice(12, 15)
|
||||
|
||||
class Meta:
|
||||
ENGAGED = slice(0, 1)
|
||||
# next 2, 4, 6, 8, 10 seconds
|
||||
GAS_DISENGAGE = slice(1, 31, 6)
|
||||
BRAKE_DISENGAGE = slice(2, 31, 6)
|
||||
STEER_OVERRIDE = slice(3, 31, 6)
|
||||
HARD_BRAKE_3 = slice(4, 31, 6)
|
||||
HARD_BRAKE_4 = slice(5, 31, 6)
|
||||
HARD_BRAKE_5 = slice(6, 31, 6)
|
||||
# next 0, 2, 4, 6, 8, 10 seconds
|
||||
GAS_PRESS = slice(31, 55, 4)
|
||||
BRAKE_PRESS = slice(32, 55, 4)
|
||||
LEFT_BLINKER = slice(33, 55, 4)
|
||||
RIGHT_BLINKER = slice(34, 55, 4)
|
||||
@@ -0,0 +1,193 @@
|
||||
import os
|
||||
import capnp
|
||||
import numpy as np
|
||||
from cereal import log
|
||||
from openpilot.selfdrive.modeld.constants import ModelConstants, Plan, Meta
|
||||
|
||||
SEND_RAW_PRED = os.getenv('SEND_RAW_PRED')
|
||||
|
||||
ConfidenceClass = log.ModelDataV2.ConfidenceClass
|
||||
|
||||
|
||||
class PublishState:
|
||||
def __init__(self):
|
||||
self.disengage_buffer = np.zeros(ModelConstants.CONFIDENCE_BUFFER_LEN*ModelConstants.DISENGAGE_WIDTH, dtype=np.float32)
|
||||
self.prev_brake_5ms2_probs = np.zeros(ModelConstants.FCW_5MS2_PROBS_WIDTH, dtype=np.float32)
|
||||
self.prev_brake_3ms2_probs = np.zeros(ModelConstants.FCW_3MS2_PROBS_WIDTH, dtype=np.float32)
|
||||
|
||||
def fill_xyzt(builder, t, x, y, z, x_std=None, y_std=None, z_std=None):
|
||||
builder.t = t
|
||||
builder.x = x.tolist()
|
||||
builder.y = y.tolist()
|
||||
builder.z = z.tolist()
|
||||
if x_std is not None:
|
||||
builder.xStd = x_std.tolist()
|
||||
if y_std is not None:
|
||||
builder.yStd = y_std.tolist()
|
||||
if z_std is not None:
|
||||
builder.zStd = z_std.tolist()
|
||||
|
||||
def fill_xyvat(builder, t, x, y, v, a, x_std=None, y_std=None, v_std=None, a_std=None):
|
||||
builder.t = t
|
||||
builder.x = x.tolist()
|
||||
builder.y = y.tolist()
|
||||
builder.v = v.tolist()
|
||||
builder.a = a.tolist()
|
||||
if x_std is not None:
|
||||
builder.xStd = x_std.tolist()
|
||||
if y_std is not None:
|
||||
builder.yStd = y_std.tolist()
|
||||
if v_std is not None:
|
||||
builder.vStd = v_std.tolist()
|
||||
if a_std is not None:
|
||||
builder.aStd = a_std.tolist()
|
||||
|
||||
def fill_xyz_poly(builder, degree, x, y, z):
|
||||
xyz = np.stack([x, y, z], axis=1)
|
||||
coeffs = np.polynomial.polynomial.polyfit(ModelConstants.T_IDXS, xyz, deg=degree)
|
||||
builder.xCoefficients = coeffs[:, 0].tolist()
|
||||
builder.yCoefficients = coeffs[:, 1].tolist()
|
||||
builder.zCoefficients = coeffs[:, 2].tolist()
|
||||
|
||||
def fill_lane_line_meta(builder, lane_lines, lane_line_probs):
|
||||
builder.leftY = lane_lines[1].y[0]
|
||||
builder.leftProb = lane_line_probs[1]
|
||||
builder.rightY = lane_lines[2].y[0]
|
||||
builder.rightProb = lane_line_probs[2]
|
||||
|
||||
def fill_model_msg(base_msg: capnp._DynamicStructBuilder, extended_msg: capnp._DynamicStructBuilder,
|
||||
net_output_data: dict[str, np.ndarray], action: log.ModelDataV2.Action,
|
||||
publish_state: PublishState, vipc_frame_id: int, vipc_frame_id_extra: int,
|
||||
frame_id: int, frame_drop: float, timestamp_eof: int, model_execution_time: float,
|
||||
valid: bool) -> None:
|
||||
frame_age = frame_id - vipc_frame_id if frame_id > vipc_frame_id else 0
|
||||
frame_drop_perc = frame_drop * 100
|
||||
extended_msg.valid = valid
|
||||
base_msg.valid = valid
|
||||
|
||||
driving_model_data = base_msg.drivingModelData
|
||||
|
||||
driving_model_data.frameId = vipc_frame_id
|
||||
driving_model_data.frameIdExtra = vipc_frame_id_extra
|
||||
driving_model_data.frameDropPerc = frame_drop_perc
|
||||
driving_model_data.modelExecutionTime = model_execution_time
|
||||
|
||||
driving_model_data.action = action
|
||||
|
||||
modelV2 = extended_msg.modelV2
|
||||
modelV2.frameId = vipc_frame_id
|
||||
modelV2.frameIdExtra = vipc_frame_id_extra
|
||||
modelV2.frameAge = frame_age
|
||||
modelV2.frameDropPerc = frame_drop_perc
|
||||
modelV2.timestampEof = timestamp_eof
|
||||
modelV2.modelExecutionTime = model_execution_time
|
||||
|
||||
# plan
|
||||
fill_xyzt(modelV2.position, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.POSITION].T, *net_output_data['plan_stds'][0,:,Plan.POSITION].T)
|
||||
fill_xyzt(modelV2.velocity, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.VELOCITY].T)
|
||||
fill_xyzt(modelV2.acceleration, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ACCELERATION].T)
|
||||
fill_xyzt(modelV2.orientation, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.T_FROM_CURRENT_EULER].T)
|
||||
fill_xyzt(modelV2.orientationRate, ModelConstants.T_IDXS, *net_output_data['plan'][0,:,Plan.ORIENTATION_RATE].T)
|
||||
|
||||
# poly path
|
||||
fill_xyz_poly(driving_model_data.path, ModelConstants.POLY_PATH_DEGREE, *net_output_data['plan'][0,:,Plan.POSITION].T)
|
||||
|
||||
# action
|
||||
modelV2.action = action
|
||||
|
||||
# times at X_IDXS of edges and lines aren't used
|
||||
LINE_T_IDXS: list[float] = []
|
||||
|
||||
# lane lines
|
||||
modelV2.init('laneLines', 4)
|
||||
for i in range(4):
|
||||
lane_line = modelV2.laneLines[i]
|
||||
fill_xyzt(lane_line, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['lane_lines'][0,i,:,0], net_output_data['lane_lines'][0,i,:,1])
|
||||
modelV2.laneLineStds = net_output_data['lane_lines_stds'][0,:,0,0].tolist()
|
||||
modelV2.laneLineProbs = net_output_data['lane_lines_prob'][0,1::2].tolist()
|
||||
|
||||
fill_lane_line_meta(driving_model_data.laneLineMeta, modelV2.laneLines, modelV2.laneLineProbs)
|
||||
|
||||
# road edges
|
||||
modelV2.init('roadEdges', 2)
|
||||
for i in range(2):
|
||||
road_edge = modelV2.roadEdges[i]
|
||||
fill_xyzt(road_edge, LINE_T_IDXS, np.array(ModelConstants.X_IDXS), net_output_data['road_edges'][0,i,:,0], net_output_data['road_edges'][0,i,:,1])
|
||||
modelV2.roadEdgeStds = net_output_data['road_edges_stds'][0,:,0,0].tolist()
|
||||
|
||||
# leads
|
||||
modelV2.init('leadsV3', 3)
|
||||
for i in range(3):
|
||||
lead = modelV2.leadsV3[i]
|
||||
fill_xyvat(lead, ModelConstants.LEAD_T_IDXS, *net_output_data['lead'][0,i].T, *net_output_data['lead_stds'][0,i].T)
|
||||
lead.prob = net_output_data['lead_prob'][0,i].tolist()
|
||||
lead.probTime = ModelConstants.LEAD_T_OFFSETS[i]
|
||||
|
||||
# meta
|
||||
meta = modelV2.meta
|
||||
meta.desireState = net_output_data['desire_state'][0].reshape(-1).tolist()
|
||||
meta.desirePrediction = net_output_data['desire_pred'][0].reshape(-1).tolist()
|
||||
meta.engagedProb = net_output_data['meta'][0,Meta.ENGAGED].item()
|
||||
meta.init('disengagePredictions')
|
||||
disengage_predictions = meta.disengagePredictions
|
||||
disengage_predictions.t = ModelConstants.META_T_IDXS
|
||||
disengage_predictions.brakeDisengageProbs = net_output_data['meta'][0,Meta.BRAKE_DISENGAGE].tolist()
|
||||
disengage_predictions.gasDisengageProbs = net_output_data['meta'][0,Meta.GAS_DISENGAGE].tolist()
|
||||
disengage_predictions.steerOverrideProbs = net_output_data['meta'][0,Meta.STEER_OVERRIDE].tolist()
|
||||
disengage_predictions.brake3MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_3].tolist()
|
||||
disengage_predictions.brake4MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_4].tolist()
|
||||
disengage_predictions.brake5MetersPerSecondSquaredProbs = net_output_data['meta'][0,Meta.HARD_BRAKE_5].tolist()
|
||||
disengage_predictions.gasPressProbs = net_output_data['meta'][0,Meta.GAS_PRESS].tolist()
|
||||
disengage_predictions.brakePressProbs = net_output_data['meta'][0,Meta.BRAKE_PRESS].tolist()
|
||||
|
||||
publish_state.prev_brake_5ms2_probs[:-1] = publish_state.prev_brake_5ms2_probs[1:]
|
||||
publish_state.prev_brake_5ms2_probs[-1] = net_output_data['meta'][0,Meta.HARD_BRAKE_5][0]
|
||||
publish_state.prev_brake_3ms2_probs[:-1] = publish_state.prev_brake_3ms2_probs[1:]
|
||||
publish_state.prev_brake_3ms2_probs[-1] = net_output_data['meta'][0,Meta.HARD_BRAKE_3][0]
|
||||
hard_brake_predicted = (publish_state.prev_brake_5ms2_probs > ModelConstants.FCW_THRESHOLDS_5MS2).all() and \
|
||||
(publish_state.prev_brake_3ms2_probs > ModelConstants.FCW_THRESHOLDS_3MS2).all()
|
||||
meta.hardBrakePredicted = hard_brake_predicted.item()
|
||||
|
||||
# confidence
|
||||
if vipc_frame_id % (2*ModelConstants.MODEL_RUN_FREQ) == 0:
|
||||
# any disengage prob
|
||||
brake_disengage_probs = net_output_data['meta'][0,Meta.BRAKE_DISENGAGE]
|
||||
gas_disengage_probs = net_output_data['meta'][0,Meta.GAS_DISENGAGE]
|
||||
steer_override_probs = net_output_data['meta'][0,Meta.STEER_OVERRIDE]
|
||||
any_disengage_probs = 1-((1-brake_disengage_probs)*(1-gas_disengage_probs)*(1-steer_override_probs))
|
||||
# independent disengage prob for each 2s slice
|
||||
ind_disengage_probs = np.r_[any_disengage_probs[0], np.diff(any_disengage_probs) / (1 - any_disengage_probs[:-1])]
|
||||
# rolling buf for 2, 4, 6, 8, 10s
|
||||
publish_state.disengage_buffer[:-ModelConstants.DISENGAGE_WIDTH] = publish_state.disengage_buffer[ModelConstants.DISENGAGE_WIDTH:]
|
||||
publish_state.disengage_buffer[-ModelConstants.DISENGAGE_WIDTH:] = ind_disengage_probs
|
||||
|
||||
score = 0.
|
||||
for i in range(ModelConstants.DISENGAGE_WIDTH):
|
||||
score += publish_state.disengage_buffer[i*ModelConstants.DISENGAGE_WIDTH+ModelConstants.DISENGAGE_WIDTH-1-i].item() / ModelConstants.DISENGAGE_WIDTH
|
||||
if score < ModelConstants.RYG_GREEN:
|
||||
modelV2.confidence = ConfidenceClass.green
|
||||
elif score < ModelConstants.RYG_YELLOW:
|
||||
modelV2.confidence = ConfidenceClass.yellow
|
||||
else:
|
||||
modelV2.confidence = ConfidenceClass.red
|
||||
|
||||
# raw prediction if enabled
|
||||
if SEND_RAW_PRED:
|
||||
modelV2.rawPredictions = net_output_data['raw_pred'].tobytes()
|
||||
|
||||
def fill_pose_msg(msg: capnp._DynamicStructBuilder, net_output_data: dict[str, np.ndarray],
|
||||
vipc_frame_id: int, vipc_dropped_frames: int, timestamp_eof: int, live_calib_seen: bool) -> None:
|
||||
msg.valid = live_calib_seen & (vipc_dropped_frames < 1)
|
||||
cameraOdometry = msg.cameraOdometry
|
||||
|
||||
cameraOdometry.frameId = vipc_frame_id
|
||||
cameraOdometry.timestampEof = timestamp_eof
|
||||
|
||||
cameraOdometry.trans = net_output_data['pose'][0,:3].tolist()
|
||||
cameraOdometry.rot = net_output_data['pose'][0,3:].tolist()
|
||||
cameraOdometry.wideFromDeviceEuler = net_output_data['wide_from_device_euler'][0,:].tolist()
|
||||
cameraOdometry.roadTransformTrans = net_output_data['road_transform'][0,:3].tolist()
|
||||
cameraOdometry.transStd = net_output_data['pose_stds'][0,:3].tolist()
|
||||
cameraOdometry.rotStd = net_output_data['pose_stds'][0,3:].tolist()
|
||||
cameraOdometry.wideFromDeviceEulerStd = net_output_data['wide_from_device_euler_stds'][0,:].tolist()
|
||||
cameraOdometry.roadTransformTransStd = net_output_data['road_transform_stds'][0,:3].tolist()
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import pathlib
|
||||
import codecs
|
||||
import pickle
|
||||
from typing import Any
|
||||
|
||||
from tinygrad.nn.onnx import OnnxPBParser
|
||||
|
||||
|
||||
class MetadataOnnxPBParser(OnnxPBParser):
|
||||
def _parse_ModelProto(self) -> dict:
|
||||
obj: dict[str, Any] = {"graph": {"input": [], "output": []}, "metadata_props": []}
|
||||
for fid, wire_type in self._parse_message(self.reader.len):
|
||||
match fid:
|
||||
case 7:
|
||||
obj["graph"] = self._parse_GraphProto()
|
||||
case 14:
|
||||
obj["metadata_props"].append(self._parse_StringStringEntryProto())
|
||||
case _:
|
||||
self.reader.skip_field(wire_type)
|
||||
return obj
|
||||
|
||||
|
||||
def get_name_and_shape(value_info: dict[str, Any]) -> tuple[str, tuple[int, ...]]:
|
||||
shape = tuple(int(dim) if isinstance(dim, int) else 0 for dim in value_info["parsed_type"].shape)
|
||||
name = value_info["name"]
|
||||
return name, shape
|
||||
|
||||
|
||||
def get_metadata_value_by_name(model: dict[str, Any], name: str) -> str | Any:
|
||||
for prop in model["metadata_props"]:
|
||||
if prop["key"] == name:
|
||||
return prop["value"]
|
||||
return None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
model_path = pathlib.Path(sys.argv[1])
|
||||
model = MetadataOnnxPBParser(model_path).parse()
|
||||
output_slices = get_metadata_value_by_name(model, 'output_slices')
|
||||
assert output_slices is not None, 'output_slices not found in metadata'
|
||||
|
||||
metadata = {
|
||||
'model_checkpoint': get_metadata_value_by_name(model, 'model_checkpoint'),
|
||||
'output_slices': pickle.loads(codecs.decode(output_slices.encode(), "base64")),
|
||||
'input_shapes': dict(get_name_and_shape(x) for x in model["graph"]["input"]),
|
||||
'output_shapes': dict(get_name_and_shape(x) for x in model["graph"]["output"]),
|
||||
}
|
||||
|
||||
metadata_path = model_path.parent / (model_path.stem + '_metadata.pkl')
|
||||
with open(metadata_path, 'wb') as f:
|
||||
pickle.dump(metadata, f)
|
||||
|
||||
print(f'saved metadata to {metadata_path}')
|
||||
@@ -0,0 +1,422 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
from openpilot.system.hardware import TICI
|
||||
os.environ['DEV'] = 'QCOM' if TICI else 'CPU'
|
||||
USBGPU = "USBGPU" in os.environ
|
||||
if USBGPU:
|
||||
os.environ['DEV'] = 'AMD'
|
||||
os.environ['AMD_IFACE'] = 'USB'
|
||||
from tinygrad.tensor import Tensor
|
||||
import time
|
||||
import pickle
|
||||
import numpy as np
|
||||
import cereal.messaging as messaging
|
||||
from cereal import car, log
|
||||
from pathlib import Path
|
||||
from cereal.messaging import PubMaster, SubMaster
|
||||
from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf
|
||||
from opendbc.car.car_helpers import get_demo_car_params
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.filter_simple import FirstOrderFilter
|
||||
from openpilot.common.realtime import config_realtime_process, DT_MDL
|
||||
from openpilot.common.transformations.camera import DEVICE_CAMERAS
|
||||
from openpilot.system.camerad.cameras.nv12_info import get_nv12_info
|
||||
from openpilot.common.transformations.model import get_warp_matrix
|
||||
from openpilot.selfdrive.controls.lib.desire_helper import DesireHelper
|
||||
from openpilot.selfdrive.controls.lib.drive_helpers import get_accel_from_plan, smooth_value, get_curvature_from_plan
|
||||
from openpilot.selfdrive.modeld.parse_model_outputs import Parser
|
||||
from openpilot.selfdrive.modeld.fill_model_msg import fill_model_msg, fill_pose_msg, PublishState
|
||||
from openpilot.common.file_chunker import read_file_chunked
|
||||
from openpilot.selfdrive.modeld.constants import ModelConstants, Plan
|
||||
|
||||
|
||||
PROCESS_NAME = "selfdrive.modeld.modeld"
|
||||
SEND_RAW_PRED = os.getenv('SEND_RAW_PRED')
|
||||
|
||||
VISION_PKL_PATH = Path(__file__).parent / 'models/driving_vision_tinygrad.pkl'
|
||||
POLICY_PKL_PATH = Path(__file__).parent / 'models/driving_policy_tinygrad.pkl'
|
||||
VISION_METADATA_PATH = Path(__file__).parent / 'models/driving_vision_metadata.pkl'
|
||||
POLICY_METADATA_PATH = Path(__file__).parent / 'models/driving_policy_metadata.pkl'
|
||||
MODELS_DIR = Path(__file__).parent / 'models'
|
||||
|
||||
LAT_SMOOTH_SECONDS = 0.0
|
||||
LONG_SMOOTH_SECONDS = 0.3
|
||||
MIN_LAT_CONTROL_SPEED = 0.3
|
||||
|
||||
IMG_QUEUE_SHAPE = (6*(ModelConstants.MODEL_RUN_FREQ//ModelConstants.MODEL_CONTEXT_FREQ + 1), 128, 256)
|
||||
assert IMG_QUEUE_SHAPE[0] == 30
|
||||
|
||||
|
||||
def get_action_from_model(model_output: dict[str, np.ndarray], prev_action: log.ModelDataV2.Action,
|
||||
lat_action_t: float, long_action_t: float, v_ego: float) -> log.ModelDataV2.Action:
|
||||
plan = model_output['plan'][0]
|
||||
desired_accel, should_stop = get_accel_from_plan(plan[:,Plan.VELOCITY][:,0],
|
||||
plan[:,Plan.ACCELERATION][:,0],
|
||||
ModelConstants.T_IDXS,
|
||||
action_t=long_action_t)
|
||||
desired_accel = smooth_value(desired_accel, prev_action.desiredAcceleration, LONG_SMOOTH_SECONDS)
|
||||
|
||||
desired_curvature = get_curvature_from_plan(plan[:,Plan.T_FROM_CURRENT_EULER][:,2],
|
||||
plan[:,Plan.ORIENTATION_RATE][:,2],
|
||||
ModelConstants.T_IDXS,
|
||||
v_ego,
|
||||
lat_action_t)
|
||||
if v_ego > MIN_LAT_CONTROL_SPEED:
|
||||
desired_curvature = smooth_value(desired_curvature, prev_action.desiredCurvature, LAT_SMOOTH_SECONDS)
|
||||
else:
|
||||
desired_curvature = prev_action.desiredCurvature
|
||||
|
||||
return log.ModelDataV2.Action(desiredCurvature=float(desired_curvature),
|
||||
desiredAcceleration=float(desired_accel),
|
||||
shouldStop=bool(should_stop))
|
||||
|
||||
class FrameMeta:
|
||||
frame_id: int = 0
|
||||
timestamp_sof: int = 0
|
||||
timestamp_eof: int = 0
|
||||
|
||||
def __init__(self, vipc=None):
|
||||
if vipc is not None:
|
||||
self.frame_id, self.timestamp_sof, self.timestamp_eof = vipc.frame_id, vipc.timestamp_sof, vipc.timestamp_eof
|
||||
|
||||
class InputQueues:
|
||||
def __init__ (self, model_fps, env_fps, n_frames_input):
|
||||
assert env_fps % model_fps == 0
|
||||
assert env_fps >= model_fps
|
||||
self.model_fps = model_fps
|
||||
self.env_fps = env_fps
|
||||
self.n_frames_input = n_frames_input
|
||||
|
||||
self.dtypes = {}
|
||||
self.shapes = {}
|
||||
self.q = {}
|
||||
|
||||
def update_dtypes_and_shapes(self, input_dtypes, input_shapes) -> None:
|
||||
self.dtypes.update(input_dtypes)
|
||||
if self.env_fps == self.model_fps:
|
||||
self.shapes.update(input_shapes)
|
||||
else:
|
||||
for k in input_shapes:
|
||||
shape = list(input_shapes[k])
|
||||
if 'img' in k:
|
||||
n_channels = shape[1] // self.n_frames_input
|
||||
shape[1] = (self.env_fps // self.model_fps + (self.n_frames_input - 1)) * n_channels
|
||||
else:
|
||||
shape[1] = (self.env_fps // self.model_fps) * shape[1]
|
||||
self.shapes[k] = tuple(shape)
|
||||
|
||||
def reset(self) -> None:
|
||||
self.q = {k: np.zeros(self.shapes[k], dtype=self.dtypes[k]) for k in self.dtypes.keys()}
|
||||
|
||||
def enqueue(self, inputs:dict[str, np.ndarray]) -> None:
|
||||
for k in inputs.keys():
|
||||
if inputs[k].dtype != self.dtypes[k]:
|
||||
raise ValueError(f'supplied input <{k}({inputs[k].dtype})> has wrong dtype, expected {self.dtypes[k]}')
|
||||
input_shape = list(self.shapes[k])
|
||||
input_shape[1] = -1
|
||||
single_input = inputs[k].reshape(tuple(input_shape))
|
||||
sz = single_input.shape[1]
|
||||
self.q[k][:,:-sz] = self.q[k][:,sz:]
|
||||
self.q[k][:,-sz:] = single_input
|
||||
|
||||
def get(self, *names) -> dict[str, np.ndarray]:
|
||||
if self.env_fps == self.model_fps:
|
||||
return {k: self.q[k] for k in names}
|
||||
else:
|
||||
out = {}
|
||||
for k in names:
|
||||
shape = self.shapes[k]
|
||||
if 'img' in k:
|
||||
n_channels = shape[1] // (self.env_fps // self.model_fps + (self.n_frames_input - 1))
|
||||
out[k] = np.concatenate([self.q[k][:, s:s+n_channels] for s in np.linspace(0, shape[1] - n_channels, self.n_frames_input, dtype=int)], axis=1)
|
||||
elif 'pulse' in k:
|
||||
# any pulse within interval counts
|
||||
out[k] = self.q[k].reshape((shape[0], shape[1] * self.model_fps // self.env_fps, self.env_fps // self.model_fps, -1)).max(axis=2)
|
||||
else:
|
||||
idxs = np.arange(-1, -shape[1], -self.env_fps // self.model_fps)[::-1]
|
||||
out[k] = self.q[k][:, idxs]
|
||||
return out
|
||||
|
||||
class ModelState:
|
||||
inputs: dict[str, np.ndarray]
|
||||
output: np.ndarray
|
||||
prev_desire: np.ndarray # for tracking the rising edge of the pulse
|
||||
|
||||
def __init__(self):
|
||||
with open(VISION_METADATA_PATH, 'rb') as f:
|
||||
vision_metadata = pickle.load(f)
|
||||
self.vision_input_shapes = vision_metadata['input_shapes']
|
||||
self.vision_input_names = list(self.vision_input_shapes.keys())
|
||||
self.vision_output_slices = vision_metadata['output_slices']
|
||||
vision_output_size = vision_metadata['output_shapes']['outputs'][1]
|
||||
|
||||
with open(POLICY_METADATA_PATH, 'rb') as f:
|
||||
policy_metadata = pickle.load(f)
|
||||
self.policy_input_shapes = policy_metadata['input_shapes']
|
||||
self.policy_output_slices = policy_metadata['output_slices']
|
||||
policy_output_size = policy_metadata['output_shapes']['outputs'][1]
|
||||
|
||||
self.prev_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32)
|
||||
|
||||
# policy inputs
|
||||
self.numpy_inputs = {k: np.zeros(self.policy_input_shapes[k], dtype=np.float32) for k in self.policy_input_shapes}
|
||||
self.full_input_queues = InputQueues(ModelConstants.MODEL_CONTEXT_FREQ, ModelConstants.MODEL_RUN_FREQ, ModelConstants.N_FRAMES)
|
||||
for k in ['desire_pulse', 'features_buffer']:
|
||||
self.full_input_queues.update_dtypes_and_shapes({k: self.numpy_inputs[k].dtype}, {k: self.numpy_inputs[k].shape})
|
||||
self.full_input_queues.reset()
|
||||
|
||||
self.img_queues = {'img': Tensor.zeros(IMG_QUEUE_SHAPE, dtype='uint8').contiguous().realize(),
|
||||
'big_img': Tensor.zeros(IMG_QUEUE_SHAPE, dtype='uint8').contiguous().realize()}
|
||||
self.full_frames : dict[str, Tensor] = {}
|
||||
self._blob_cache : dict[int, Tensor] = {}
|
||||
self.transforms_np = {k: np.zeros((3,3), dtype=np.float32) for k in self.img_queues}
|
||||
self.transforms = {k: Tensor(v, device='NPY').realize() for k, v in self.transforms_np.items()}
|
||||
self.vision_output = np.zeros(vision_output_size, dtype=np.float32)
|
||||
self.policy_inputs = {k: Tensor(v, device='NPY').realize() for k,v in self.numpy_inputs.items()}
|
||||
self.policy_output = np.zeros(policy_output_size, dtype=np.float32)
|
||||
self.parser = Parser()
|
||||
self.frame_buf_params : dict[str, tuple[int, int, int, int]] = {}
|
||||
self.update_imgs = None
|
||||
self.vision_run = pickle.loads(read_file_chunked(str(VISION_PKL_PATH)))
|
||||
self.policy_run = pickle.loads(read_file_chunked(str(POLICY_PKL_PATH)))
|
||||
|
||||
def slice_outputs(self, model_outputs: np.ndarray, output_slices: dict[str, slice]) -> dict[str, np.ndarray]:
|
||||
parsed_model_outputs = {k: model_outputs[np.newaxis, v] for k,v in output_slices.items()}
|
||||
return parsed_model_outputs
|
||||
|
||||
def run(self, bufs: dict[str, VisionBuf], transforms: dict[str, np.ndarray],
|
||||
inputs: dict[str, np.ndarray], prepare_only: bool) -> dict[str, np.ndarray] | None:
|
||||
# Model decides when action is completed, so desire input is just a pulse triggered on rising edge
|
||||
inputs['desire_pulse'][0] = 0
|
||||
new_desire = np.where(inputs['desire_pulse'] - self.prev_desire > .99, inputs['desire_pulse'], 0)
|
||||
self.prev_desire[:] = inputs['desire_pulse']
|
||||
if self.update_imgs is None:
|
||||
for key in bufs.keys():
|
||||
w, h = bufs[key].width, bufs[key].height
|
||||
self.frame_buf_params[key] = get_nv12_info(w, h)
|
||||
warp_path = MODELS_DIR / f'warp_{w}x{h}_tinygrad.pkl'
|
||||
with open(warp_path, "rb") as f:
|
||||
self.update_imgs = pickle.load(f)
|
||||
|
||||
for key in bufs.keys():
|
||||
ptr = bufs[key].data.ctypes.data
|
||||
yuv_size = self.frame_buf_params[key][3]
|
||||
# There is a ringbuffer of imgs, just cache tensors pointing to all of them
|
||||
cache_key = (key, ptr)
|
||||
if cache_key not in self._blob_cache:
|
||||
self._blob_cache[cache_key] = Tensor.from_blob(ptr, (yuv_size,), dtype='uint8')
|
||||
self.full_frames[key] = self._blob_cache[cache_key]
|
||||
for key in bufs.keys():
|
||||
self.transforms_np[key][:,:] = transforms[key][:,:]
|
||||
|
||||
out = self.update_imgs(self.img_queues['img'], self.full_frames['img'], self.transforms['img'],
|
||||
self.img_queues['big_img'], self.full_frames['big_img'], self.transforms['big_img'])
|
||||
self.img_queues['img'], self.img_queues['big_img'] = out[0].realize(), out[2].realize()
|
||||
vision_inputs = {'img': out[1], 'big_img': out[3]}
|
||||
|
||||
if prepare_only:
|
||||
return None
|
||||
|
||||
self.vision_output = self.vision_run(**vision_inputs).contiguous().realize().uop.base.buffer.numpy().flatten()
|
||||
vision_outputs_dict = self.parser.parse_vision_outputs(self.slice_outputs(self.vision_output, self.vision_output_slices))
|
||||
|
||||
self.full_input_queues.enqueue({'features_buffer': vision_outputs_dict['hidden_state'], 'desire_pulse': new_desire})
|
||||
for k in ['desire_pulse', 'features_buffer']:
|
||||
self.numpy_inputs[k][:] = self.full_input_queues.get(k)[k]
|
||||
self.numpy_inputs['traffic_convention'][:] = inputs['traffic_convention']
|
||||
|
||||
self.policy_output = self.policy_run(**self.policy_inputs).contiguous().realize().uop.base.buffer.numpy().flatten()
|
||||
policy_outputs_dict = self.parser.parse_policy_outputs(self.slice_outputs(self.policy_output, self.policy_output_slices))
|
||||
combined_outputs_dict = {**vision_outputs_dict, **policy_outputs_dict}
|
||||
if SEND_RAW_PRED:
|
||||
combined_outputs_dict['raw_pred'] = np.concatenate([self.vision_output.copy(), self.policy_output.copy()])
|
||||
|
||||
return combined_outputs_dict
|
||||
|
||||
|
||||
def main(demo=False):
|
||||
cloudlog.warning("modeld init")
|
||||
|
||||
if not USBGPU:
|
||||
# USB GPU currently saturates a core so can't do this yet,
|
||||
# also need to move the aux USB interrupts for good timings
|
||||
config_realtime_process(7, 54)
|
||||
|
||||
st = time.monotonic()
|
||||
cloudlog.warning("loading model")
|
||||
model = ModelState()
|
||||
cloudlog.warning(f"models loaded in {time.monotonic() - st:.1f}s, modeld starting")
|
||||
|
||||
# visionipc clients
|
||||
while True:
|
||||
available_streams = VisionIpcClient.available_streams("camerad", block=False)
|
||||
if available_streams:
|
||||
use_extra_client = VisionStreamType.VISION_STREAM_WIDE_ROAD in available_streams and VisionStreamType.VISION_STREAM_ROAD in available_streams
|
||||
main_wide_camera = VisionStreamType.VISION_STREAM_ROAD not in available_streams
|
||||
break
|
||||
time.sleep(.1)
|
||||
|
||||
vipc_client_main_stream = VisionStreamType.VISION_STREAM_WIDE_ROAD if main_wide_camera else VisionStreamType.VISION_STREAM_ROAD
|
||||
vipc_client_main = VisionIpcClient("camerad", vipc_client_main_stream, True)
|
||||
vipc_client_extra = VisionIpcClient("camerad", VisionStreamType.VISION_STREAM_WIDE_ROAD, False)
|
||||
cloudlog.warning(f"vision stream set up, main_wide_camera: {main_wide_camera}, use_extra_client: {use_extra_client}")
|
||||
|
||||
while not vipc_client_main.connect(False):
|
||||
time.sleep(0.1)
|
||||
while use_extra_client and not vipc_client_extra.connect(False):
|
||||
time.sleep(0.1)
|
||||
|
||||
cloudlog.warning(f"connected main cam with buffer size: {vipc_client_main.buffer_len} ({vipc_client_main.width} x {vipc_client_main.height})")
|
||||
if use_extra_client:
|
||||
cloudlog.warning(f"connected extra cam with buffer size: {vipc_client_extra.buffer_len} ({vipc_client_extra.width} x {vipc_client_extra.height})")
|
||||
|
||||
# messaging
|
||||
pm = PubMaster(["modelV2", "drivingModelData", "cameraOdometry"])
|
||||
sm = SubMaster(["deviceState", "carState", "roadCameraState", "liveCalibration", "driverMonitoringState", "carControl", "liveDelay"])
|
||||
|
||||
publish_state = PublishState()
|
||||
params = Params()
|
||||
|
||||
# setup filter to track dropped frames
|
||||
frame_dropped_filter = FirstOrderFilter(0., 10., 1. / ModelConstants.MODEL_RUN_FREQ)
|
||||
frame_id = 0
|
||||
last_vipc_frame_id = 0
|
||||
run_count = 0
|
||||
|
||||
model_transform_main = np.zeros((3, 3), dtype=np.float32)
|
||||
model_transform_extra = np.zeros((3, 3), dtype=np.float32)
|
||||
live_calib_seen = False
|
||||
buf_main, buf_extra = None, None
|
||||
meta_main = FrameMeta()
|
||||
meta_extra = FrameMeta()
|
||||
|
||||
|
||||
if demo:
|
||||
CP = get_demo_car_params()
|
||||
else:
|
||||
CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams)
|
||||
cloudlog.info("modeld got CarParams: %s", CP.brand)
|
||||
|
||||
# TODO this needs more thought, use .2s extra for now to estimate other delays
|
||||
# TODO Move smooth seconds to action function
|
||||
long_delay = CP.longitudinalActuatorDelay + LONG_SMOOTH_SECONDS
|
||||
prev_action = log.ModelDataV2.Action()
|
||||
|
||||
DH = DesireHelper()
|
||||
|
||||
while True:
|
||||
# Keep receiving frames until we are at least 1 frame ahead of previous extra frame
|
||||
while meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000:
|
||||
buf_main = vipc_client_main.recv()
|
||||
meta_main = FrameMeta(vipc_client_main)
|
||||
if buf_main is None:
|
||||
break
|
||||
|
||||
if buf_main is None:
|
||||
cloudlog.debug("vipc_client_main no frame")
|
||||
continue
|
||||
|
||||
if use_extra_client:
|
||||
# Keep receiving extra frames until frame id matches main camera
|
||||
while True:
|
||||
buf_extra = vipc_client_extra.recv()
|
||||
meta_extra = FrameMeta(vipc_client_extra)
|
||||
if buf_extra is None or meta_main.timestamp_sof < meta_extra.timestamp_sof + 25000000:
|
||||
break
|
||||
|
||||
if buf_extra is None:
|
||||
cloudlog.debug("vipc_client_extra no frame")
|
||||
continue
|
||||
|
||||
if abs(meta_main.timestamp_sof - meta_extra.timestamp_sof) > 10000000:
|
||||
cloudlog.error(f"frames out of sync! main: {meta_main.frame_id} ({meta_main.timestamp_sof / 1e9:.5f}),\
|
||||
extra: {meta_extra.frame_id} ({meta_extra.timestamp_sof / 1e9:.5f})")
|
||||
|
||||
else:
|
||||
# Use single camera
|
||||
buf_extra = buf_main
|
||||
meta_extra = meta_main
|
||||
|
||||
sm.update(0)
|
||||
desire = DH.desire
|
||||
is_rhd = sm["driverMonitoringState"].isRHD
|
||||
frame_id = sm["roadCameraState"].frameId
|
||||
v_ego = max(sm["carState"].vEgo, 0.)
|
||||
lat_delay = sm["liveDelay"].lateralDelay + LAT_SMOOTH_SECONDS
|
||||
if sm.updated["liveCalibration"] and sm.seen['roadCameraState'] and sm.seen['deviceState']:
|
||||
device_from_calib_euler = np.array(sm["liveCalibration"].rpyCalib, dtype=np.float32)
|
||||
dc = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))]
|
||||
model_transform_main = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics if main_wide_camera else dc.fcam.intrinsics, False).astype(np.float32)
|
||||
model_transform_extra = get_warp_matrix(device_from_calib_euler, dc.ecam.intrinsics, True).astype(np.float32)
|
||||
live_calib_seen = True
|
||||
|
||||
traffic_convention = np.zeros(2)
|
||||
traffic_convention[int(is_rhd)] = 1
|
||||
|
||||
vec_desire = np.zeros(ModelConstants.DESIRE_LEN, dtype=np.float32)
|
||||
if desire >= 0 and desire < ModelConstants.DESIRE_LEN:
|
||||
vec_desire[desire] = 1
|
||||
|
||||
# tracked dropped frames
|
||||
vipc_dropped_frames = max(0, meta_main.frame_id - last_vipc_frame_id - 1)
|
||||
frames_dropped = frame_dropped_filter.update(min(vipc_dropped_frames, 10))
|
||||
if run_count < 10: # let frame drops warm up
|
||||
frame_dropped_filter.x = 0.
|
||||
frames_dropped = 0.
|
||||
run_count = run_count + 1
|
||||
|
||||
frame_drop_ratio = frames_dropped / (1 + frames_dropped)
|
||||
prepare_only = vipc_dropped_frames > 0
|
||||
if prepare_only:
|
||||
cloudlog.error(f"skipping model eval. Dropped {vipc_dropped_frames} frames")
|
||||
|
||||
bufs = {name: buf_extra if 'big' in name else buf_main for name in model.vision_input_names}
|
||||
transforms = {name: model_transform_extra if 'big' in name else model_transform_main for name in model.vision_input_names}
|
||||
inputs:dict[str, np.ndarray] = {
|
||||
'desire_pulse': vec_desire,
|
||||
'traffic_convention': traffic_convention,
|
||||
}
|
||||
|
||||
mt1 = time.perf_counter()
|
||||
model_output = model.run(bufs, transforms, inputs, prepare_only)
|
||||
mt2 = time.perf_counter()
|
||||
model_execution_time = mt2 - mt1
|
||||
|
||||
if model_output is not None:
|
||||
modelv2_send = messaging.new_message('modelV2')
|
||||
drivingdata_send = messaging.new_message('drivingModelData')
|
||||
posenet_send = messaging.new_message('cameraOdometry')
|
||||
|
||||
action = get_action_from_model(model_output, prev_action, lat_delay + DT_MDL, long_delay + DT_MDL, v_ego)
|
||||
prev_action = action
|
||||
fill_model_msg(drivingdata_send, modelv2_send, model_output, action,
|
||||
publish_state, meta_main.frame_id, meta_extra.frame_id, frame_id,
|
||||
frame_drop_ratio, meta_main.timestamp_eof, model_execution_time, live_calib_seen)
|
||||
|
||||
desire_state = modelv2_send.modelV2.meta.desireState
|
||||
l_lane_change_prob = desire_state[log.Desire.laneChangeLeft]
|
||||
r_lane_change_prob = desire_state[log.Desire.laneChangeRight]
|
||||
lane_change_prob = l_lane_change_prob + r_lane_change_prob
|
||||
DH.update(sm['carState'], sm['carControl'].latActive, lane_change_prob)
|
||||
modelv2_send.modelV2.meta.laneChangeState = DH.lane_change_state
|
||||
modelv2_send.modelV2.meta.laneChangeDirection = DH.lane_change_direction
|
||||
drivingdata_send.drivingModelData.meta.laneChangeState = DH.lane_change_state
|
||||
drivingdata_send.drivingModelData.meta.laneChangeDirection = DH.lane_change_direction
|
||||
|
||||
fill_pose_msg(posenet_send, model_output, meta_main.frame_id, vipc_dropped_frames, meta_main.timestamp_eof, live_calib_seen)
|
||||
pm.send('modelV2', modelv2_send)
|
||||
pm.send('drivingModelData', drivingdata_send)
|
||||
pm.send('cameraOdometry', posenet_send)
|
||||
last_vipc_frame_id = meta_main.frame_id
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--demo', action='store_true', help='A boolean for demo mode.')
|
||||
args = parser.parse_args()
|
||||
main(demo=args.demo)
|
||||
except KeyboardInterrupt:
|
||||
cloudlog.warning("got SIGINT")
|
||||
@@ -0,0 +1,66 @@
|
||||
## Neural networks in openpilot
|
||||
To view the architecture of the ONNX networks, you can use [netron](https://netron.app/)
|
||||
|
||||
## Driving Model (vision model + temporal policy model)
|
||||
### Vision inputs (Full size: 799906 x float32)
|
||||
* **image stream**
|
||||
* Two consecutive images (256 * 512 * 3 in RGB) recorded at 20 Hz : 393216 = 2 * 6 * 128 * 256
|
||||
* Each 256 * 512 image is represented in YUV420 with 6 channels : 6 * 128 * 256
|
||||
* Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2]
|
||||
* Channel 4 represents the half-res U channel
|
||||
* Channel 5 represents the half-res V channel
|
||||
* **wide image stream**
|
||||
* Two consecutive images (256 * 512 * 3 in RGB) recorded at 20 Hz : 393216 = 2 * 6 * 128 * 256
|
||||
* Each 256 * 512 image is represented in YUV420 with 6 channels : 6 * 128 * 256
|
||||
* Channels 0,1,2,3 represent the full-res Y channel and are represented in numpy as Y[::2, ::2], Y[::2, 1::2], Y[1::2, ::2], and Y[1::2, 1::2]
|
||||
* Channel 4 represents the half-res U channel
|
||||
* Channel 5 represents the half-res V channel
|
||||
### Policy inputs
|
||||
* **desire**
|
||||
* one-hot encoded buffer to command model to execute certain actions, bit needs to be sent for the past 5 seconds (at 20FPS) : 100 * 8
|
||||
* **traffic convention**
|
||||
* one-hot encoded vector to tell model whether traffic is right-hand or left-hand traffic : 2
|
||||
* **lateral control params**
|
||||
* speed and steering delay for predicting the desired curvature: 2
|
||||
* **previous desired curvatures**
|
||||
* vector of previously predicted desired curvatures: 100 * 1
|
||||
* **feature buffer**
|
||||
* a buffer of intermediate features including the current feature to form a 5 seconds temporal context (at 20FPS) : 100 * 512
|
||||
|
||||
|
||||
### Driving Model output format (Full size: XXX x float32)
|
||||
Refer to **slice_outputs** and **parse_vision_outputs/parse_policy_outputs** in modeld.
|
||||
|
||||
|
||||
## Driver Monitoring Model
|
||||
* .onnx model can be run with onnx runtimes
|
||||
* .dlc file is a pre-quantized model and only runs on qualcomm DSPs
|
||||
|
||||
### input format
|
||||
* single image W = 1440 H = 960 luminance channel (Y) from the planar YUV420 format:
|
||||
* full input size is 1440 * 960 = 1382400
|
||||
* normalized ranging from 0.0 to 1.0 in float32 (onnx runner) or ranging from 0 to 255 in uint8 (snpe runner)
|
||||
* camera calibration angles (roll, pitch, yaw) from liveCalibration: 3 x float32 inputs
|
||||
|
||||
### output format
|
||||
* 84 x float32 outputs = 2 + 41 * 2 ([parsing example](https://github.com/commaai/openpilot/blob/22ce4e17ba0d3bfcf37f8255a4dd1dc683fe0c38/selfdrive/modeld/models/dmonitoring.cc#L33))
|
||||
* for each person in the front seats (2 * 41)
|
||||
* face pose: 12 = 6 + 6
|
||||
* face orientation [pitch, yaw, roll] in camera frame: 3
|
||||
* face position [dx, dy] relative to image center: 2
|
||||
* normalized face size: 1
|
||||
* standard deviations for above outputs: 6
|
||||
* face visible probability: 1
|
||||
* eyes: 20 = (8 + 1) + (8 + 1) + 1 + 1
|
||||
* eye position and size, and their standard deviations: 8
|
||||
* eye visible probability: 1
|
||||
* eye closed probability: 1
|
||||
* wearing sunglasses probability: 1
|
||||
* face occluded probability: 1
|
||||
* touching wheel probability: 1
|
||||
* paying attention probability: 1
|
||||
* (deprecated) distracted probabilities: 2
|
||||
* using phone probability: 1
|
||||
* distracted probability: 1
|
||||
* common outputs 1
|
||||
* left hand drive probability: 1
|
||||
@@ -0,0 +1,124 @@
|
||||
import numpy as np
|
||||
from openpilot.selfdrive.modeld.constants import ModelConstants
|
||||
|
||||
def safe_exp(x, out=None):
|
||||
# -11 is around 10**14, more causes float16 overflow
|
||||
return np.exp(np.clip(x, -np.inf, 11), out=out)
|
||||
|
||||
def sigmoid(x):
|
||||
return 1. / (1. + safe_exp(-x))
|
||||
|
||||
def softmax(x, axis=-1):
|
||||
x -= np.max(x, axis=axis, keepdims=True)
|
||||
if x.dtype == np.float32 or x.dtype == np.float64:
|
||||
safe_exp(x, out=x)
|
||||
else:
|
||||
x = safe_exp(x)
|
||||
x /= np.sum(x, axis=axis, keepdims=True)
|
||||
return x
|
||||
|
||||
class Parser:
|
||||
def __init__(self, ignore_missing=False):
|
||||
self.ignore_missing = ignore_missing
|
||||
|
||||
def check_missing(self, outs, name):
|
||||
missing = name not in outs
|
||||
if missing and not self.ignore_missing:
|
||||
raise ValueError(f"Missing output {name}")
|
||||
return missing
|
||||
|
||||
def parse_categorical_crossentropy(self, name, outs, out_shape=None):
|
||||
if self.check_missing(outs, name):
|
||||
return
|
||||
raw = outs[name]
|
||||
if out_shape is not None:
|
||||
raw = raw.reshape((raw.shape[0],) + out_shape)
|
||||
outs[name] = softmax(raw, axis=-1)
|
||||
|
||||
def parse_binary_crossentropy(self, name, outs):
|
||||
if self.check_missing(outs, name):
|
||||
return
|
||||
raw = outs[name]
|
||||
outs[name] = sigmoid(raw)
|
||||
|
||||
def parse_mdn(self, name, outs, in_N=0, out_N=1, out_shape=None):
|
||||
if self.check_missing(outs, name):
|
||||
return
|
||||
raw = outs[name]
|
||||
raw = raw.reshape((raw.shape[0], max(in_N, 1), -1))
|
||||
|
||||
n_values = (raw.shape[2] - out_N)//2
|
||||
pred_mu = raw[:,:,:n_values]
|
||||
pred_std = safe_exp(raw[:,:,n_values: 2*n_values])
|
||||
|
||||
if in_N > 1:
|
||||
weights = np.zeros((raw.shape[0], in_N, out_N), dtype=raw.dtype)
|
||||
for i in range(out_N):
|
||||
weights[:,:,i - out_N] = softmax(raw[:,:,i - out_N], axis=-1)
|
||||
|
||||
if out_N == 1:
|
||||
for fidx in range(weights.shape[0]):
|
||||
idxs = np.argsort(weights[fidx][:,0])[::-1]
|
||||
weights[fidx] = weights[fidx][idxs]
|
||||
pred_mu[fidx] = pred_mu[fidx][idxs]
|
||||
pred_std[fidx] = pred_std[fidx][idxs]
|
||||
full_shape = tuple([raw.shape[0], in_N] + list(out_shape))
|
||||
outs[name + '_weights'] = weights
|
||||
outs[name + '_hypotheses'] = pred_mu.reshape(full_shape)
|
||||
outs[name + '_stds_hypotheses'] = pred_std.reshape(full_shape)
|
||||
|
||||
pred_mu_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype)
|
||||
pred_std_final = np.zeros((raw.shape[0], out_N, n_values), dtype=raw.dtype)
|
||||
for fidx in range(weights.shape[0]):
|
||||
for hidx in range(out_N):
|
||||
idxs = np.argsort(weights[fidx,:,hidx])[::-1]
|
||||
pred_mu_final[fidx, hidx] = pred_mu[fidx, idxs[0]]
|
||||
pred_std_final[fidx, hidx] = pred_std[fidx, idxs[0]]
|
||||
else:
|
||||
pred_mu_final = pred_mu
|
||||
pred_std_final = pred_std
|
||||
|
||||
if out_N > 1:
|
||||
final_shape = tuple([raw.shape[0], out_N] + list(out_shape))
|
||||
else:
|
||||
final_shape = tuple([raw.shape[0],] + list(out_shape))
|
||||
outs[name] = pred_mu_final.reshape(final_shape)
|
||||
outs[name + '_stds'] = pred_std_final.reshape(final_shape)
|
||||
|
||||
def is_mhp(self, outs, name, shape):
|
||||
if self.check_missing(outs, name):
|
||||
return False
|
||||
if outs[name].shape[1] == 2 * shape:
|
||||
return False
|
||||
return True
|
||||
|
||||
def parse_vision_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
|
||||
self.parse_mdn('pose', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,))
|
||||
self.parse_mdn('wide_from_device_euler', outs, in_N=0, out_N=0, out_shape=(ModelConstants.WIDE_FROM_DEVICE_WIDTH,))
|
||||
self.parse_mdn('road_transform', outs, in_N=0, out_N=0, out_shape=(ModelConstants.POSE_WIDTH,))
|
||||
self.parse_mdn('lane_lines', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_LANE_LINES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH))
|
||||
self.parse_mdn('road_edges', outs, in_N=0, out_N=0, out_shape=(ModelConstants.NUM_ROAD_EDGES,ModelConstants.IDX_N,ModelConstants.LANE_LINES_WIDTH))
|
||||
self.parse_binary_crossentropy('lane_lines_prob', outs)
|
||||
self.parse_categorical_crossentropy('desire_pred', outs, out_shape=(ModelConstants.DESIRE_PRED_LEN,ModelConstants.DESIRE_PRED_WIDTH))
|
||||
self.parse_binary_crossentropy('meta', outs)
|
||||
self.parse_binary_crossentropy('lead_prob', outs)
|
||||
lead_mhp = self.is_mhp(outs, 'lead', ModelConstants.LEAD_MHP_SELECTION * ModelConstants.LEAD_TRAJ_LEN * ModelConstants.LEAD_WIDTH)
|
||||
lead_in_N, lead_out_N = (ModelConstants.LEAD_MHP_N, ModelConstants.LEAD_MHP_SELECTION) if lead_mhp else (0, 0)
|
||||
lead_out_shape = (ModelConstants.LEAD_TRAJ_LEN, ModelConstants.LEAD_WIDTH) if lead_mhp else \
|
||||
(ModelConstants.LEAD_MHP_SELECTION, ModelConstants.LEAD_TRAJ_LEN, ModelConstants.LEAD_WIDTH)
|
||||
self.parse_mdn('lead', outs, in_N=lead_in_N, out_N=lead_out_N, out_shape=lead_out_shape)
|
||||
return outs
|
||||
|
||||
def parse_policy_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
|
||||
plan_mhp = self.is_mhp(outs, 'plan', ModelConstants.IDX_N * ModelConstants.PLAN_WIDTH)
|
||||
plan_in_N, plan_out_N = (ModelConstants.PLAN_MHP_N, ModelConstants.PLAN_MHP_SELECTION) if plan_mhp else (0, 0)
|
||||
self.parse_mdn('plan', outs, in_N=plan_in_N, out_N=plan_out_N, out_shape=(ModelConstants.IDX_N, ModelConstants.PLAN_WIDTH))
|
||||
if 'planplus' in outs:
|
||||
self.parse_mdn('planplus', outs, in_N=0, out_N=0, out_shape=(ModelConstants.IDX_N, ModelConstants.PLAN_WIDTH))
|
||||
self.parse_categorical_crossentropy('desire_state', outs, out_shape=(ModelConstants.DESIRE_PRED_WIDTH,))
|
||||
return outs
|
||||
|
||||
def parse_outputs(self, outs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
|
||||
outs = self.parse_vision_outputs(outs)
|
||||
outs = self.parse_policy_outputs(outs)
|
||||
return outs
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,43 @@
|
||||
0: \x80 PROTO 4
|
||||
2: \x95 FRAME 90
|
||||
11: } EMPTY_DICT
|
||||
12: \x94 MEMOIZE (as 0)
|
||||
13: ( MARK
|
||||
14: \x8c SHORT_BINUNICODE 'plan'
|
||||
20: \x94 MEMOIZE (as 1)
|
||||
21: \x8c SHORT_BINUNICODE 'builtins'
|
||||
31: \x94 MEMOIZE (as 2)
|
||||
32: \x8c SHORT_BINUNICODE 'slice'
|
||||
39: \x94 MEMOIZE (as 3)
|
||||
40: \x93 STACK_GLOBAL
|
||||
41: \x94 MEMOIZE (as 4)
|
||||
42: K BININT1 0
|
||||
44: M BININT2 990
|
||||
47: N NONE
|
||||
48: \x87 TUPLE3
|
||||
49: \x94 MEMOIZE (as 5)
|
||||
50: R REDUCE
|
||||
51: \x94 MEMOIZE (as 6)
|
||||
52: \x8c SHORT_BINUNICODE 'desire_state'
|
||||
66: \x94 MEMOIZE (as 7)
|
||||
67: h BINGET 4
|
||||
69: M BININT2 990
|
||||
72: M BININT2 998
|
||||
75: N NONE
|
||||
76: \x87 TUPLE3
|
||||
77: \x94 MEMOIZE (as 8)
|
||||
78: R REDUCE
|
||||
79: \x94 MEMOIZE (as 9)
|
||||
80: \x8c SHORT_BINUNICODE 'pad'
|
||||
85: \x94 MEMOIZE (as 10)
|
||||
86: h BINGET 4
|
||||
88: J BININT -2
|
||||
93: N NONE
|
||||
94: N NONE
|
||||
95: \x87 TUPLE3
|
||||
96: \x94 MEMOIZE (as 11)
|
||||
97: R REDUCE
|
||||
98: \x94 MEMOIZE (as 12)
|
||||
99: u SETITEMS (MARK at 13)
|
||||
100: . STOP
|
||||
highest protocol among opcodes = 4
|
||||
@@ -0,0 +1,133 @@
|
||||
0: \x80 PROTO 4
|
||||
2: \x95 FRAME 320
|
||||
11: } EMPTY_DICT
|
||||
12: \x94 MEMOIZE (as 0)
|
||||
13: ( MARK
|
||||
14: \x8c SHORT_BINUNICODE 'meta'
|
||||
20: \x94 MEMOIZE (as 1)
|
||||
21: \x8c SHORT_BINUNICODE 'builtins'
|
||||
31: \x94 MEMOIZE (as 2)
|
||||
32: \x8c SHORT_BINUNICODE 'slice'
|
||||
39: \x94 MEMOIZE (as 3)
|
||||
40: \x93 STACK_GLOBAL
|
||||
41: \x94 MEMOIZE (as 4)
|
||||
42: K BININT1 0
|
||||
44: K BININT1 55
|
||||
46: N NONE
|
||||
47: \x87 TUPLE3
|
||||
48: \x94 MEMOIZE (as 5)
|
||||
49: R REDUCE
|
||||
50: \x94 MEMOIZE (as 6)
|
||||
51: \x8c SHORT_BINUNICODE 'desire_pred'
|
||||
64: \x94 MEMOIZE (as 7)
|
||||
65: h BINGET 4
|
||||
67: K BININT1 55
|
||||
69: K BININT1 87
|
||||
71: N NONE
|
||||
72: \x87 TUPLE3
|
||||
73: \x94 MEMOIZE (as 8)
|
||||
74: R REDUCE
|
||||
75: \x94 MEMOIZE (as 9)
|
||||
76: \x8c SHORT_BINUNICODE 'pose'
|
||||
82: \x94 MEMOIZE (as 10)
|
||||
83: h BINGET 4
|
||||
85: K BININT1 87
|
||||
87: K BININT1 99
|
||||
89: N NONE
|
||||
90: \x87 TUPLE3
|
||||
91: \x94 MEMOIZE (as 11)
|
||||
92: R REDUCE
|
||||
93: \x94 MEMOIZE (as 12)
|
||||
94: \x8c SHORT_BINUNICODE 'wide_from_device_euler'
|
||||
118: \x94 MEMOIZE (as 13)
|
||||
119: h BINGET 4
|
||||
121: K BININT1 99
|
||||
123: K BININT1 105
|
||||
125: N NONE
|
||||
126: \x87 TUPLE3
|
||||
127: \x94 MEMOIZE (as 14)
|
||||
128: R REDUCE
|
||||
129: \x94 MEMOIZE (as 15)
|
||||
130: \x8c SHORT_BINUNICODE 'road_transform'
|
||||
146: \x94 MEMOIZE (as 16)
|
||||
147: h BINGET 4
|
||||
149: K BININT1 105
|
||||
151: K BININT1 117
|
||||
153: N NONE
|
||||
154: \x87 TUPLE3
|
||||
155: \x94 MEMOIZE (as 17)
|
||||
156: R REDUCE
|
||||
157: \x94 MEMOIZE (as 18)
|
||||
158: \x8c SHORT_BINUNICODE 'lane_lines'
|
||||
170: \x94 MEMOIZE (as 19)
|
||||
171: h BINGET 4
|
||||
173: K BININT1 117
|
||||
175: M BININT2 645
|
||||
178: N NONE
|
||||
179: \x87 TUPLE3
|
||||
180: \x94 MEMOIZE (as 20)
|
||||
181: R REDUCE
|
||||
182: \x94 MEMOIZE (as 21)
|
||||
183: \x8c SHORT_BINUNICODE 'lane_lines_prob'
|
||||
200: \x94 MEMOIZE (as 22)
|
||||
201: h BINGET 4
|
||||
203: M BININT2 645
|
||||
206: M BININT2 653
|
||||
209: N NONE
|
||||
210: \x87 TUPLE3
|
||||
211: \x94 MEMOIZE (as 23)
|
||||
212: R REDUCE
|
||||
213: \x94 MEMOIZE (as 24)
|
||||
214: \x8c SHORT_BINUNICODE 'road_edges'
|
||||
226: \x94 MEMOIZE (as 25)
|
||||
227: h BINGET 4
|
||||
229: M BININT2 653
|
||||
232: M BININT2 917
|
||||
235: N NONE
|
||||
236: \x87 TUPLE3
|
||||
237: \x94 MEMOIZE (as 26)
|
||||
238: R REDUCE
|
||||
239: \x94 MEMOIZE (as 27)
|
||||
240: \x8c SHORT_BINUNICODE 'lead'
|
||||
246: \x94 MEMOIZE (as 28)
|
||||
247: h BINGET 4
|
||||
249: M BININT2 917
|
||||
252: M BININT2 1061
|
||||
255: N NONE
|
||||
256: \x87 TUPLE3
|
||||
257: \x94 MEMOIZE (as 29)
|
||||
258: R REDUCE
|
||||
259: \x94 MEMOIZE (as 30)
|
||||
260: \x8c SHORT_BINUNICODE 'lead_prob'
|
||||
271: \x94 MEMOIZE (as 31)
|
||||
272: h BINGET 4
|
||||
274: M BININT2 1061
|
||||
277: M BININT2 1064
|
||||
280: N NONE
|
||||
281: \x87 TUPLE3
|
||||
282: \x94 MEMOIZE (as 32)
|
||||
283: R REDUCE
|
||||
284: \x94 MEMOIZE (as 33)
|
||||
285: \x8c SHORT_BINUNICODE 'hidden_state'
|
||||
299: \x94 MEMOIZE (as 34)
|
||||
300: h BINGET 4
|
||||
302: M BININT2 1064
|
||||
305: M BININT2 1576
|
||||
308: N NONE
|
||||
309: \x87 TUPLE3
|
||||
310: \x94 MEMOIZE (as 35)
|
||||
311: R REDUCE
|
||||
312: \x94 MEMOIZE (as 36)
|
||||
313: \x8c SHORT_BINUNICODE 'pad'
|
||||
318: \x94 MEMOIZE (as 37)
|
||||
319: h BINGET 4
|
||||
321: K BININT1 0
|
||||
323: N NONE
|
||||
324: N NONE
|
||||
325: \x87 TUPLE3
|
||||
326: \x94 MEMOIZE (as 38)
|
||||
327: R REDUCE
|
||||
328: \x94 MEMOIZE (as 39)
|
||||
329: u SETITEMS (MARK at 13)
|
||||
330: . STOP
|
||||
highest protocol among opcodes = 4
|
||||
@@ -0,0 +1,63 @@
|
||||
# Model Selector Version Compatibility
|
||||
|
||||
This document explains the version compatibility mechanism used by the Model Selector system, and the rationale behind certain version constraints and JSON file management strategies.
|
||||
|
||||
## Overview
|
||||
|
||||
The Model Selector is responsible for selecting and validating model bundles based on their metadata and version constraints. Each model bundle is distributed via a JSON file and includes a `minimumSelectorVersion` field indicating the minimum selector version required to load it.
|
||||
|
||||
To ensure robust compatibility and prevent mismatches between model expectations and selector capabilities, the selector enforces two version boundaries:
|
||||
|
||||
* **`REQUIRED_MIN_SELECTOR_VERSION`**: the oldest selector version we support.
|
||||
* **`CURRENT_SELECTOR_VERSION`**: the current version of the selector logic.
|
||||
|
||||
## Version Compatibility Check
|
||||
|
||||
A model bundle is considered compatible if:
|
||||
|
||||
```python
|
||||
REQUIRED_MIN_SELECTOR_VERSION <= bundle["minimumSelectorVersion"] <= CURRENT_SELECTOR_VERSION
|
||||
```
|
||||
|
||||
This ensures:
|
||||
|
||||
* **Old bundles are rejected** if they rely on deprecated selector behavior.
|
||||
* **Future bundles are ignored** if they expect logic that the current selector doesn't yet implement.
|
||||
|
||||
## Handling Breaking Changes
|
||||
|
||||
When a deep change in selector behavior requires *all* models to be recompiled (e.g., due to a major architectural update), we:
|
||||
|
||||
1. **Create a new JSON file** (e.g., from `models_v4.json` to `models_v5.json`).
|
||||
2. **Assign updated `minimumSelectorVersion` values** in the new bundles.
|
||||
|
||||
This allows older selector versions to continue using the previous JSON file, while newer versions point to the new one, preventing cross-contamination.
|
||||
|
||||
## Why `REQUIRED_MIN_SELECTOR_VERSION` Still Matters
|
||||
|
||||
Despite using new JSON files to isolate breaking changes, `REQUIRED_MIN_SELECTOR_VERSION` plays a critical role:
|
||||
|
||||
### 1. **Cached Bundle Validation**
|
||||
|
||||
Model bundles are cached locally (e.g., in-memory or on disk). A user might have previously loaded a now-invalid bundle from an older JSON file.
|
||||
|
||||
`REQUIRED_MIN_SELECTOR_VERSION` prevents the selector from reloading or trusting that stale cached bundle, even if the original JSON is gone.
|
||||
|
||||
### 2. **Explicit Deprecation Boundary**
|
||||
|
||||
By raising `REQUIRED_MIN_SELECTOR_VERSION`, we declare older bundles officially unsupported, even if they technically still exist in a legacy JSON file.
|
||||
|
||||
### 3. **Avoiding Race Conditions**
|
||||
|
||||
Some clients may have intermittent access to updated JSONs. The runtime check ensures version compatibility is enforced independently of external file state.
|
||||
|
||||
## Summary
|
||||
|
||||
| Component | Purpose |
|
||||
| ------------------------------- | --------------------------------------------------------------------- |
|
||||
| `minimumSelectorVersion` | Declares the minimum selector version required to load a model bundle |
|
||||
| `REQUIRED_MIN_SELECTOR_VERSION` | Prevents loading bundles that are too old (e.g., from stale cache) |
|
||||
| `CURRENT_SELECTOR_VERSION` | Prevents loading bundles that are too new or forward-incompatible |
|
||||
| JSON file renaming | Isolates bundles by selector generation to handle full recompiles |
|
||||
|
||||
This layered strategy ensures safe evolution of the model selection system while maintaining backward compatibility and runtime protection against stale or incompatible bundles.
|
||||
@@ -0,0 +1,274 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
|
||||
import time
|
||||
import os
|
||||
import requests
|
||||
from requests.exceptions import (SSLError, RequestException, HTTPError)
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.common.hardware.hw import Paths
|
||||
from openpilot.sunnypilot.models.helpers import is_bundle_version_compatible
|
||||
from openpilot.cereal import custom
|
||||
|
||||
|
||||
class ModelParser:
|
||||
"""Handles parsing of model data into cereal objects"""
|
||||
|
||||
@staticmethod
|
||||
def _parse_download_uri(download_uri_data) -> custom.ModelManagerSP.DownloadUri:
|
||||
download_uri = custom.ModelManagerSP.DownloadUri()
|
||||
download_uri.uri = download_uri_data.get("url")
|
||||
download_uri.sha256 = download_uri_data.get("sha256")
|
||||
return download_uri
|
||||
|
||||
@staticmethod
|
||||
def _parse_chunk(chunk_data) -> custom.ModelManagerSP.Chunk:
|
||||
chunk = custom.ModelManagerSP.Chunk()
|
||||
chunk.fileName = chunk_data.get("file_name")
|
||||
chunk.sha256 = chunk_data.get("sha256")
|
||||
return chunk
|
||||
|
||||
@staticmethod
|
||||
def _parse_artifact(artifact_data) -> custom.ModelManagerSP.Artifact:
|
||||
artifact = custom.ModelManagerSP.Artifact()
|
||||
artifact.fileName = artifact_data.get("file_name")
|
||||
artifact.downloadUri = ModelParser._parse_download_uri(artifact_data.get("download_uri", {}))
|
||||
|
||||
if "chunks" in artifact_data:
|
||||
artifact.chunks = [ModelParser._parse_chunk(chunk_data) for chunk_data in artifact_data["chunks"]]
|
||||
|
||||
try:
|
||||
model_dir = Paths.model_root()
|
||||
os.makedirs(model_dir, exist_ok=True)
|
||||
manifest_path = os.path.join(model_dir, f"{artifact.fileName}.chunkmanifest")
|
||||
num_chunks = str(len(artifact.chunks))
|
||||
|
||||
if not os.path.exists(manifest_path) or open(manifest_path).read().strip() != num_chunks:
|
||||
with open(manifest_path, "w") as f:
|
||||
f.write(num_chunks)
|
||||
cloudlog.info(f"Wrote chunk manifest for {artifact.fileName}: {num_chunks} chunks")
|
||||
except Exception as e:
|
||||
cloudlog.warning(f"Failed to write chunk manifest for {artifact.fileName}: {e}")
|
||||
|
||||
return artifact
|
||||
|
||||
@staticmethod
|
||||
def _parse_model(model_data) -> custom.ModelManagerSP.Model:
|
||||
model = custom.ModelManagerSP.Model()
|
||||
|
||||
model.type = model_data.get("type")
|
||||
model.artifact = ModelParser._parse_artifact(model_data.get("artifact", {}))
|
||||
return model
|
||||
|
||||
@staticmethod
|
||||
def _parse_overrides(overrides_data: dict[str, str]) -> list[custom.ModelManagerSP.Override]:
|
||||
overrides = []
|
||||
for key, value in overrides_data.items():
|
||||
override = custom.ModelManagerSP.Override()
|
||||
override.key = key
|
||||
override.value = value
|
||||
overrides.append(override)
|
||||
return overrides
|
||||
|
||||
@staticmethod
|
||||
def _parse_bundle(bundle) -> custom.ModelManagerSP.ModelBundle:
|
||||
model_bundle = custom.ModelManagerSP.ModelBundle()
|
||||
model_bundle.index = int(bundle["index"])
|
||||
model_bundle.internalName = bundle["short_name"]
|
||||
model_bundle.displayName = bundle["display_name"]
|
||||
model_bundle.models = [ModelParser._parse_model(model) for model in bundle.get("models",[])]
|
||||
model_bundle.status = 0
|
||||
model_bundle.generation = int(bundle["generation"])
|
||||
model_bundle.environment = bundle["environment"]
|
||||
model_bundle.runner = bundle.get("runner", custom.ModelManagerSP.Runner.snpe)
|
||||
model_bundle.is20hz = bundle.get("is_20hz", False)
|
||||
model_bundle.minimumSelectorVersion = int(bundle["minimum_selector_version"])
|
||||
model_bundle.overrides = ModelParser._parse_overrides(bundle.get("overrides", {}))
|
||||
model_bundle.ref = bundle.get("ref")
|
||||
|
||||
return model_bundle
|
||||
|
||||
@staticmethod
|
||||
def parse_models(json_data: dict) -> list[custom.ModelManagerSP.ModelBundle]:
|
||||
found_bundles = [ModelParser._parse_bundle(bundle) for bundle in json_data.get("bundles", [])]
|
||||
return [bundle for bundle in found_bundles if is_bundle_version_compatible(bundle.to_dict())]
|
||||
|
||||
|
||||
class ModelCache:
|
||||
"""Handles caching of model data to avoid frequent remote fetches"""
|
||||
|
||||
def __init__(self, params: Params, cache_timeout: int = int(3600 * 1e9), suffix: str = ""):
|
||||
self.params = params
|
||||
self.cache_timeout = cache_timeout
|
||||
self._LAST_SYNC_KEY = f"ModelManager_LastSyncTime{suffix}"
|
||||
self._CACHE_KEY = f"ModelManager_ModelsCache{suffix}"
|
||||
|
||||
def _is_expired(self) -> bool:
|
||||
"""Checks if the cache has expired"""
|
||||
current_time = int(time.monotonic() * 1e9)
|
||||
last_sync = self.params.get(self._LAST_SYNC_KEY) or 0
|
||||
return bool(last_sync == 0) or (current_time - last_sync) >= self.cache_timeout
|
||||
|
||||
def get(self) -> tuple[dict, bool]:
|
||||
"""
|
||||
Retrieves cached model data and expiration status atomically.
|
||||
Returns: Tuple of (cached_data, is_expired)
|
||||
If no cached data exists or on error, returns an empty dict
|
||||
"""
|
||||
try:
|
||||
cached_data = self.params.get(self._CACHE_KEY)
|
||||
if not cached_data:
|
||||
cloudlog.warning("No cached model data available")
|
||||
return {}, True
|
||||
return cached_data, self._is_expired()
|
||||
except Exception as e:
|
||||
cloudlog.exception(f"Error retrieving cached model data: {str(e)}")
|
||||
return {}, True
|
||||
|
||||
def set(self, data: dict) -> None:
|
||||
"""Updates the cache with new model data"""
|
||||
self.params.put(self._CACHE_KEY, data, block=True)
|
||||
self.params.put(self._LAST_SYNC_KEY, int(time.monotonic() * 1e9), block=True)
|
||||
|
||||
|
||||
class ModelFetcher:
|
||||
"""Handles fetching and caching of model data from remote source"""
|
||||
MODEL_URL = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_v22.json"
|
||||
MODEL_URL_CHESTNUT = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_chestnut_v25.json"
|
||||
|
||||
MODEL_SOURCES = {
|
||||
"qcom": (MODEL_URL, ""),
|
||||
"chestnut": (MODEL_URL_CHESTNUT, "_Chestnut"),
|
||||
}
|
||||
|
||||
def __init__(self, params: Params):
|
||||
self.params = params
|
||||
self.model_parser = ModelParser()
|
||||
self.model_caches = {
|
||||
source: ModelCache(params, suffix=suffix)
|
||||
for source, (_, suffix) in self.MODEL_SOURCES.items()
|
||||
}
|
||||
self._refetched: set[str] = set()
|
||||
self.params.put("ModelManager_ActiveJson", {
|
||||
"qcom": self.MODEL_URL,
|
||||
"chestnut": self.MODEL_URL_CHESTNUT,
|
||||
}, block=True)
|
||||
|
||||
@staticmethod
|
||||
def active_source(chestnut_present: bool) -> str:
|
||||
return "chestnut" if chestnut_present else "qcom"
|
||||
|
||||
def _fetch_and_cache_models(self, source: str) -> list[custom.ModelManagerSP.ModelBundle] | None:
|
||||
"""Fetches fresh model data from remote and updates cache.
|
||||
Returns None on transport errors. Raises on 404 and other fatal HTTP errors.
|
||||
"""
|
||||
model_url, _ = self.MODEL_SOURCES[source]
|
||||
try:
|
||||
response = requests.get(model_url, timeout=10)
|
||||
|
||||
# Explicitly handle 404 differently
|
||||
if response.status_code == 404:
|
||||
cloudlog.error(f"Models URL returned 404 Not Found: {model_url}")
|
||||
raise HTTPError(f"404 Not Found: {model_url}", response=response)
|
||||
|
||||
# Raise for any other 4xx/5xx
|
||||
response.raise_for_status()
|
||||
|
||||
json_data = response.json()
|
||||
parsed = self.model_parser.parse_models(json_data)
|
||||
if parsed:
|
||||
self.model_caches[source].set(json_data)
|
||||
cloudlog.debug(f"Successfully updated models cache for {source}")
|
||||
return parsed
|
||||
|
||||
except ConnectionError as e:
|
||||
cloudlog.warning(f"DNS/connection error while fetching models: {e}")
|
||||
except SSLError as e:
|
||||
cloudlog.warning(f"SSL error while fetching models: {e}")
|
||||
except RequestException as e:
|
||||
cloudlog.warning(f"Request transport error while fetching models: {e}")
|
||||
except Exception as e:
|
||||
cloudlog.exception(f"Unexpected error fetching models: {e}")
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _cache_matches_source(source: str, cached_data: dict) -> bool:
|
||||
bundles = cached_data.get("bundles", [])
|
||||
if source == "chestnut":
|
||||
return any(bundle.get("is_big") is True for bundle in bundles)
|
||||
return not any(bundle.get("is_big") is True for bundle in bundles)
|
||||
|
||||
def get_bundles_for_source(self, source: str) -> list[custom.ModelManagerSP.ModelBundle]:
|
||||
if source not in self.MODEL_SOURCES:
|
||||
cloudlog.warning(f"Unknown model source: {source}")
|
||||
return []
|
||||
|
||||
cached_data, is_expired = self.model_caches[source].get()
|
||||
|
||||
if cached_data and not is_expired:
|
||||
# a source is refetched over a mismatch at most once per process: if the fresh
|
||||
# manifest still mismatches, the URL is authoritative and the cache is trusted
|
||||
if self._cache_matches_source(source, cached_data) or source in self._refetched:
|
||||
try:
|
||||
parsed = self.model_parser.parse_models(cached_data)
|
||||
except Exception:
|
||||
cloudlog.warning(f"Failed to parse cached models for {source}; refetching", exc_info=True)
|
||||
else:
|
||||
if parsed:
|
||||
cloudlog.debug(f"Using valid cached models data for source {source}")
|
||||
return parsed
|
||||
# a source-matching cache that yields no valid bundles is stale (e.g. an old
|
||||
# manifest version) - do not trust it, refetch so the source is repopulated
|
||||
cloudlog.warning(f"Cached models for {source} have no valid bundles; refetching")
|
||||
else:
|
||||
self._refetched.add(source)
|
||||
cloudlog.warning(f"Cached models for {source} not valid; refetching once")
|
||||
|
||||
fetched_bundles = self._fetch_and_cache_models(source)
|
||||
if fetched_bundles is not None:
|
||||
return fetched_bundles
|
||||
|
||||
if not cached_data:
|
||||
cloudlog.warning("Failed to fetch fresh data and no cache available")
|
||||
|
||||
cloudlog.warning("Failed to fetch fresh data. Using expired cache as fallback")
|
||||
try:
|
||||
return self.model_parser.parse_models(cached_data)
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def get_cached_bundles(params: Params, source: str) -> list[custom.ModelManagerSP.ModelBundle]:
|
||||
|
||||
if source not in ModelFetcher.MODEL_SOURCES:
|
||||
cloudlog.warning(f"Unknown model source: {source}")
|
||||
return []
|
||||
_, suffix = ModelFetcher.MODEL_SOURCES[source]
|
||||
cached_data = params.get(f"ModelManager_ModelsCache{suffix}")
|
||||
if not cached_data:
|
||||
return []
|
||||
try:
|
||||
return ModelParser.parse_models(cached_data)
|
||||
except Exception as e:
|
||||
cloudlog.warning(f"Failed to parse cached models for source {source}: {e}")
|
||||
return []
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from openpilot.selfdrive.modeld.helpers import chestnut_present
|
||||
params = Params()
|
||||
model_fetcher = ModelFetcher(params)
|
||||
bundles = model_fetcher.get_bundles_for_source(ModelFetcher.active_source(chestnut_present()))
|
||||
for bundle in bundles:
|
||||
for model in bundle.models:
|
||||
model_overrides = {override.key: override.value for override in bundle.overrides}
|
||||
print(f"Bundle: {bundle.internalName}, Type: {model.type}, Status: {bundle.status}, Overrides: {model_overrides}")
|
||||
print(f"Artifact: {model.artifact.fileName}, Download URI: {model.artifact.downloadUri.uri}")
|
||||
if model.artifact.chunks:
|
||||
print(f"Contains {len(model.artifact.chunks)} chunks.")
|
||||
@@ -0,0 +1,221 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import numpy as np
|
||||
|
||||
from openpilot.cereal import custom
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.common.hardware.hw import Paths
|
||||
from openpilot.selfdrive.modeld.helpers import chestnut_present
|
||||
|
||||
# SET ME TO THE EXACT JSON VERSION WE SET IN SUNNYPILOT_MODELS REPO
|
||||
REQUIRED_JSON_VERSION = 19
|
||||
|
||||
CUSTOM_MODEL_PATH = Paths.model_root()
|
||||
ModelManager = custom.ModelManagerSP
|
||||
|
||||
ACTIVE_BUNDLE_KEYS = {
|
||||
"qcom": "ModelManager_ActiveBundle",
|
||||
"chestnut": "ModelManager_ActiveBundleChestnut",
|
||||
}
|
||||
_LAST_VALIDATED_RAW: dict[str, dict | None] = {}
|
||||
|
||||
|
||||
def _compute_hash(file_path: str) -> str | None:
|
||||
from openpilot.common.file_chunker import open_file_chunked
|
||||
try:
|
||||
with open_file_chunked(file_path) as file:
|
||||
return hashlib.file_digest(file, "sha256").hexdigest().lower()
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
|
||||
|
||||
async def verify_file(file_path: str, expected_hash: str) -> bool:
|
||||
file_hash = _compute_hash(file_path)
|
||||
return file_hash == expected_hash.lower() if file_hash else False
|
||||
|
||||
|
||||
def _verify_file(file_path: str, expected_hash: str) -> bool:
|
||||
file_hash = _compute_hash(file_path)
|
||||
return file_hash == expected_hash.lower() if file_hash else False
|
||||
|
||||
|
||||
def is_bundle_version_compatible(bundle: dict) -> bool:
|
||||
"""
|
||||
The bundle parsed from the json specifies a `minimum_selector_version`, which defines the minimum selector version
|
||||
required to load the model. This function ensures that:
|
||||
the bundle MUST match the `REQUIRED_JSON_VERSION` set here in helpers.
|
||||
"""
|
||||
return bundle.get("minimumSelectorVersion", 0) == REQUIRED_JSON_VERSION
|
||||
|
||||
|
||||
def _bundle_artifacts(bundle: custom.ModelManagerSP.ModelBundle) -> list[tuple[str, str]]:
|
||||
artifacts = []
|
||||
from openpilot.common.file_chunker import get_chunk_name
|
||||
for model in getattr(bundle, 'models', []) or []:
|
||||
for artifact in (getattr(model, 'artifact', None),):
|
||||
if artifact and getattr(artifact, 'fileName', None):
|
||||
if len(artifact.chunks) > 0:
|
||||
for i, chunk in enumerate(artifact.chunks):
|
||||
chunk_name = get_chunk_name(artifact.fileName, i, len(artifact.chunks))
|
||||
if getattr(chunk, 'sha256', None):
|
||||
artifacts.append((chunk_name, chunk.sha256))
|
||||
else:
|
||||
if getattr(artifact, 'downloadUri', None):
|
||||
sha256 = getattr(artifact.downloadUri, 'sha256', None)
|
||||
if sha256:
|
||||
artifacts.append((artifact.fileName, sha256))
|
||||
return artifacts
|
||||
|
||||
|
||||
def _bundle_is_valid_locally(bundle: custom.ModelManagerSP.ModelBundle) -> bool:
|
||||
model_root = Paths.model_root()
|
||||
return all(_verify_file(os.path.join(model_root, file_name), expected_hash)
|
||||
for file_name, expected_hash in _bundle_artifacts(bundle))
|
||||
|
||||
|
||||
def _bundle_needs_reset(active_bundle: custom.ModelManagerSP.ModelBundle, available_bundles: list[custom.ModelManagerSP.ModelBundle] | None) -> bool:
|
||||
if active_bundle is None:
|
||||
return False
|
||||
|
||||
if available_bundles is not None:
|
||||
matching_bundle = None
|
||||
for bundle in available_bundles:
|
||||
if active_bundle.ref and bundle.ref:
|
||||
if active_bundle.ref == bundle.ref:
|
||||
matching_bundle = bundle
|
||||
break
|
||||
elif active_bundle.internalName == bundle.internalName:
|
||||
matching_bundle = bundle
|
||||
break
|
||||
|
||||
if matching_bundle is None:
|
||||
return True
|
||||
if active_bundle.minimumSelectorVersion != matching_bundle.minimumSelectorVersion:
|
||||
return True
|
||||
if active_bundle.runner != matching_bundle.runner:
|
||||
return True
|
||||
if set(_bundle_artifacts(active_bundle)) != set(_bundle_artifacts(matching_bundle)):
|
||||
return True
|
||||
|
||||
return not _bundle_is_valid_locally(active_bundle)
|
||||
|
||||
|
||||
def _parse_active_bundle(raw_bundle) -> "custom.ModelManagerSP.ModelBundle | None":
|
||||
try:
|
||||
if isinstance(raw_bundle, dict) and raw_bundle and is_bundle_version_compatible(raw_bundle):
|
||||
return custom.ModelManagerSP.ModelBundle(**raw_bundle)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def get_selected_bundle(params: Params | None = None, source: str = "qcom") -> "custom.ModelManagerSP.ModelBundle | None":
|
||||
params = params or Params()
|
||||
return _parse_active_bundle(params.get(ACTIVE_BUNDLE_KEYS[source]))
|
||||
|
||||
|
||||
def get_active_source(chestnut: bool | None = None, chestnut_active: bool | None = None,
|
||||
chestnut_loading: bool | None = None, offroad: bool | None = None) -> str:
|
||||
if chestnut is None:
|
||||
chestnut = chestnut_present()
|
||||
state_valid = chestnut_active is not None or chestnut_loading is not None or offroad is not None
|
||||
big_active = chestnut and (not state_valid or chestnut_active or chestnut_loading or offroad)
|
||||
return "chestnut" if big_active else "qcom"
|
||||
|
||||
|
||||
def get_active_bundle(params: Params | None = None, *, chestnut: bool | None = None) -> "custom.ModelManagerSP.ModelBundle | None":
|
||||
# no cross-slot fallback: an empty active slot means the hardware default, which
|
||||
# only stock modeld can run - modeld_v2 requires a real bundle
|
||||
params = params or Params()
|
||||
return get_selected_bundle(params, get_active_source(chestnut=chestnut))
|
||||
|
||||
|
||||
def resolve_bundle_by_ref(
|
||||
ref: str, source_bundles: dict[str, list[custom.ModelManagerSP.ModelBundle]],
|
||||
) -> "tuple[custom.ModelManagerSP.ModelBundle, str] | None":
|
||||
for source, bundles in source_bundles.items():
|
||||
for bundle in bundles:
|
||||
if bundle.ref == ref:
|
||||
return bundle, source
|
||||
return None
|
||||
|
||||
|
||||
def _validate_active_bundle(params: Params, source: str, available_bundles: list[custom.ModelManagerSP.ModelBundle] | None = None) -> None:
|
||||
global _LAST_VALIDATED_RAW
|
||||
|
||||
key = ACTIVE_BUNDLE_KEYS[source]
|
||||
raw_bundle = params.get(key)
|
||||
if not raw_bundle:
|
||||
return
|
||||
|
||||
if _LAST_VALIDATED_RAW.get(key) == raw_bundle:
|
||||
return
|
||||
|
||||
active_bundle = _parse_active_bundle(raw_bundle)
|
||||
if active_bundle is None or _bundle_needs_reset(active_bundle, available_bundles):
|
||||
cloudlog.warning(f"Active model bundle invalid for {source}; resetting to default")
|
||||
params.remove(key)
|
||||
_LAST_VALIDATED_RAW[key] = None
|
||||
else:
|
||||
_LAST_VALIDATED_RAW[key] = raw_bundle
|
||||
|
||||
|
||||
def validate_active_bundles(params: Params, source_bundles: dict[str, list[custom.ModelManagerSP.ModelBundle]]) -> None:
|
||||
# an empty list means the fetch failed, not that the catalog dropped the bundle
|
||||
for source, bundles in source_bundles.items():
|
||||
_validate_active_bundle(params, source, bundles or None)
|
||||
get_active_model_runner(params, force_check=True)
|
||||
|
||||
|
||||
def get_active_model_runner(params: Params | None = None, force_check: bool = False) -> int:
|
||||
params = params or Params()
|
||||
cached_runner_type = params.get("ModelRunnerTypeCache")
|
||||
if cached_runner_type is not None and not force_check:
|
||||
return cached_runner_type
|
||||
runner_type = custom.ModelManagerSP.Runner.stock
|
||||
if active_bundle := get_active_bundle(params):
|
||||
runner_type = active_bundle.runner.raw
|
||||
|
||||
if cached_runner_type != runner_type:
|
||||
params.put("ModelRunnerTypeCache", int(runner_type), block=True)
|
||||
|
||||
return runner_type
|
||||
|
||||
|
||||
def _get_model():
|
||||
if bundle := get_active_bundle():
|
||||
drive_model = next(model for model in bundle.models if model.type == ModelManager.Model.Type.supercombo)
|
||||
return drive_model
|
||||
return None
|
||||
|
||||
|
||||
# The following method(s) are modeld helper methods
|
||||
def plan_x_idxs_helper(constants, plan, model_output) -> list[float]:
|
||||
# times at X_IDXS according to plan.
|
||||
LINE_T_IDXS = [np.nan] * constants.IDX_N
|
||||
LINE_T_IDXS[0] = 0.0
|
||||
plan_x = model_output['plan'][0, :, plan.POSITION][:, 0].tolist()
|
||||
for xidx in range(1, constants.IDX_N):
|
||||
tidx = 0
|
||||
# increment tidx until we find an element that's further away than the current xidx
|
||||
while tidx < constants.IDX_N - 1 and plan_x[tidx + 1] < constants.X_IDXS[xidx]:
|
||||
tidx += 1
|
||||
if tidx == constants.IDX_N - 1:
|
||||
# if the plan doesn't extend far enough, set plan_t to the max value (10s), then break
|
||||
LINE_T_IDXS[xidx] = constants.T_IDXS[constants.IDX_N - 1]
|
||||
break
|
||||
# interpolate to find `t` for the current xidx
|
||||
current_x_val = plan_x[tidx]
|
||||
next_x_val = plan_x[tidx + 1]
|
||||
p = (constants.X_IDXS[xidx] - current_x_val) / (next_x_val - current_x_val) if abs(
|
||||
next_x_val - current_x_val) > 1e-9 else float('nan')
|
||||
LINE_T_IDXS[xidx] = p * constants.T_IDXS[tidx + 1] + (1 - p) * constants.T_IDXS[tidx]
|
||||
return LINE_T_IDXS
|
||||
@@ -0,0 +1,382 @@
|
||||
"""
|
||||
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
|
||||
import requests
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.realtime import Ratekeeper
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.common.hardware.hw import Paths
|
||||
|
||||
from openpilot.cereal import messaging, custom
|
||||
from openpilot.sunnypilot.models.fetcher import ModelFetcher
|
||||
from openpilot.sunnypilot.models.helpers import (ACTIVE_BUNDLE_KEYS, get_active_bundle, get_selected_bundle,
|
||||
resolve_bundle_by_ref, validate_active_bundles, verify_file)
|
||||
|
||||
# (connect, read) seconds. read is per-request inactivity, not a total cap
|
||||
DOWNLOAD_TIMEOUT = (30, 30)
|
||||
|
||||
|
||||
class DownloadCancelled(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ModelManagerSP:
|
||||
"""Manages model downloads and status reporting"""
|
||||
|
||||
def __init__(self):
|
||||
self.params = Params()
|
||||
self.model_fetcher = ModelFetcher(self.params)
|
||||
self.pm = messaging.PubMaster(["modelManagerSP"])
|
||||
self.sm = messaging.SubMaster(["deviceState"])
|
||||
self.chestnut_present = False
|
||||
self.available_models: list[custom.ModelManagerSP.ModelBundle] = []
|
||||
self.source_models: dict[str, list[custom.ModelManagerSP.ModelBundle]] = {}
|
||||
self.selected_bundle: custom.ModelManagerSP.ModelBundle = None
|
||||
self.active_bundle: custom.ModelManagerSP.ModelBundle = get_active_bundle(self.params, chestnut=self.chestnut_present)
|
||||
self._chunk_size = 128 * 1000 # 128 KB chunks
|
||||
self._download_start_times: dict[str, float] = {} # Track start time per model
|
||||
self._download_ref: bytes | str | None = None
|
||||
|
||||
def _download_interrupted(self) -> bool:
|
||||
# only removal cancels: a different ref is a queued selection that
|
||||
# _release_download_ref leaves in place for the next tick
|
||||
return self.params.get("ModelManager_DownloadRef") is None
|
||||
|
||||
def _release_download_ref(self) -> None:
|
||||
if self.params.get("ModelManager_DownloadRef") == self._download_ref:
|
||||
self.params.remove("ModelManager_DownloadRef")
|
||||
self._download_ref = None
|
||||
|
||||
def _sync_artifact_progress(self, source_artifact) -> None:
|
||||
"""Mirror download progress to all artifacts sharing the same filename in the selected bundle."""
|
||||
if not self.selected_bundle:
|
||||
return
|
||||
for model in self.selected_bundle.models:
|
||||
artifact = model.artifact
|
||||
if artifact is not source_artifact and artifact.fileName == source_artifact.fileName:
|
||||
artifact.downloadProgress.status = source_artifact.downloadProgress.status
|
||||
artifact.downloadProgress.progress = source_artifact.downloadProgress.progress
|
||||
artifact.downloadProgress.eta = source_artifact.downloadProgress.eta
|
||||
|
||||
def _calculate_eta(self, filename: str, progress: float) -> int:
|
||||
"""Calculate ETA based on elapsed time and current progress"""
|
||||
if filename not in self._download_start_times or progress <= 0:
|
||||
return 60 # Default ETA for new downloads
|
||||
|
||||
elapsed_time = time.monotonic() - self._download_start_times[filename]
|
||||
if elapsed_time <= 0:
|
||||
return 60
|
||||
|
||||
# If we're at X% after Y seconds, we can estimate total time as (Y / X) * 100
|
||||
total_estimated_time = (elapsed_time / progress) * 100
|
||||
eta = total_estimated_time - elapsed_time
|
||||
|
||||
return max(1, int(eta)) # Return at least 1 second if download is ongoing
|
||||
|
||||
async def _download_file(self, url: str, path: str, model) -> None:
|
||||
"""Downloads a file with progress tracking"""
|
||||
self._download_start_times[model.fileName] = time.monotonic()
|
||||
|
||||
with requests.get(url, stream=True, timeout=DOWNLOAD_TIMEOUT) as response: # noqa: ASYNC210
|
||||
response.raise_for_status()
|
||||
total_size = int(response.headers.get("content-length", 0))
|
||||
bytes_downloaded = 0
|
||||
|
||||
with open(path, 'wb') as f: # noqa: ASYNC230
|
||||
for chunk in response.iter_content(chunk_size=self._chunk_size): # type: bytes
|
||||
f.write(chunk)
|
||||
bytes_downloaded += len(chunk)
|
||||
|
||||
if self._download_interrupted():
|
||||
raise DownloadCancelled("Download cancelled")
|
||||
|
||||
if total_size > 0:
|
||||
progress = (bytes_downloaded / total_size) * 100
|
||||
model.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.downloading
|
||||
model.downloadProgress.progress = progress
|
||||
model.downloadProgress.eta = self._calculate_eta(model.fileName, progress)
|
||||
self._sync_artifact_progress(model)
|
||||
self._report_status()
|
||||
|
||||
# Clean up start time after download completes
|
||||
del self._download_start_times[model.fileName]
|
||||
|
||||
async def _download_chunked(self, base_url: str, base_path: str, artifact, skip: frozenset[int] | set[int] = frozenset()) -> None:
|
||||
from openpilot.common.file_chunker import get_chunk_name, get_manifest_path
|
||||
|
||||
num_chunks = len(artifact.chunks)
|
||||
if num_chunks == 0:
|
||||
raise ValueError("No chunks defined in artifact")
|
||||
|
||||
manifest_path = get_manifest_path(base_path)
|
||||
self._download_start_times[artifact.fileName] = time.monotonic()
|
||||
|
||||
# Shared connection saves a TCP+TLS handshake per chunk.
|
||||
# Keep sequential: the link saturates on one stream and Session is not thread-safe.
|
||||
completed = len(skip)
|
||||
with requests.Session() as session:
|
||||
for i, _ in enumerate(artifact.chunks):
|
||||
if i in skip:
|
||||
continue
|
||||
chunk_url = get_chunk_name(base_url, i, num_chunks)
|
||||
chunk_path = get_chunk_name(base_path, i, num_chunks)
|
||||
chunk_downloaded = 0
|
||||
with session.get(chunk_url, stream=True, timeout=DOWNLOAD_TIMEOUT) as response:
|
||||
response.raise_for_status()
|
||||
chunk_size = int(response.headers.get("content-length", 0))
|
||||
with open(chunk_path, 'wb') as f: # noqa: ASYNC230
|
||||
for data in response.iter_content(chunk_size=self._chunk_size):
|
||||
f.write(data)
|
||||
chunk_downloaded += len(data)
|
||||
if self._download_interrupted():
|
||||
raise DownloadCancelled("Download cancelled")
|
||||
intra = chunk_downloaded / max(chunk_size, 1)
|
||||
progress = min(99.0, ((completed + intra) / num_chunks) * 100)
|
||||
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.downloading
|
||||
artifact.downloadProgress.progress = progress
|
||||
artifact.downloadProgress.eta = self._calculate_eta(artifact.fileName, progress)
|
||||
self._sync_artifact_progress(artifact)
|
||||
self._report_status()
|
||||
completed += 1
|
||||
|
||||
with open(manifest_path, 'w') as f: # noqa: ASYNC230
|
||||
f.write(str(num_chunks))
|
||||
if os.path.isfile(base_path): # noqa: ASYNC240
|
||||
os.remove(base_path)
|
||||
del self._download_start_times[artifact.fileName]
|
||||
|
||||
async def _process_artifact(self, artifact, destination_path: str) -> None:
|
||||
if not artifact.downloadUri.uri:
|
||||
return None
|
||||
if self._download_interrupted():
|
||||
raise DownloadCancelled("Download cancelled")
|
||||
|
||||
url = artifact.downloadUri.uri
|
||||
expected_hash = artifact.downloadUri.sha256
|
||||
filename = artifact.fileName
|
||||
full_path = os.path.join(destination_path, filename)
|
||||
|
||||
try:
|
||||
# progress counts only valid chunks so a resumed download continues the
|
||||
# bar from where verification left it, instead of falling back to zero
|
||||
is_cached = False
|
||||
valid_chunks: set[int] = set()
|
||||
if len(artifact.chunks) > 0:
|
||||
from openpilot.common.file_chunker import get_chunk_name
|
||||
num_chunks = len(artifact.chunks)
|
||||
for i, chunk in enumerate(artifact.chunks):
|
||||
if self._download_interrupted():
|
||||
raise DownloadCancelled("Download cancelled")
|
||||
if await verify_file(get_chunk_name(full_path, i, num_chunks), chunk.sha256):
|
||||
valid_chunks.add(i)
|
||||
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.verifying
|
||||
artifact.downloadProgress.progress = (len(valid_chunks) / num_chunks) * 100
|
||||
self._sync_artifact_progress(artifact)
|
||||
self._report_status()
|
||||
is_cached = len(valid_chunks) == num_chunks
|
||||
else:
|
||||
if await verify_file(full_path, expected_hash):
|
||||
is_cached = True
|
||||
|
||||
if is_cached:
|
||||
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.cached
|
||||
artifact.downloadProgress.progress = 100
|
||||
artifact.downloadProgress.eta = 0
|
||||
self._sync_artifact_progress(artifact)
|
||||
self._report_status()
|
||||
return
|
||||
|
||||
if len(artifact.chunks) > 0:
|
||||
await self._download_chunked(url, full_path, artifact, skip=valid_chunks)
|
||||
from openpilot.common.file_chunker import get_chunk_name
|
||||
for i, chunk in enumerate(artifact.chunks):
|
||||
chunk_path = get_chunk_name(full_path, i, len(artifact.chunks))
|
||||
if not await verify_file(chunk_path, chunk.sha256):
|
||||
raise ValueError(f"Hash validation failed for chunk {i+1} of {filename}")
|
||||
else:
|
||||
await self._download_file(url, full_path, artifact)
|
||||
if not await verify_file(full_path, expected_hash):
|
||||
raise ValueError(f"Hash validation failed for {filename}")
|
||||
|
||||
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.downloaded
|
||||
artifact.downloadProgress.progress = 100
|
||||
artifact.downloadProgress.eta = 0
|
||||
self._sync_artifact_progress(artifact)
|
||||
self._report_status()
|
||||
|
||||
except DownloadCancelled:
|
||||
# a cancel keeps whatever is on disk: complete chunks resume the next attempt
|
||||
self._download_start_times.pop(artifact.fileName, None)
|
||||
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.failed
|
||||
artifact.downloadProgress.eta = 0
|
||||
self._sync_artifact_progress(artifact)
|
||||
if self.selected_bundle:
|
||||
self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.failed
|
||||
self._report_status()
|
||||
raise
|
||||
|
||||
except Exception as e:
|
||||
cloudlog.error(f"Error downloading {filename}: {str(e)}")
|
||||
for f in [full_path] + [p for p in (os.path.join(destination_path, f) for f in os.listdir(destination_path)) if filename in p]:
|
||||
if os.path.isfile(f): # noqa: ASYNC240
|
||||
os.remove(f)
|
||||
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.failed
|
||||
artifact.downloadProgress.eta = 0
|
||||
self._sync_artifact_progress(artifact)
|
||||
if self.selected_bundle:
|
||||
self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.failed
|
||||
self._report_status()
|
||||
self._download_start_times.pop(artifact.fileName, None)
|
||||
raise
|
||||
|
||||
async def _process_model(self, model, destination_path: str) -> None:
|
||||
"""Processes a single model download including verification"""
|
||||
await self._process_artifact(model.artifact, destination_path)
|
||||
|
||||
def _report_status(self) -> None:
|
||||
"""Reports current status through messaging system"""
|
||||
msg = messaging.new_message('modelManagerSP', valid=True)
|
||||
model_manager_state = msg.modelManagerSP
|
||||
if self.selected_bundle:
|
||||
model_manager_state.selectedBundle = self.selected_bundle
|
||||
|
||||
if self.active_bundle:
|
||||
model_manager_state.activeBundle = self.active_bundle
|
||||
|
||||
model_manager_state.availableBundles = self.available_models
|
||||
self.pm.send('modelManagerSP', msg)
|
||||
|
||||
async def _download_bundle(self, model_bundle: custom.ModelManagerSP.ModelBundle, destination_path: str, source: str) -> None:
|
||||
self.selected_bundle = model_bundle
|
||||
self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.downloading
|
||||
for model in self.selected_bundle.models:
|
||||
model.artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.downloading
|
||||
self._report_status()
|
||||
os.makedirs(destination_path, exist_ok=True)
|
||||
|
||||
try:
|
||||
seen_artifacts: set[str] = set()
|
||||
for model in self.selected_bundle.models:
|
||||
artifact = model.artifact
|
||||
if not artifact.fileName:
|
||||
continue
|
||||
if artifact.fileName in seen_artifacts:
|
||||
artifact.downloadProgress.status = custom.ModelManagerSP.DownloadStatus.cached
|
||||
artifact.downloadProgress.progress = 100
|
||||
artifact.downloadProgress.eta = 0
|
||||
else:
|
||||
seen_artifacts.add(artifact.fileName)
|
||||
await self._process_artifact(artifact, destination_path)
|
||||
|
||||
if self._download_interrupted():
|
||||
raise DownloadCancelled("Download cancelled")
|
||||
self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.downloaded
|
||||
self.params.put(ACTIVE_BUNDLE_KEYS[source], model_bundle.to_dict(), block=True)
|
||||
self.active_bundle = get_active_bundle(self.params, chestnut=self.chestnut_present)
|
||||
|
||||
except Exception:
|
||||
if self.selected_bundle is not None:
|
||||
self.selected_bundle.status = custom.ModelManagerSP.DownloadStatus.failed
|
||||
raise
|
||||
|
||||
finally:
|
||||
self._report_status()
|
||||
|
||||
def download(self, model_bundle: custom.ModelManagerSP.ModelBundle, destination_path: str, source: str) -> None:
|
||||
"""Main entry point for downloading a model bundle"""
|
||||
asyncio.run(self._download_bundle(model_bundle, destination_path, source))
|
||||
|
||||
def _process_download_requests(self) -> None:
|
||||
# loops so a ref queued during a download starts in the same tick, without
|
||||
# the bar dropping to idle for a tick between the two transfers
|
||||
last_ref = None
|
||||
while (ref_to_download := self.params.get("ModelManager_DownloadRef")) is not None:
|
||||
if ref_to_download == last_ref: # a repeating ref falls back to the next tick instead of spinning
|
||||
return
|
||||
last_ref = ref_to_download
|
||||
resolved = resolve_bundle_by_ref(ref_to_download, self.source_models)
|
||||
if not resolved:
|
||||
return
|
||||
model_to_download, source = resolved
|
||||
self._download_ref = ref_to_download
|
||||
try:
|
||||
self.download(model_to_download, Paths.model_root(), source)
|
||||
except Exception as e:
|
||||
cloudlog.exception(e)
|
||||
finally:
|
||||
self._release_download_ref()
|
||||
self.selected_bundle = None
|
||||
|
||||
def main_thread(self) -> None:
|
||||
"""Main thread for model management"""
|
||||
rk = Ratekeeper(1, print_delay_threshold=None)
|
||||
|
||||
while True:
|
||||
try:
|
||||
self.sm.update(0)
|
||||
self.chestnut_present = self.sm['deviceState'].chestnutPresent
|
||||
self.source_models = {source: self.model_fetcher.get_bundles_for_source(source) for source in ModelFetcher.MODEL_SOURCES}
|
||||
self.available_models = self.source_models[ModelFetcher.active_source(self.chestnut_present)]
|
||||
validate_active_bundles(self.params, self.source_models)
|
||||
self.active_bundle = get_active_bundle(self.params, chestnut=self.chestnut_present)
|
||||
|
||||
if get_selected_bundle(self.params, "chestnut") is not None and get_selected_bundle(self.params, "qcom") is None:
|
||||
if self.params.get("ModelManager_DownloadRef") is None:
|
||||
from openpilot.sunnypilot.models.model_name import DEFAULT_MODEL_REF
|
||||
if DEFAULT_MODEL_REF:
|
||||
self.params.put("ModelManager_DownloadRef", DEFAULT_MODEL_REF)
|
||||
|
||||
self._process_download_requests()
|
||||
|
||||
if self.params.get("ModelManager_ClearCache"):
|
||||
self.clear_model_cache()
|
||||
self.params.remove("ModelManager_ClearCache")
|
||||
|
||||
self._report_status()
|
||||
rk.keep_time()
|
||||
|
||||
except Exception as e:
|
||||
cloudlog.exception(f"Error in main thread: {str(e)}")
|
||||
rk.keep_time()
|
||||
|
||||
def clear_model_cache(self) -> None:
|
||||
"""
|
||||
Clears the model cache directory of all files except those in the active model bundle.
|
||||
"""
|
||||
|
||||
# Get list of files used by both slots' selected bundles (either may become
|
||||
# the truly active bundle depending on hardware availability)
|
||||
active_files = []
|
||||
for source in ACTIVE_BUNDLE_KEYS:
|
||||
if selected_bundle := get_selected_bundle(self.params, source):
|
||||
for model in selected_bundle.models:
|
||||
if model.artifact.fileName:
|
||||
active_files.append(model.artifact.fileName)
|
||||
|
||||
# Remove all files except active ones (including their chunk files)
|
||||
model_dir = Paths.model_root()
|
||||
try:
|
||||
for filename in os.listdir(model_dir):
|
||||
base = filename.split('.chunk')[0] if '.chunk' in filename else filename
|
||||
if base not in active_files and filename not in active_files:
|
||||
file_path = os.path.join(model_dir, filename)
|
||||
if os.path.isfile(file_path):
|
||||
os.remove(file_path)
|
||||
cloudlog.info("Model cache cleared, keeping active model files")
|
||||
except Exception as e:
|
||||
cloudlog.exception(f"Error clearing model cache: {str(e)}")
|
||||
|
||||
def main():
|
||||
ModelManagerSP().main_thread()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,4 @@
|
||||
DEFAULT_MODEL = "CD210"
|
||||
DEFAULT_MODEL_REF = "5b6436a90cf6902b8aaa71c2b6f3d7164d8ae391"
|
||||
DEFAULT_BIG_MODEL = "BMRLNAP Model v4"
|
||||
DEFAULT_BIG_MODEL_REF = "f877d7a0ccc3cce943c76e285214c020cd65c899"
|
||||
@@ -0,0 +1,15 @@
|
||||
import os
|
||||
import numpy as np
|
||||
from openpilot.common.hardware.hw import Paths
|
||||
from openpilot.cereal import custom
|
||||
|
||||
# Type definitions for clarity
|
||||
NumpyDict = dict[str, np.ndarray]
|
||||
ShapeDict = dict[str, tuple[int, ...]]
|
||||
SliceDict = dict[str, slice]
|
||||
|
||||
ModelType = custom.ModelManagerSP.Model.Type
|
||||
Model = custom.ModelManagerSP.Model
|
||||
|
||||
SEND_RAW_PRED = os.getenv('SEND_RAW_PRED')
|
||||
CUSTOM_MODEL_PATH = Paths.model_root()
|
||||
@@ -0,0 +1,95 @@
|
||||
import numpy as np
|
||||
|
||||
|
||||
def index_function(idx, max_val=192, max_idx=32):
|
||||
return max_val * ((idx/max_idx)**2)
|
||||
|
||||
|
||||
class SplitModelConstants:
|
||||
# time and distance indices
|
||||
IDX_N = 33
|
||||
T_IDXS = [index_function(idx, max_val=10.0) for idx in range(IDX_N)]
|
||||
X_IDXS = [index_function(idx, max_val=192.0) for idx in range(IDX_N)]
|
||||
LEAD_T_IDXS = [0., 2., 4., 6., 8., 10.]
|
||||
LEAD_T_OFFSETS = [0., 2., 4.]
|
||||
META_T_IDXS = [2., 4., 6., 8., 10.]
|
||||
|
||||
# model inputs constants
|
||||
MODEL_FREQ = 20
|
||||
HISTORY_FREQ = 5
|
||||
HISTORY_LEN_SECONDS = 5
|
||||
TEMPORAL_SKIP = MODEL_FREQ // HISTORY_FREQ
|
||||
FULL_HISTORY_BUFFER_LEN = MODEL_FREQ * HISTORY_LEN_SECONDS
|
||||
INPUT_HISTORY_BUFFER_LEN = HISTORY_FREQ * HISTORY_LEN_SECONDS
|
||||
|
||||
FEATURE_LEN = 512
|
||||
|
||||
DESIRE_LEN = 8
|
||||
TRAFFIC_CONVENTION_LEN = 2
|
||||
LAT_PLANNER_STATE_LEN = 4
|
||||
LATERAL_CONTROL_PARAMS_LEN = 2
|
||||
PREV_DESIRED_CURV_LEN = 1
|
||||
|
||||
# model outputs constants
|
||||
FCW_THRESHOLDS_5MS2 = np.array([.05, .05, .15, .15, .15], dtype=np.float32)
|
||||
FCW_THRESHOLDS_3MS2 = np.array([.7, .7], dtype=np.float32)
|
||||
FCW_5MS2_PROBS_WIDTH = 5
|
||||
FCW_3MS2_PROBS_WIDTH = 2
|
||||
|
||||
DISENGAGE_WIDTH = 5
|
||||
POSE_WIDTH = 6
|
||||
WIDE_FROM_DEVICE_WIDTH = 3
|
||||
LEAD_WIDTH = 4
|
||||
LANE_LINES_WIDTH = 2
|
||||
ROAD_EDGES_WIDTH = 2
|
||||
PLAN_WIDTH = 15
|
||||
ACTION_WIDTH = 2
|
||||
DESIRE_PRED_WIDTH = 8
|
||||
LAT_PLANNER_SOLUTION_WIDTH = 4
|
||||
DESIRED_CURV_WIDTH = 1
|
||||
|
||||
NUM_LANE_LINES = 4
|
||||
NUM_ROAD_EDGES = 2
|
||||
|
||||
LEAD_TRAJ_LEN = 6
|
||||
DESIRE_PRED_LEN = 4
|
||||
|
||||
PLAN_MHP_N = 5
|
||||
LEAD_MHP_N = 2
|
||||
PLAN_MHP_SELECTION = 1
|
||||
LEAD_MHP_SELECTION = 3
|
||||
|
||||
FCW_THRESHOLD_5MS2_HIGH = 0.15
|
||||
FCW_THRESHOLD_5MS2_LOW = 0.05
|
||||
FCW_THRESHOLD_3MS2 = 0.7
|
||||
|
||||
CONFIDENCE_BUFFER_LEN = 5
|
||||
RYG_GREEN = 0.01165
|
||||
RYG_YELLOW = 0.06157
|
||||
|
||||
POLY_PATH_DEGREE = 4
|
||||
|
||||
|
||||
# model outputs slices
|
||||
class Plan:
|
||||
POSITION = slice(0, 3)
|
||||
VELOCITY = slice(3, 6)
|
||||
ACCELERATION = slice(6, 9)
|
||||
T_FROM_CURRENT_EULER = slice(9, 12)
|
||||
ORIENTATION_RATE = slice(12, 15)
|
||||
|
||||
|
||||
class Meta:
|
||||
ENGAGED = slice(0, 1)
|
||||
# next 2, 4, 6, 8, 10 seconds
|
||||
GAS_DISENGAGE = slice(1, 31, 6)
|
||||
BRAKE_DISENGAGE = slice(2, 31, 6)
|
||||
STEER_OVERRIDE = slice(3, 31, 6)
|
||||
HARD_BRAKE_3 = slice(4, 31, 6)
|
||||
HARD_BRAKE_4 = slice(5, 31, 6)
|
||||
HARD_BRAKE_5 = slice(6, 31, 6)
|
||||
# next 0, 2, 4, 6, 8, 10 seconds
|
||||
GAS_PRESS = slice(31, 55, 4)
|
||||
BRAKE_PRESS = slice(32, 55, 4)
|
||||
LEFT_BLINKER = slice(33, 55, 4)
|
||||
RIGHT_BLINKER = slice(34, 55, 4)
|
||||
@@ -0,0 +1,92 @@
|
||||
{
|
||||
"driving_vision.onnx": {
|
||||
"inputs": [
|
||||
{
|
||||
"name": "img",
|
||||
"shape": [
|
||||
1,
|
||||
12,
|
||||
128,
|
||||
256
|
||||
],
|
||||
"type": "tensor(uint8)"
|
||||
},
|
||||
{
|
||||
"name": "big_img",
|
||||
"shape": [
|
||||
1,
|
||||
12,
|
||||
128,
|
||||
256
|
||||
],
|
||||
"type": "tensor(uint8)"
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "outputs",
|
||||
"shape": [
|
||||
1,
|
||||
1576
|
||||
],
|
||||
"type": "tensor(float16)"
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"output_slices": "gASVQAEAAAAAAAB9lCiMBG1ldGGUjAhidWlsdGluc5SMBXNsaWNllJOUSwBLN06HlFKUjAtkZXNp\ncmVfcHJlZJRoBEs3S1dOh5RSlIwEcG9zZZRoBEtXS2NOh5RSlIwWd2lkZV9mcm9tX2RldmljZV9l\ndWxlcpRoBEtjS2lOh5RSlIwOcm9hZF90cmFuc2Zvcm2UaARLaUt1ToeUUpSMCmxhbmVfbGluZXOU\naARLdU2FAk6HlFKUjA9sYW5lX2xpbmVzX3Byb2KUaARNhQJNjQJOh5RSlIwKcm9hZF9lZGdlc5Ro\nBE2NAk2VA06HlFKUjARsZWFklGgETZUDTSUEToeUUpSMCWxlYWRfcHJvYpRoBE0lBE0oBE6HlFKU\njAxoaWRkZW5fc3RhdGWUaARNKARNKAZOh5RSlIwDcGFklGgESwBOToeUUpR1Lg==\n",
|
||||
"model_checkpoint": "6a7d09ad-bcc9-43bc-916d-29287e60cee2/200"
|
||||
},
|
||||
"provider": [
|
||||
"CPUExecutionProvider"
|
||||
],
|
||||
"producer": "pytorch"
|
||||
},
|
||||
"driving_policy.onnx": {
|
||||
"inputs": [
|
||||
{
|
||||
"name": "desire_pulse",
|
||||
"shape": [
|
||||
1,
|
||||
25,
|
||||
8
|
||||
],
|
||||
"type": "tensor(float16)"
|
||||
},
|
||||
{
|
||||
"name": "traffic_convention",
|
||||
"shape": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"type": "tensor(float16)"
|
||||
},
|
||||
{
|
||||
"name": "features_buffer",
|
||||
"shape": [
|
||||
1,
|
||||
25,
|
||||
512
|
||||
],
|
||||
"type": "tensor(float16)"
|
||||
}
|
||||
],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "outputs",
|
||||
"shape": [
|
||||
1,
|
||||
1000
|
||||
],
|
||||
"type": "tensor(float16)"
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"output_slices": "gASVWgAAAAAAAAB9lCiMBHBsYW6UjAhidWlsdGluc5SMBXNsaWNllJOUSwBN3gNOh5RSlIwMZGVz\naXJlX3N0YXRllGgETd4DTeYDToeUUpSMA3BhZJRoBEr+////Tk6HlFKUdS4=\n",
|
||||
"model_checkpoint": "05a58a51-e0e3-4e9b-8e27-e644685f2c50/100"
|
||||
},
|
||||
"provider": [
|
||||
"CPUExecutionProvider"
|
||||
],
|
||||
"producer": "pytorch"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
[
|
||||
{
|
||||
"id": "supercombo-6409",
|
||||
"label": "Supercombo 6409 (current calibration)",
|
||||
"file": "supercombo.onnx",
|
||||
"manifest": "manifest.json"
|
||||
},
|
||||
{
|
||||
"id": "pop-v2",
|
||||
"label": "Pop v2 (experimental preview)",
|
||||
"file": "pop-v2/driving_vision.onnx",
|
||||
"manifest": "pop-v2/manifest.json"
|
||||
},
|
||||
{
|
||||
"id": "wmi-v0.11.0",
|
||||
"label": "Stock WMI (openpilot 0.11.0)",
|
||||
"file": "wmi-v0.11.0/driving_vision.onnx",
|
||||
"manifest": "wmi-v0.11.0/manifest.json"
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"source_revision": "3469d9aadbc16eb854bad3d851bd580d2b8f132e",
|
||||
"source_tag": "v0.11.0",
|
||||
"source_hashes": {
|
||||
"common_transformations_model.py": "c87aad27074362fe9fe361a71da92c1fc90daf63bcfd4d8c47d65d3a936ec15e",
|
||||
"selfdrive_controls_lib_drive_helpers.py": "0c8b32b1667000d48ee4630f0b197a05edabd811d718709ab616872c35918844",
|
||||
"selfdrive_modeld_compile_warp.py": "574aa090de6fa272f95b00e039b1467d60c6d9445ee8d774e8529369648fcf0f",
|
||||
"selfdrive_modeld_constants.py": "e1e3a01ea31dd57dbd9ffd588ff1f2ab22e6088a558c65ad68bf20678552c00c",
|
||||
"selfdrive_modeld_fill_model_msg.py": "d99289ee16ddbcc286abc7184f1de55ad4378d860092ec896d1cdc4cf4f12799",
|
||||
"selfdrive_modeld_get_model_metadata.py": "045d9fd4b10ff989adc5837b9a5dfad2b961b890f46f0bbe995335dae5e68789",
|
||||
"selfdrive_modeld_modeld.py": "571496f6e8b8364d90d0e2dddcb2a6f375ecbb434927e11078f40084e56f3b66",
|
||||
"selfdrive_modeld_parse_model_outputs.py": "82d5eb5391f2c02c187adb3ad9ae6ad9d97fd0ae681d54e808a438f415802ed4"
|
||||
},
|
||||
"decoded_metadata_no_pickle_execution": true,
|
||||
"same_output_slices_as_pop": true,
|
||||
"same_parser_constants_modeld_source_as_pop": true,
|
||||
"different_weights_from_pop": true
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "Stock openpilot 0.11.0 WMI",
|
||||
"model_id": "wmi-v0.11.0",
|
||||
"output_layout": "pop-v2-split-1576-1000",
|
||||
"model_file": "driving_vision.onnx",
|
||||
"sha256": "ee29ee5bce84d1ce23e9ff381280de9b4e4d96d2934cd751740354884e112c66",
|
||||
"policy_file": "driving_policy.onnx",
|
||||
"policy_sha256": "78477124cbf3ffe30fa951ebada8410b43c4242c6054584d656f1d329b067e15",
|
||||
"source_repository": "commaai/openpilot",
|
||||
"source_revision": "3469d9aadbc16eb854bad3d851bd580d2b8f132e",
|
||||
"source_tag": "v0.11.0",
|
||||
"expected_run_hz": 20,
|
||||
"context_hz": 5,
|
||||
"image_pair_separation_s": 0.2,
|
||||
"feature_context_samples": 25,
|
||||
"feature_context_span_s": 4.8,
|
||||
"experimental": true,
|
||||
"preview_only": true,
|
||||
"camera_validated": false,
|
||||
"usable_for_control": false,
|
||||
"decoder_compatibility": "Tagged WMI tensor signatures and embedded output_slices exactly match the Pop v2 split contract; constants, parser and modeld source are byte-identical. Policy checkpoint is distinct; vision checkpoint is shared with Pop, with a different ONNX artifact hash.",
|
||||
"plan_confidence": "unassessed: unary mean/logstd plan has no selection probability",
|
||||
"camera_approximation": "ATS SBIG render with derived MED crop; physical calibration remains unvalidated. Display toggle does not change inference inputs.",
|
||||
"source_urls": {
|
||||
"vision": "https://media.githubusercontent.com/media/commaai/openpilot/3469d9aadbc16eb854bad3d851bd580d2b8f132e/selfdrive/modeld/models/driving_vision.onnx",
|
||||
"policy": "https://media.githubusercontent.com/media/commaai/openpilot/3469d9aadbc16eb854bad3d851bd580d2b8f132e/selfdrive/modeld/models/driving_policy.onnx",
|
||||
"release": "https://blog.comma.ai/011release/"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"vision": {
|
||||
"meta": [
|
||||
0,
|
||||
55
|
||||
],
|
||||
"desire_pred": [
|
||||
55,
|
||||
87
|
||||
],
|
||||
"pose": [
|
||||
87,
|
||||
99
|
||||
],
|
||||
"wide_from_device_euler": [
|
||||
99,
|
||||
105
|
||||
],
|
||||
"road_transform": [
|
||||
105,
|
||||
117
|
||||
],
|
||||
"lane_lines": [
|
||||
117,
|
||||
645
|
||||
],
|
||||
"lane_lines_prob": [
|
||||
645,
|
||||
653
|
||||
],
|
||||
"road_edges": [
|
||||
653,
|
||||
917
|
||||
],
|
||||
"lead": [
|
||||
917,
|
||||
1061
|
||||
],
|
||||
"lead_prob": [
|
||||
1061,
|
||||
1064
|
||||
],
|
||||
"hidden_state": [
|
||||
1064,
|
||||
1576
|
||||
]
|
||||
},
|
||||
"policy": {
|
||||
"plan": [
|
||||
0,
|
||||
990
|
||||
],
|
||||
"desire_state": [
|
||||
990,
|
||||
998
|
||||
]
|
||||
},
|
||||
"lane_probability_logit_indices": [
|
||||
1,
|
||||
3,
|
||||
5,
|
||||
7
|
||||
],
|
||||
"plan_mean_shape": [
|
||||
33,
|
||||
15
|
||||
],
|
||||
"plan_std_encoding": "second495 values exp(logstd), exponent clipped11 upstream",
|
||||
"extraction": "WMI v0.11.0 embedded output_slices are byte-identical to Pop metadata, independently checked via pickletools disassembly; no pickle execution"
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import numpy as np
|
||||
|
||||
from openpilot.common.transformations.orientation import rot_from_euler
|
||||
from openpilot.common.transformations.camera import get_view_frame_from_calib_frame, view_frame_from_device_frame, _ar_ox_fisheye
|
||||
|
||||
# segnet
|
||||
SEGNET_SIZE = (512, 384)
|
||||
|
||||
# MED model
|
||||
MEDMODEL_INPUT_SIZE = (512, 256)
|
||||
MEDMODEL_YUV_SIZE = (MEDMODEL_INPUT_SIZE[0], MEDMODEL_INPUT_SIZE[1] * 3 // 2)
|
||||
MEDMODEL_CY = 47.6
|
||||
|
||||
medmodel_fl = 910.0
|
||||
medmodel_intrinsics = np.array([
|
||||
[medmodel_fl, 0.0, 0.5 * MEDMODEL_INPUT_SIZE[0]],
|
||||
[0.0, medmodel_fl, MEDMODEL_CY],
|
||||
[0.0, 0.0, 1.0]])
|
||||
|
||||
|
||||
# BIG model
|
||||
BIGMODEL_INPUT_SIZE = (1024, 512)
|
||||
BIGMODEL_YUV_SIZE = (BIGMODEL_INPUT_SIZE[0], BIGMODEL_INPUT_SIZE[1] * 3 // 2)
|
||||
|
||||
bigmodel_fl = 910.0
|
||||
bigmodel_intrinsics = np.array([
|
||||
[bigmodel_fl, 0.0, 0.5 * BIGMODEL_INPUT_SIZE[0]],
|
||||
[0.0, bigmodel_fl, 256 + MEDMODEL_CY],
|
||||
[0.0, 0.0, 1.0]])
|
||||
|
||||
|
||||
# SBIG model (big model with the size of small model)
|
||||
SBIGMODEL_INPUT_SIZE = (512, 256)
|
||||
SBIGMODEL_YUV_SIZE = (SBIGMODEL_INPUT_SIZE[0], SBIGMODEL_INPUT_SIZE[1] * 3 // 2)
|
||||
|
||||
sbigmodel_fl = 455.0
|
||||
sbigmodel_intrinsics = np.array([
|
||||
[sbigmodel_fl, 0.0, 0.5 * SBIGMODEL_INPUT_SIZE[0]],
|
||||
[0.0, sbigmodel_fl, 0.5 * (256 + MEDMODEL_CY)],
|
||||
[0.0, 0.0, 1.0]])
|
||||
|
||||
DM_INPUT_SIZE = (1440, 960)
|
||||
dmonitoringmodel_fl = _ar_ox_fisheye.focal_length
|
||||
dmonitoringmodel_intrinsics = np.array([
|
||||
[dmonitoringmodel_fl, 0.0, DM_INPUT_SIZE[0]/2],
|
||||
[0.0, dmonitoringmodel_fl, DM_INPUT_SIZE[1]/2 - (_ar_ox_fisheye.height - DM_INPUT_SIZE[1])/2],
|
||||
[0.0, 0.0, 1.0]])
|
||||
|
||||
bigmodel_frame_from_calib_frame = np.dot(bigmodel_intrinsics,
|
||||
get_view_frame_from_calib_frame(0, 0, 0, 0))
|
||||
|
||||
|
||||
sbigmodel_frame_from_calib_frame = np.dot(sbigmodel_intrinsics,
|
||||
get_view_frame_from_calib_frame(0, 0, 0, 0))
|
||||
|
||||
medmodel_frame_from_calib_frame = np.dot(medmodel_intrinsics,
|
||||
get_view_frame_from_calib_frame(0, 0, 0, 0))
|
||||
|
||||
medmodel_frame_from_bigmodel_frame = np.dot(medmodel_intrinsics, np.linalg.inv(bigmodel_intrinsics))
|
||||
|
||||
calib_from_medmodel = np.linalg.inv(medmodel_frame_from_calib_frame[:, :3])
|
||||
calib_from_sbigmodel = np.linalg.inv(sbigmodel_frame_from_calib_frame[:, :3])
|
||||
|
||||
# This function is verified to give similar results to xx.uncommon.utils.transform_img
|
||||
def get_warp_matrix(device_from_calib_euler: np.ndarray, intrinsics: np.ndarray, bigmodel_frame: bool = False) -> np.ndarray:
|
||||
calib_from_model = calib_from_sbigmodel if bigmodel_frame else calib_from_medmodel
|
||||
device_from_calib = rot_from_euler(device_from_calib_euler)
|
||||
camera_from_calib = intrinsics @ view_frame_from_device_frame @ device_from_calib
|
||||
warp_matrix: np.ndarray = camera_from_calib @ calib_from_model
|
||||
return warp_matrix
|
||||
@@ -0,0 +1,43 @@
|
||||
0: \x80 PROTO 4
|
||||
2: \x95 FRAME 90
|
||||
11: } EMPTY_DICT
|
||||
12: \x94 MEMOIZE (as 0)
|
||||
13: ( MARK
|
||||
14: \x8c SHORT_BINUNICODE 'plan'
|
||||
20: \x94 MEMOIZE (as 1)
|
||||
21: \x8c SHORT_BINUNICODE 'builtins'
|
||||
31: \x94 MEMOIZE (as 2)
|
||||
32: \x8c SHORT_BINUNICODE 'slice'
|
||||
39: \x94 MEMOIZE (as 3)
|
||||
40: \x93 STACK_GLOBAL
|
||||
41: \x94 MEMOIZE (as 4)
|
||||
42: K BININT1 0
|
||||
44: M BININT2 990
|
||||
47: N NONE
|
||||
48: \x87 TUPLE3
|
||||
49: \x94 MEMOIZE (as 5)
|
||||
50: R REDUCE
|
||||
51: \x94 MEMOIZE (as 6)
|
||||
52: \x8c SHORT_BINUNICODE 'desire_state'
|
||||
66: \x94 MEMOIZE (as 7)
|
||||
67: h BINGET 4
|
||||
69: M BININT2 990
|
||||
72: M BININT2 998
|
||||
75: N NONE
|
||||
76: \x87 TUPLE3
|
||||
77: \x94 MEMOIZE (as 8)
|
||||
78: R REDUCE
|
||||
79: \x94 MEMOIZE (as 9)
|
||||
80: \x8c SHORT_BINUNICODE 'pad'
|
||||
85: \x94 MEMOIZE (as 10)
|
||||
86: h BINGET 4
|
||||
88: J BININT -2
|
||||
93: N NONE
|
||||
94: N NONE
|
||||
95: \x87 TUPLE3
|
||||
96: \x94 MEMOIZE (as 11)
|
||||
97: R REDUCE
|
||||
98: \x94 MEMOIZE (as 12)
|
||||
99: u SETITEMS (MARK at 13)
|
||||
100: . STOP
|
||||
highest protocol among opcodes = 4
|
||||
@@ -0,0 +1,133 @@
|
||||
0: \x80 PROTO 4
|
||||
2: \x95 FRAME 320
|
||||
11: } EMPTY_DICT
|
||||
12: \x94 MEMOIZE (as 0)
|
||||
13: ( MARK
|
||||
14: \x8c SHORT_BINUNICODE 'meta'
|
||||
20: \x94 MEMOIZE (as 1)
|
||||
21: \x8c SHORT_BINUNICODE 'builtins'
|
||||
31: \x94 MEMOIZE (as 2)
|
||||
32: \x8c SHORT_BINUNICODE 'slice'
|
||||
39: \x94 MEMOIZE (as 3)
|
||||
40: \x93 STACK_GLOBAL
|
||||
41: \x94 MEMOIZE (as 4)
|
||||
42: K BININT1 0
|
||||
44: K BININT1 55
|
||||
46: N NONE
|
||||
47: \x87 TUPLE3
|
||||
48: \x94 MEMOIZE (as 5)
|
||||
49: R REDUCE
|
||||
50: \x94 MEMOIZE (as 6)
|
||||
51: \x8c SHORT_BINUNICODE 'desire_pred'
|
||||
64: \x94 MEMOIZE (as 7)
|
||||
65: h BINGET 4
|
||||
67: K BININT1 55
|
||||
69: K BININT1 87
|
||||
71: N NONE
|
||||
72: \x87 TUPLE3
|
||||
73: \x94 MEMOIZE (as 8)
|
||||
74: R REDUCE
|
||||
75: \x94 MEMOIZE (as 9)
|
||||
76: \x8c SHORT_BINUNICODE 'pose'
|
||||
82: \x94 MEMOIZE (as 10)
|
||||
83: h BINGET 4
|
||||
85: K BININT1 87
|
||||
87: K BININT1 99
|
||||
89: N NONE
|
||||
90: \x87 TUPLE3
|
||||
91: \x94 MEMOIZE (as 11)
|
||||
92: R REDUCE
|
||||
93: \x94 MEMOIZE (as 12)
|
||||
94: \x8c SHORT_BINUNICODE 'wide_from_device_euler'
|
||||
118: \x94 MEMOIZE (as 13)
|
||||
119: h BINGET 4
|
||||
121: K BININT1 99
|
||||
123: K BININT1 105
|
||||
125: N NONE
|
||||
126: \x87 TUPLE3
|
||||
127: \x94 MEMOIZE (as 14)
|
||||
128: R REDUCE
|
||||
129: \x94 MEMOIZE (as 15)
|
||||
130: \x8c SHORT_BINUNICODE 'road_transform'
|
||||
146: \x94 MEMOIZE (as 16)
|
||||
147: h BINGET 4
|
||||
149: K BININT1 105
|
||||
151: K BININT1 117
|
||||
153: N NONE
|
||||
154: \x87 TUPLE3
|
||||
155: \x94 MEMOIZE (as 17)
|
||||
156: R REDUCE
|
||||
157: \x94 MEMOIZE (as 18)
|
||||
158: \x8c SHORT_BINUNICODE 'lane_lines'
|
||||
170: \x94 MEMOIZE (as 19)
|
||||
171: h BINGET 4
|
||||
173: K BININT1 117
|
||||
175: M BININT2 645
|
||||
178: N NONE
|
||||
179: \x87 TUPLE3
|
||||
180: \x94 MEMOIZE (as 20)
|
||||
181: R REDUCE
|
||||
182: \x94 MEMOIZE (as 21)
|
||||
183: \x8c SHORT_BINUNICODE 'lane_lines_prob'
|
||||
200: \x94 MEMOIZE (as 22)
|
||||
201: h BINGET 4
|
||||
203: M BININT2 645
|
||||
206: M BININT2 653
|
||||
209: N NONE
|
||||
210: \x87 TUPLE3
|
||||
211: \x94 MEMOIZE (as 23)
|
||||
212: R REDUCE
|
||||
213: \x94 MEMOIZE (as 24)
|
||||
214: \x8c SHORT_BINUNICODE 'road_edges'
|
||||
226: \x94 MEMOIZE (as 25)
|
||||
227: h BINGET 4
|
||||
229: M BININT2 653
|
||||
232: M BININT2 917
|
||||
235: N NONE
|
||||
236: \x87 TUPLE3
|
||||
237: \x94 MEMOIZE (as 26)
|
||||
238: R REDUCE
|
||||
239: \x94 MEMOIZE (as 27)
|
||||
240: \x8c SHORT_BINUNICODE 'lead'
|
||||
246: \x94 MEMOIZE (as 28)
|
||||
247: h BINGET 4
|
||||
249: M BININT2 917
|
||||
252: M BININT2 1061
|
||||
255: N NONE
|
||||
256: \x87 TUPLE3
|
||||
257: \x94 MEMOIZE (as 29)
|
||||
258: R REDUCE
|
||||
259: \x94 MEMOIZE (as 30)
|
||||
260: \x8c SHORT_BINUNICODE 'lead_prob'
|
||||
271: \x94 MEMOIZE (as 31)
|
||||
272: h BINGET 4
|
||||
274: M BININT2 1061
|
||||
277: M BININT2 1064
|
||||
280: N NONE
|
||||
281: \x87 TUPLE3
|
||||
282: \x94 MEMOIZE (as 32)
|
||||
283: R REDUCE
|
||||
284: \x94 MEMOIZE (as 33)
|
||||
285: \x8c SHORT_BINUNICODE 'hidden_state'
|
||||
299: \x94 MEMOIZE (as 34)
|
||||
300: h BINGET 4
|
||||
302: M BININT2 1064
|
||||
305: M BININT2 1576
|
||||
308: N NONE
|
||||
309: \x87 TUPLE3
|
||||
310: \x94 MEMOIZE (as 35)
|
||||
311: R REDUCE
|
||||
312: \x94 MEMOIZE (as 36)
|
||||
313: \x8c SHORT_BINUNICODE 'pad'
|
||||
318: \x94 MEMOIZE (as 37)
|
||||
319: h BINGET 4
|
||||
321: K BININT1 0
|
||||
323: N NONE
|
||||
324: N NONE
|
||||
325: \x87 TUPLE3
|
||||
326: \x94 MEMOIZE (as 38)
|
||||
327: R REDUCE
|
||||
328: \x94 MEMOIZE (as 39)
|
||||
329: u SETITEMS (MARK at 13)
|
||||
330: . STOP
|
||||
highest protocol among opcodes = 4
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user