matlab-cosimulate-sumo-simulink
>
git clone --depth 1 https://github.com/matlab/matlab-agentic-toolkit /tmp/matlab-cosimulate-sumo-simulink && cp -r /tmp/matlab-cosimulate-sumo-simulink/skills-catalog/automotive/matlab-cosimulate-sumo-simulink ~/.claude/skills/matlab-cosimulate-sumo-simulinkSKILL.md
# Build SUMO-Simulink Co-simulation
Create Simulink models that run synchronized co-simulation with Eclipse SUMO using the `SumoInterfaceLibrary` blocks from the Automated Driving Toolbox Interface for Eclipse SUMO Traffic Simulator.
## When to Use
- Building a Simulink model that connects to Eclipse SUMO
- Setting up traffic co-simulation for ADAS/AD controller testing
- Reading vehicle states (position, speed) from SUMO into Simulink
- Controlling an ego vehicle in SUMO from a Simulink controller
- Spawning or removing vehicles dynamically during simulation
- Generating random background traffic without writing route files
## When NOT to Use
- Pure SUMO simulation without Simulink (use SUMO's CLI or Python TraCI directly)
- Vehicle dynamics modeling (use Vehicle Dynamics Blockset)
- Scenario design with Driving Scenario Designer (different workflow)
## Prerequisites
1. **Eclipse SUMO installed** with `SUMO_HOME` environment variable set
2. **Support package installed**: "Automated Driving Toolbox Interface for Eclipse SUMO Traffic Simulator"
3. **Windows: append trailing separator to `SUMO_HOME`** — The Server block's launcher concatenates `SUMO_HOME + "bin\..."` without a separator. If `SUMO_HOME` lacks a trailing `\` or `/`, every `sim()` fails with "Failed to launch Eclipse SUMO simulator" even though SUMO is installed correctly. Always run before building/simulating:
```matlab
if ~endsWith(getenv('SUMO_HOME'), filesep)
setenv('SUMO_HOME', [getenv('SUMO_HOME') filesep]);
end
```
4. **Verify**: `getenv('SUMO_HOME')` must return a valid path ending with a separator.
## Preferred Construction Path
When `mcp__matlab__model_edit` (SATK) is available, prefer it over raw `add_block`/`add_line`. It applies auto-layout after every edit, produces clean wiring with no overlap, and lets you reference newly-added blocks by `ref` within the same call. The patterns below still apply — express them as `add_block`/`connect`/`configure` operations in a single JSON payload. Fall back to `add_block`/`add_line` only when SATK is unavailable or when the operation is not expressible in the schema (e.g., setting MATLAB Function `Script` via `sfroot`).
**Note:** When wiring `EnablePort` on a freshly-created Enabled Subsystem whose default `In1`/`Out1` have been deleted, `model_edit` cannot resolve the Enable port. Workaround: `add_line(model, 'Source/1', 'SubsystemName/Enable', 'autorouting','smart')`.
## Workflow
### Idempotent Build Template
```matlab
modelName = 'sumo_cosim';
workDir = fileparts(mfilename('fullpath'));
% SUMO_HOME workaround (Windows)
sh = getenv('SUMO_HOME');
if ~endsWith(sh, filesep), setenv('SUMO_HOME', [sh filesep]); end
% Idempotent rebuild
if bdIsLoaded(modelName), close_system(modelName, 0); end
slxPath = fullfile(workDir, [modelName '.slx']);
if isfile(slxPath), delete(slxPath); end
new_system(modelName);
open_system(modelName);
set_param(modelName, 'StopTime','100', 'SolverType','Fixed-step', 'FixedStep','0.1');
% ... build model ...
save_system(modelName, slxPath);
```
### 1. Prepare SUMO Scenario Files
Ask the user for their existing `.sumocfg`. Only generate new files if explicitly requested. For quick networks use `netgenerate`:
```matlab
sumoHome = getenv('SUMO_HOME');
cmd = sprintf('"%s" --grid --grid.number 2 --grid.length 200 --output-file "%s"', ...
fullfile(sumoHome,'bin','netgenerate'), fullfile(pwd,'network.net.xml'));
system(cmd);
```
Minimal `.sumocfg` (route-files optional when using `EnableRandomTraffic`):
```xml
<configuration>
<input><net-file value="network.net.xml"/></input>
<time><begin value="0"/><end value="100"/><step-length value="0.1"/></time>
</configuration>
```
**Route file rules:** All `<vehicle>`, `<person>`, and `<personFlow>` entries MUST be sorted by `depart` time (`begin` for flows). Out-of-order entries are silently ignored. Routes used by Actor blocks must be standalone `<route>` elements — not embedded in `<flow>`.
**OpenDRIVE import:** Use `netconvert --opendrive-files file.xodr -o network.net.xml`. Note: SUMO applies a `netOffset` (visible in `.net.xml` `<location>` element) — all SUMO coordinates = OpenDRIVE coordinates + netOffset.
### 2. Create Server and Client
```matlab
add_block('SumoInterfaceLibrary/Server', [modelName '/SUMO Server']);
set_param([modelName '/SUMO Server'], 'ServerFile',fullfile(pwd,'cosim.sumocfg'), ...
'ServerPort','8813', 'ServerNumClients','1', 'EnablePacing','on', ...
'PacingRate','1', 'SampleTime','0.1');
add_block('SumoInterfaceLibrary/Client', [modelName '/SUMO Client']);
set_param([modelName '/SUMO Client'], 'ClientAddress','127.0.0.1', ...
'ClientPort','8813', 'ClientOrder','1', 'SampleTime','0.1');
```
**Critical:** `ClientPort` must equal `ServerPort`. `FixedStep` must match SUMO `step-length`. Enable pacing (`EnablePacing='on'`) so the GUI doesn't flash by in 2 seconds.
### 3–6. Add Readers, Writers, Actors, Save and Run
See Block Reference and Patterns sections below. Always `save_system(modelName)` before `sim(modelName)` when the model has been modified programmatically.
## Block Reference
### Server Block
| Parameter | Purpose | Default |
|-----------|---------|---------|
| `ServerFile` | Path to `.sumocfg` | — |
| `ServerPort` | TraCI port | `'8813'` |
| `ServerNumClients` | Number of clients | `'1'` |
| `EnableRandomTraffic` | Spawn vehicles without route file | `'off'` |
| `RandomTraffic` | Vehicle count when random traffic enabled | `'0'` |
| `EnablePacing` | Real-time pacing (recommended for demos) | `'off'` |
| `PacingRate` | Pacing multiplier | `'1'` |
| `SampleTime` | Step interval | `'-1'` |
**Note:** SUMO default `time-to-teleport=300s` — any vehicle stuck >300s gets teleported. This can surprise when deliberately stopping an ego at a bus stop.
### Client Block
| Parameter | Purpose | Default |
|-----------|---------|---------|
| `ClientAddress` | Server IP | `'127.0.0.1'` |
| `ClientPort` | Must match ServerPort | `'8813'` |
|>
Import recorded driving sensor data (GPS, camera, lidar, actor tracks, lanes) into scenariobuilder.* objects (GPSData, CameraData, LidarData, ActorTrackData, Trajectory, laneData) and run preprocessing — synchronize, offset correction, crop, normalizeTimestamps, convertTimestamps. Also: compute actor tracks from lidar when no annotations exist, attach camera/lidar mounting + intrinsics, export to MAT/workspace/timetable/script. Use for raw driving dataset files (KITTI, nuScenes, Waymo, Pandaset, ROS/ROS2 bags, .mat, .csv, .mp4) or driving/vehicle/sensor logs that need wrapping. drivingLogAnalyzer (DLA) is OPT-IN ONLY — invoke only on explicit user request ('DLA', 'open in DLA', 'inspect/explore/analyze the recording') or reported sensor problem (sync drift, timestamp mismatch, overlay misalignment). NEVER auto-launch DLA after wrapping (Rule 0). For 'build scenario / export to RoadRunner / drivingScenario / OpenSCENARIO / Unreal / simulate', hand off to matlab-scenario-builder.
Generate driving scenes, scenarios, road surfaces, and 3D content from already-wrapped scenariobuilder.* sensor data (GPS, camera, lidar, actor tracks) using Scenario Builder for Automated Driving Toolbox. Use to BUILD, EXPORT, or AUGMENT a virtual scenario/scene/map: ego or actor trajectories, trajectory smoothing, OpenCRG road-surface extraction, 3D asset generation, static-object placement, point-cloud georeferencing + elevation, lane-based ego localization, sensor-fusion tracking, scenario-event extraction (cut-ins, hard brakes, near-misses, ADAS disengagements), or export to RoadRunner, drivingScenario, OpenDRIVE, OpenCRG, OpenSCENARIO, or Unreal Engine. Also: log-to-scenario, scenario harvesting, accident/near-miss reconstruction, SOTIF (ISO 21448) and ISO 26262 scenario coverage, USGS-aerial-lidar scene augmentation, traffic-sign placement from camera+lidar logs. NOT for raw-data import or multi-sensor sync/crop/offset/timestamp normalization — route those to matlab-driving-data-importer.
>
>
>
>
Build, modify, and diagram SimBiology models — API reference, helper functions, and layout patterns. Use when constructing or editing models programmatically or visually.