Skip to content

zyfgi/carsim-guide-skill

carsim-guide

Verified

Operate 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.

FileKindSize
SKILL.mdskill md6.3 KB
examples/batches/friction_sweep.yamlconfig159 B
examples/batches/mass_friction_grid.yamlconfig198 B
examples/discovery/dataset_tree.pyscript693 B
examples/discovery/find_output.pyscript715 B
examples/discovery/find_parameter.pyscript761 B
examples/scenarios/basic_cruise.yamlconfig380 B
examples/scenarios/friction_change.yamlconfig379 B
examples/scenarios/steering_maneuver.yamlconfig377 B
examples/scenarios/tire_force_output.yamlconfig437 B
examples/scenarios/vehicle_override.yamlconfig376 B
examples/simulink_cosim.pyscript5.5 KB
examples/torque_vectoring.pyscript5.6 KB
references/advanced-controls.mdmarkdown4.0 KB
references/batch-workflows.mdmarkdown1.6 KB
references/compatibility.mdmarkdown1.4 KB
references/control-modes.mdmarkdown1.0 KB
references/database-exploration.mdmarkdown7.4 KB
references/dataset-syntax.mdmarkdown6.6 KB
references/outputs-and-units.mdmarkdown2.1 KB
references/parameter-discovery.mdmarkdown1.4 KB
references/parameters.mdmarkdown3.3 KB
references/python-interface.mdmarkdown7.9 KB
references/run-validation.mdmarkdown2.2 KB
references/scenarios.mdmarkdown3.3 KB
references/simulink-cosim.mdmarkdown4.0 KB
references/troubleshooting.mdmarkdown1.4 KB
references/version-compatibility.mdmarkdown811 B
references/vs-c-api.mdmarkdown3.3 KB
scripts/base_registry.pyscript4.7 KB
scripts/batch_runner.pyscript7.1 KB
scripts/carsim_batch.pyscript23.4 KB
scripts/carsim_errors.pyscript2.2 KB
scripts/control_modes.pyscript1.8 KB
scripts/cosim_model.mother4.7 KB
scripts/database_tools.pyscript16.5 KB
scripts/diagnose_run.pyscript444 B
scripts/diagnostics.pyscript6.9 KB
scripts/discovery_query.pyscript1.0 KB
scripts/dump_dll_exports.pyscript1.9 KB
scripts/output_registry.pyscript8.9 KB
scripts/override_registry.pyscript2.9 KB
scripts/parameter_discovery.pyscript8.6 KB
scripts/parameters.pyscript10.0 KB
scripts/result_contract.pyscript548 B
scripts/scenario_runner.pyscript11.3 KB
scripts/scenario_schema.pyscript4.0 KB
scripts/setup_paths.pyscript11.2 KB
scripts/tv_cosim.mother8.5 KB
scripts/validate_run.pyscript6.1 KB
scripts/version_compatibility.pyscript2.0 KB

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())
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: 472kUpdated Claude CodeCodexVerifiedInstall
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: 323kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 323kUpdated Claude CodeCodexVerifiedInstall
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 availableStars: 323kUpdated Claude CodeCodexVerifiedInstall