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

scripts/validate_run.py

View on GitHub
"""Core run validation: fresh artifacts, complete time grid, parameter echo.

check_run() reports structured issues (error / warning / info) instead of
raising; validate_run() is the compatibility wrapper that raises ValueError
on the first error and returns the legacy metrics dict. Failure semantics of
the previously field-validated checks are unchanged.
"""
from dataclasses import asdict, dataclass, field
import math
import re
from pathlib import Path

import numpy as np
import pandas as pd


@dataclass
class ValidationIssue:
    severity: str   # "error" | "warning" | "info"
    code: str
    message: str


@dataclass
class RunValidationResult:
    passed: bool
    issues: list = field(default_factory=list)
    metrics: dict = field(default_factory=dict)

    def errors(self):
        return [i for i in self.issues if i.severity == "error"]

    def warnings(self):
        return [i for i in self.issues if i.severity == "warning"]


def check_run(directory, simulation, required_channels, started_at=None,
              expected_parameters=None, minimum_speed_mps=None,
              solver_stdout=None):
    """Validate a finished run directory; never raises. Missing run.csv /
    run_echo short-circuit with a single error (nothing else can be checked)."""
    directory = Path(directory)
    issues = []

    def add(severity, code, message):
        issues.append(ValidationIssue(severity, code, message))

    paths = {"run_csv": directory / "run.csv", "run_echo": directory / "run_echo.par"}
    fatal = False
    for key, path in paths.items():
        if not path.is_file() or path.stat().st_size == 0:
            add("error", "missing_artifact", "Missing or empty result: %s" % path)
            fatal = True
        elif started_at is not None and path.stat().st_mtime < started_at:
            add("error", "stale_artifact", "Stale result: %s" % path)
            fatal = True
    if not fatal:
        metrics, fatal = _check_contents(directory, simulation, required_channels,
                                         expected_parameters, minimum_speed_mps, add)
    else:
        metrics = {}
    if solver_stdout is not None and "Termination at simulation time" not in solver_stdout:
        add("error", "solver_no_termination",
            "Solver output lacks 'Termination at simulation time'")
    if not (directory / "run_log.txt").is_file():
        add("warning", "missing_run_log", "run_log.txt absent; dataset provenance not recorded")
    return RunValidationResult(passed=not any(i.severity == "error" for i in issues),
                               issues=issues, metrics=metrics)


def _check_contents(directory, simulation, required_channels, expected_parameters,
                    minimum_speed_mps, add):
    df = pd.read_csv(directory / "run.csv")
    missing = set(["Time"] + list(required_channels)) - set(df.columns)
    if missing:
        add("error", "missing_channels", "Missing required channels: %s" % sorted(missing))
        return {}, True
    try:
        values = df.to_numpy(dtype=float)
    except (TypeError, ValueError) as exc:
        add("error", "non_numeric", "Non-numeric result: %s" % exc)
        return {}, True
    if not np.isfinite(values).all():
        add("error", "nonfinite_values", "Result contains NaN/inf")
        return {}, True
    t = df.Time.to_numpy(dtype=float)
    expected_count = round(simulation.duration / simulation.dt) + 1
    tolerance = max(1e-8, simulation.dt * 1e-4)
    if len(t) != expected_count:
        add("error", "sample_count", "Unexpected sample count: %s, expected %s"
            % (len(t), expected_count))
        return {}, True
    if not (np.diff(t) > 0).all() or not np.allclose(t, np.arange(expected_count) * simulation.dt,
                                                     atol=tolerance, rtol=0):
        add("error", "time_grid", "Time must be strictly increasing and match requested grid/TSTOP")
        return {}, True
    metrics = {"samples": len(t), "final_time_s": float(t[-1]),
               "minimum_speed_mps": minimum_speed_mps}
    echo = (directory / "run_echo.par").read_text(encoding="utf-8", errors="replace")
    actual = {}
    echo_ok = True
    for key, expectation in (expected_parameters or {}).items():
        if isinstance(expectation, dict):
            requested = expectation["value"]
            policy = expectation.get("echo_validation", "required")
        else:
            requested = expectation
            policy = "required"
        if policy == "none":
            continue
        matches = re.findall(r"^\s*" + re.escape(key) + r"\s+([-+0-9.eEdD]+)(?=\s|$)", echo, re.M)
        if not matches:
            severity = "error" if policy == "required" else "warning"
            add(severity, "echo_absent", "Parameter absent from echo: %s" % key)
            echo_ok = echo_ok and severity != "error"
            continue
        value = float(matches[-1].replace("D", "E").replace("d", "e"))
        if not math.isclose(value, requested, rel_tol=1e-6, abs_tol=1e-8):
            add("error", "echo_mismatch", "Echo mismatch %s: requested %s, actual %s"
                % (key, requested, value))
            echo_ok = False
            continue
        actual[key] = value
    metrics["echo_parameters"] = actual
    if minimum_speed_mps is not None:
        if "Vx" not in df or df.Vx.abs().max() / 3.6 < minimum_speed_mps:
            add("error", "movement_threshold",
                "Vehicle did not meet requested movement threshold")
            echo_ok = False
    return metrics, not echo_ok


def validate_run(directory, simulation, required_channels, started_at=None,
                 expected_parameters=None, minimum_speed_mps=None,
                 solver_stdout=None):
    """Compatibility wrapper: raise ValueError on the first error, return the
    legacy metrics dict (with passed=True) otherwise."""
    result = check_run(directory, simulation, required_channels, started_at,
                       expected_parameters, minimum_speed_mps, solver_stdout)
    if not result.passed:
        first = result.errors()[0]
        raise ValueError("%s: %s" % (first.code, first.message))
    return dict(result.metrics, passed=True, issues=[asdict(i) for i in result.issues])
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