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/torque_vectoring.py

View on GitHub
#!/usr/bin/env python3
"""Runnable example: torque-vectoring co-simulation (4-motor EV, zero steer).

Generates a co-sim simfile with FOUR per-wheel motor-torque imports
(IMP_M_MOTOR_CMD_*) and four exports, then runs scripts/tv_cosim.m headless:
speed is held by a PI on total wheel torque, and a yaw-rate target is reached
PURELY by left/right torque vectoring (steering wheel stays at zero).
Verifies the yaw tracking in pandas.

Usage:
  python examples/torque_vectoring.py \
      --prog    "C:/CarSim/CarSim2024.0_Prog" \
      --datadir "C:/CarSim/CarSim2024.0_Data" \
      --base    "C:/work/base/Run_all.par" \
      --out     "C:/work/tv_demo" \
      --matlab  "C:/MATLAB/R2025b/bin/matlab.exe"
"""
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("torque_vectoring")

EXTRA_LINES = [
    # per-wheel motor torque commands, N.m at the wheels (verified 1:1 with
    # the My_Dr_* output channels); EXACT form of the official torque-vectoring
    # run control ("Add 0.0! 1" = GUI-native active form)
    "IMPORT IMP_M_MOTOR_CMD_D1_L Add 0.0! 1",
    "IMPORT IMP_M_MOTOR_CMD_D1_R Add 0.0! 1",
    "IMPORT IMP_M_MOTOR_CMD_D2_L Add 0.0! 1",
    "IMPORT IMP_M_MOTOR_CMD_D2_R Add 0.0! 1",
    "EXPORT Vx",        # km/h
    "EXPORT AVz",       # deg/s
    "EXPORT Yo",        # m
    "EXPORT Steer_SW",  # deg (stays 0 -- yaw comes from torque vectoring)
    "PORTS_IMP 1,4",    # <array #>,<count> -- never a single count
    "PORTS_EXP 1,4",
]
TARGET_DEGS = 0.06 / 0.0174533


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--prog", default=None,
                    help="CarSim *_Prog dir (default: setup_paths.py cache)")
    ap.add_argument("--datadir", default=None,
                    help="CarSim *_Data dir (default: setup_paths.py cache)")
    ap.add_argument("--base", default=None,
                    help="GUI-expanded Run_all.par (default: cache)")
    ap.add_argument("--out", required=True)
    ap.add_argument("--matlab", default=None,
                    help="path to matlab.exe (default: setup_paths.py cache)")
    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")

    args.out = os.path.abspath(args.out)
    os.makedirs(args.out, exist_ok=True)
    # OPT_SC 0: open loop (torque imports are the only drive); initial speed
    # from standstill, built up by the speed PI itself
    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, 0), (args.tstop, 0)],
        steer_rows=[(0, 0), (args.tstop, 0)], unsafe_extra_lines=EXTRA_LINES + ["OPT_SC 0"])
    with open(sim_path, encoding="utf-8") as source:
        sim = source.read()
    sim = sim.replace("PORTS_IMP 0", "PORTS_IMP 1,4")
    sim = sim.replace("PORTS_EXP 0", "PORTS_EXP 1,4")
    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)

    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'); tv_cosim('%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)

    df = pd.read_csv(os.path.join(args.out, "cosim_results.csv"),
                     names=["t", "vx_kmh", "avz_degs", "yo_m",
                            "steersw_deg", "tl", "tr"])
    w = df[df.t.between(args.tstop / 2, 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_SW = %.3f deg | T_L = %.0f, T_R = %.0f N.m"
          % (w.vx_kmh.mean(), w.steersw_deg.max(), w.tl.mean(), w.tr.mean()))
    if not (err < 5.0 and w.steersw_deg.abs().max() < 1e-6
            and w.vx_kmh.mean() > 40):
        raise SystemExit("FAIL: torque-vectoring yaw not achieved")
    print("PASS: yaw generated purely by torque vectoring at zero steering")


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