carsim-guide
VerifiedOperate and automate CarSim simulations from an agent, including safe output and parameter discovery, named Run Control execution contexts, structured overrides, isolated batch sweeps, dataset dependency inspection, control-mode selection, result validation, diagnostics, and version-aware CLI/Simulink/VS API routing. Use for executing, configuring, exploring, or debugging CarSim. Do not use for vehicle-dynamics theory alone, generic dataframe work, or unrelated simulators.
examples/simulink_cosim.py
View on GitHub#!/usr/bin/env python3
"""Runnable example: Simulink + CarSim closed-loop co-simulation, end to end.
Generates a co-sim simfile (steering import + 5 exports) with the normal
override workflow, builds & runs a Simulink PI yaw-rate controller around the
CarSim S-Function headless via `matlab -batch`, then verifies the tracking in
pandas. This is the demo behind references/simulink-cosim.md (verified:
0.00% steady-state error).
Usage:
python examples/simulink_cosim.py \
--prog "C:/CarSim/CarSim2024.0_Prog" \
--datadir "C:/CarSim/CarSim2024.0_Data" \
--base "C:/work/base/Run_all.par" \
--out "C:/work/cosim_demo" \
--matlab "C:/MATLAB/R2025b/bin/matlab.exe"
Requires: CarSim 2024.0 with license (GUI or cslm.exe), MATLAB R2023a+ with
Simulink, Python 3 + pandas.
"""
import argparse
import logging
import os
import subprocess
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)),
"..", "scripts"))
import carsim_batch as cb # noqa: E402
import pandas as pd # noqa: E402
logger = logging.getLogger("simulink_cosim")
EXTRA_LINES = [
"IMPORT IMP_STEER_SW REPLACE", # steering wheel angle [deg] from Simulink
"EXPORT Vx", # export order = declaration order
"EXPORT AVz", # [deg/s] -> element 2 (feedback signal)
"EXPORT Ay", # [g]
"EXPORT Yo", # [m]
"EXPORT Steer_SW", # [deg]
"PORTS_IMP 1,1", # <array #>,<count> -- never a single count
"PORTS_EXP 1,5",
]
TARGET_DEGS = 0.15 / 0.0174533 # 0.15 rad/s expressed in deg/s
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--prog", default=None, help="CarSim *_Prog directory "
"(default: setup_paths.py cache)")
ap.add_argument("--datadir", default=None, help="CarSim *_Data directory "
"(default: setup_paths.py cache)")
ap.add_argument("--base", default=None, help="GUI-expanded Run_all.par "
"(default: setup_paths.py cache)")
ap.add_argument("--out", required=True, help="work/output directory")
ap.add_argument("--matlab", default=None, help="path to matlab.exe "
"(default: cached by setup_paths.py)")
ap.add_argument("--tstop", type=float, default=30.0)
ap.add_argument("--verbose", action="store_true")
args = ap.parse_args()
args.prog, args.datadir, args.base = cb.resolve_paths(
args.prog, args.datadir, args.base)
args.matlab = args.matlab or cb.cached_paths().get("matlab")
if not args.matlab:
ap.error("--matlab not given and none in the setup_paths.py cache "
"(run setup_paths.py with MATLAB on PATH)")
logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO,
format="%(levelname)s %(name)s: %(message)s")
# 1) co-sim inputs via the normal override workflow
args.out = os.path.abspath(args.out)
os.makedirs(args.out, exist_ok=True)
simulation = cb.SimulationConfig(dt=0.001, duration=args.tstop)
sim_path = cb.make_scenario(
args.out, args.base, args.prog, args.datadir, config=simulation,
speed_rows=[(0, 50), (args.tstop, 50)],
steer_rows=[(0, 0), (args.tstop, 0)], unsafe_extra_lines=EXTRA_LINES)
with open(sim_path, encoding="utf-8") as source:
sim = source.read()
sim = sim.replace("PORTS_IMP 0", "PORTS_IMP 1,1")
sim = sim.replace("PORTS_EXP 0", "PORTS_EXP 1,5")
open(os.path.join(args.out, "simfile.sim"), "w", newline="\n", encoding="utf-8").write(sim)
logger.info("co-sim inputs written to %s", args.out)
# 2) build + run the Simulink model headless
solver_matlab = os.path.join(args.prog, "Programs", "solvers", "Matlab")
scripts_dir = os.path.dirname(cb.__file__)
cmd = [args.matlab, "-batch",
"addpath('%s'); addpath('%s'); cosim_model('%s', '%s', %.17g, %.17g)"
% (solver_matlab.replace("\\", "/"), scripts_dir.replace("\\", "/"),
args.out.replace("\\", "/"), solver_matlab.replace("\\", "/"),
simulation.duration, simulation.dt)]
logger.info("launching MATLAB ...")
proc = subprocess.run(cmd, capture_output=True, text=True,
timeout=900, encoding="utf-8", errors="replace")
combined = (proc.stdout or "") + (proc.stderr or "")
with open(os.path.join(args.out, "matlab_output.txt"), "w", encoding="utf-8") as log:
log.write(combined)
tail = "\n".join(combined.splitlines()[-20:])
logger.info("MATLAB tail:\n%s", tail)
if proc.returncode != 0 or "DONE" not in (proc.stdout or ""):
raise RuntimeError("MATLAB co-sim failed (returncode %s; see matlab_output.txt)" % proc.returncode)
# 3) verify in pandas (exports are in NATIVE CarSim units)
df = pd.read_csv(os.path.join(args.out, "cosim_results.csv"),
names=["t", "vx_kmh", "avz_degs", "ay_g", "yo_m",
"steersw_deg", "steer_cmd_deg"])
w = df[df.t.between(args.tstop / 3, args.tstop)]
err = abs(w.avz_degs.mean() - TARGET_DEGS) / TARGET_DEGS * 100
print("steady AVz = %.3f deg/s (target %.3f) -> error %.2f%%"
% (w.avz_degs.mean(), TARGET_DEGS, err))
print("Vx = %.2f km/h | steer = %.2f deg" % (w.vx_kmh.mean(),
w.steer_cmd_deg.mean()))
if err >= 2.0:
raise SystemExit("FAIL: tracking error %.2f%% >= 2%%" % err)
print("PASS: Simulink+CarSim closed loop verified")
if __name__ == "__main__":
sys.exit(main())
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |