mirror of
https://github.com/MaSzyna-EU07/maszyna.git
synced 2026-12-02 17:46:48 +01:00
919b4af043
* test(scenarios): AI through a section without voltage and with interlocked line contactors Scenario cases for the parts of #272 (line breaker ahead of the pantographs, PantRequiresMain) and #276 (line contactors interlocked with the vehicle's own converter, LineContactorsInterlock) that had not been run in the simulator before. They all run the AI on the timetable run of td.scn. - ep05_td_dead_section: an EP05 runs under power into a 61 m span of overhead wire that has no voltage. Its line breaker stays closed, the traction force drops to 0, and behind the span the AI takes power again and stops at Przystanek. eu07_td_dead_section is the same run with an EU07, as a reference for the old behaviour: its line breaker opens after 0.2 s and the AI closes it again. - ep05_td_neutral_section: the same span, with the track under it marked overhead 0. The AI coasts from before the dead wire. - ep05_td_section_insulator: a 1 m section insulator, run under power. The 0.2 s voltage hold keeps the traction force up past it. - et42_td_converter_interlock(_cold): an ET42 with the interlock starts up and runs its timetable. - ep05_td_interlock_dead_section_cold: both keys on one EP05, starting cold, with the dead span on its way. - ep05_td_timetable: the plain timetable run of the EP05, as a reference. The runner gets vehicle_variants, a vehicle of the case's own made from one of the game's with .fiz replacements. The game's ET42 data doesn't have the interlock key yet. The runner also gets two new checks: traction (the traction force between two distances travelled) and master_controller. The local converter switch of #276 can't be covered: only the cab can set it, and in test mode nobody sits in a cab. * feat(physics): the genset of a dual-mode vehicle, a second source of the traction circuit (GE#536) A vehicle with induction motors and pantographs can have a diesel generator set as well (Power: GensetPower and the other Genset* keys, Cntrl. GensetStart). The traction selector picks the source of the traction circuit: the catenary through the pantographs, as before, or the genset. It moves only with the line breaker open. - the genset starts on request with the battery on, cranks for GensetStartTime, then runs at idle and up to full revolutions with the traction demand; stopped, it coasts down. It gives its regulated voltage from the idle revolutions up. - on the genset the line breaker closes only on a running genset, the undervoltage trip works at half its voltage, the traction power is capped at the genset's power at its present revolutions times GensetPmaxRatio, braking sends nothing back, and the pantographs' pressure switch is left out. The genset's voltage goes to the train's high voltage line as the pantographs' does. - the commands TractionMode and GensetSwitch pass along the train and can come from a scenery's PutValues. Nothing changes without GensetPower: the selector stays on the catenary and every new branch is unreachable. The keys are ignored, with a line in the log, on a vehicle which isn't an induction motor one fed by pantographs. * feat(cab): the traction selector and the genset switch of a dual-mode vehicle (GE#536) New commands tractionmodetoggle, tractionmodecatenary, tractionmodegenset (shift+G toggles) and gensettoggle, gensetenable, gensetdisable (ctrl+G toggles), and the two-state cab switches tractionmode_sw: and genset_sw:. The selector switch doesn't move while the line breaker is closed. Both act on the whole train, as the fuel pump switch does. A cab without the switches works as before. * test: the genset of a dual-mode vehicle (GE#536) The game's E6ACT with the genset of the E6ACTad "last mile" set in the test (520 kW, the rest assumed): the keys and their defaults, the selector's interlock with the line breaker, the start, the power cap at the wheels, the revolutions following the demand, the stop opening the line breaker, the automatic start, the battery, the pantographs' pressure switch, braking with nothing sent back, the genset feeding the next car through the high voltage coupling, the commands along the train and from a scenery. A run from the catenary is the same, step for step, with the genset keys as without them. * test(scenarios): traction_power check, and an E6ACTad timetable run on its genset (GE#536) traction_power checks the power at the wheels, the traction force times the vehicle speed, against a ceiling and optionally a peak to reach. e6actad_genset_td_timetable runs the td/rozklad timetable with an E6ACTad switched to its genset by the scenery (PutValues from event0 of its track); e6actad_catenary_td_timetable is the same vehicle left on the catenary. Both need a temporary vehicle variant in the game's data, which the README describes; it isn't in the SVN. * test(scenarios): the genset cases make their own E6ACTad variant The two E6ACTad cases needed a vehicle variant placed in the game's dynamic/ by hand. They now make it for the run with vehicle_variants. vehicle_variants takes an optional fiz_from: a file to copy instead of the vehicle's own .fiz, named in full, while the .mmd still comes from "from". e6actad.fiz only includes e6acta.fiz.inc, and the genset keys can't go on a second Power: line after the include, which would load the power source again; so the variant is e6acta.fiz.inc with the keys added to its Cntrl. and Power: lines. Cases without fiz_from work as before. * fix(physics): the genset's traction current isn't taken from the wire (GE#536) On the genset the pantographs still handed the traction current to the wire and the energy meter, so a dual-mode vehicle under a wire loaded the substation while its genset did the work. The current now comes from CatenaryCurrent(): on the catenary the expression DynObj had, on the genset only a heating fed straight from the pantographs. A selector command refused with the line breaker closed is no longer passed down the train, and a car whose genset starts on its own passes the start switch on to the cars behind. The cab's genset switch moves only when the request was taken, so it no longer sticks on an automatic-start car.
1531 lines
79 KiB
Python
1531 lines
79 KiB
Python
#!/usr/bin/env python3
|
|
"""Scenario tests: run the real simulator on a scenery and check what a vehicle did.
|
|
|
|
A case (cases/<name>.json) names a base scenery from the game install, a fragment
|
|
added to it (usually a trainset with an AI driver), the result the simulator's test
|
|
mode should end with, and checks on the vehicle's physics log. The runner:
|
|
|
|
1. builds scenery/autotest_<case>.scn in the game dir: the base scenery with its own
|
|
trainsets removed, optionally a different start time, and the case fragment added,
|
|
2. starts eu07 in test mode (--test: every train driven by AI, nothing drawn, fixed
|
|
time steps as fast as it can) with that scenery and an extra settings file (-ini)
|
|
that turns on physicslog,
|
|
3. waits until the simulator quits by itself and reads the test result from its exit
|
|
code: pass, fail, signal passed at danger, timeout (after `duration` seconds of
|
|
simulation, if the case gives one), standstill or error,
|
|
4. compares the result with the one the case expects, evaluates the checks on the
|
|
physicslog and prints PASS/FAIL per check.
|
|
|
|
Scenery and vehicle data are not part of this repo, so this runs against a local game
|
|
install only (--game-dir or EU07_GAME_DIR), not in CI. See README.md.
|
|
|
|
Usage:
|
|
python tests/scenarios/run.py --game-dir "E:/.../MaSzyna" -j 4 # all cases
|
|
python tests/scenarios/run.py --game-dir ... eu07_td_timetable # chosen cases
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import heapq
|
|
import json
|
|
import math
|
|
import os
|
|
import re
|
|
import shutil
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
|
|
HERE = Path(__file__).resolve().parent
|
|
REPO = HERE.parents[1]
|
|
CASES_DIR = HERE / "cases"
|
|
OUT_DIR = HERE / "out"
|
|
|
|
# physicslog columns, see TController::PhysicsLog() in vehicle/Driver.cpp.
|
|
# Velocity is in km/h and pressures in bar, despite the header saying m/s and MPa.
|
|
COL_TIME = 0
|
|
COL_VELOCITY = 1 # wheel speed: stays at 0 while the wheels are locked in a skid
|
|
COL_TRACTION_FORCE = 5 # N, despite the header saying kN
|
|
COL_BRAKE_PRESS = 8
|
|
COL_MASTER_CONTROLLER = 11 # the position of the master controller
|
|
COL_COMMAND = 16 # text, read as None
|
|
COL_WHEELSLIP = 20
|
|
COL_VEHICLE_VELOCITY = 25 # signed vehicle speed, km/h; only in builds which log it
|
|
|
|
# exit codes of the simulator's test mode (eu07 --test), see simulation/simulationtestrules.h
|
|
EXIT_RESULTS = {
|
|
0: "pass",
|
|
10: "fail",
|
|
11: "signal_passed_at_danger",
|
|
12: "timeout",
|
|
13: "standstill",
|
|
14: "error",
|
|
}
|
|
# the timeout of the simulator's real time watchdog (test.wall_timeout) has the timeout code too; told
|
|
# apart by its verdict, so a run that hung doesn't pass a case that expects the simulation time to run out
|
|
WALL_TIMEOUT = "wall_timeout"
|
|
RESULTS = (*EXIT_RESULTS.values(), WALL_TIMEOUT)
|
|
|
|
# settings layered over the game's eu07.ini for a test run (test mode doesn't read the player's own
|
|
# in %APPDATA%); the window ones only matter
|
|
# with --watch, test mode keeps its window hidden and turns the sound off by itself
|
|
TEST_INI = """\
|
|
fullscreen no
|
|
fullscreenwindowed no
|
|
width 1280
|
|
height 720
|
|
inactivepause no
|
|
soundenabled no
|
|
convertmodels 0
|
|
physicslog {physicslog}
|
|
multiplelogs yes
|
|
timespeed {timespeed}
|
|
"""
|
|
# multiplelogs: log and errors go to logs/log (<scenery>) <date>.txt instead of the shared
|
|
# log.txt, so runs of different cases can go in parallel
|
|
# convertmodels 0: a test run writes no converted models (.e3d) into the game dir
|
|
|
|
|
|
# ---------------------------------------------------------------- scenery
|
|
|
|
|
|
def split_trainsets(text: str) -> tuple[str, str]:
|
|
"""Splits text into (everything else, the trainset ... endtrainset blocks)."""
|
|
rest, trainsets = [], []
|
|
inside = False
|
|
for line in text.splitlines(keepends=True):
|
|
tokens = line.split("//", 1)[0].split()
|
|
if not inside and tokens and tokens[0].lower() == "trainset":
|
|
inside = True
|
|
if inside:
|
|
trainsets.append(line)
|
|
if any(t.lower() == "endtrainset" for t in tokens):
|
|
inside = False
|
|
continue
|
|
rest.append(line)
|
|
return "".join(rest), "".join(trainsets)
|
|
|
|
|
|
def set_start_time(text: str, hhmm: str) -> str:
|
|
return re.sub(r"(?im)^(\s*time\s+)\d{1,2}:\d{2}", lambda m: m.group(1) + hhmm, text, count=1)
|
|
|
|
|
|
def add_track_events(text: str, events: dict) -> str:
|
|
"""Adds lines (e.g. "event0 test_pass") to tracks named in events, before their endtrack."""
|
|
for track, lines in events.items():
|
|
lines = [lines] if isinstance(lines, str) else lines
|
|
m = re.search(rf"(?im)^\s*node\s+\S+\s+\S+\s+{re.escape(track)}\s+track\b.*?^(\s*endtrack\b)", text, re.S)
|
|
if not m:
|
|
sys.exit(f"track_events: no track {track} in the base scenery itself (not in its includes)")
|
|
text = text[: m.start(1)] + "".join(line + "\n" for line in lines) + text[m.start(1):]
|
|
return text
|
|
|
|
|
|
def set_track_friction(text: str, friction: float) -> str:
|
|
"""Sets the friction of every track: node <range> <range> <name> track <type> <length> <gauge> <friction> ..."""
|
|
return re.sub(r"(?im)^(\s*node\s+\S+\s+\S+\s+\S+\s+track\s+\S+\s+\S+\s+\S+\s+)[-\d.]+",
|
|
lambda m: m.group(1) + f"{friction}", text)
|
|
|
|
|
|
def fill_vars(fragment: str, values: dict, keep=frozenset()) -> str:
|
|
"""Replaces {{name}} with the case's value; a list value becomes one line per item."""
|
|
def value(m):
|
|
if m.group(1) in keep:
|
|
return m.group(0)
|
|
v = values.get(m.group(1))
|
|
if v is None:
|
|
sys.exit(f"fragment uses {{{{{m.group(1)}}}}} but the case sets no such var")
|
|
return "\n".join(v) if isinstance(v, list) else str(v)
|
|
return re.sub(r"\{\{(\w+)\}\}", value, fragment)
|
|
|
|
|
|
def scenery_cache(game_dir: Path, case_name: str) -> Path:
|
|
"""The simulator's geometry cache of the case scenery."""
|
|
return game_dir / "scenery" / f"autotest_{case_name}.sbt"
|
|
|
|
|
|
def timetable_name(case_name: str) -> str:
|
|
"""The case's own timetable as a trainset names it: {{timetable}} in the fragment."""
|
|
return f"autotest_{case_name}"
|
|
|
|
|
|
def timetable_path(game_dir: Path, case_name: str) -> Path:
|
|
return game_dir / "scenery" / f"{timetable_name(case_name)}.txt"
|
|
|
|
|
|
def variant_name(case_name: str, name: str) -> str:
|
|
"""A vehicle variant of the case as a trainset names it: {{variant_<name>}} in the fragment."""
|
|
return f"autotest_{case_name}_{name}"
|
|
|
|
|
|
def variant_paths(game_dir: Path, case_name: str, variant: dict) -> list[Path]:
|
|
"""The .fiz and .mmd of a vehicle variant of the case, beside those of the vehicle it is made from."""
|
|
folder = (game_dir / "dynamic" / variant["from"]).parent
|
|
return [folder / f"{variant_name(case_name, variant['name'])}{suffix}" for suffix in (".fiz", ".mmd")]
|
|
|
|
|
|
def write_vehicle_variants(case: dict, game_dir: Path, case_name: str) -> None:
|
|
"""Writes the case's vehicle variants into the game's dynamic/ dir: a copy of a vehicle's .fiz with the
|
|
case's replacements, e.g. a .fiz key the shipped data doesn't have yet, and a copy of its .mmd. The
|
|
simulator hands the .mmd its type name as (p2), which some pass on to the include that names the
|
|
model (et42_v2: `include 112e-a.mmd.inc (p2) end`, `models: (p1).t3d`), so the copy has the name of
|
|
the vehicle it is made from in place of (p2) and looks and loads as that one does."""
|
|
files = {}
|
|
for variant in case.get("vehicle_variants", []):
|
|
source = game_dir / "dynamic" / variant["from"]
|
|
# the .fiz to copy: the vehicle's own, or another file named in full (fiz_from), e.g. the .fiz.inc a
|
|
# vehicle's .fiz only includes, as keys added after the include on a second line of the same section
|
|
# would load that section again
|
|
fiz_source = game_dir / "dynamic" / variant["fiz_from"] if "fiz_from" in variant else source.with_name(source.name + ".fiz")
|
|
fiz_name = variant.get("fiz_from", f"{variant['from']}.fiz")
|
|
# .fiz files are cp1250 like the sceneries; latin-1 round-trips every byte
|
|
fiz = fiz_source.read_bytes().decode("latin-1")
|
|
for old, new in variant.get("replace", []):
|
|
if old not in fiz:
|
|
sys.exit(f"vehicle_variants: {fiz_name} has no {old!r}")
|
|
fiz = fiz.replace(old, new)
|
|
mmd = source.with_name(source.name + ".mmd").read_bytes().decode("latin-1").replace("(p2)", source.name)
|
|
fiz_path, mmd_path = variant_paths(game_dir, case_name, variant)
|
|
files[fiz_path], files[mmd_path] = fiz, mmd
|
|
# written once every variant is made, so a case with a wrong replacement leaves nothing in the game dir
|
|
for path, text in files.items():
|
|
path.write_bytes(text.encode("latin-1"))
|
|
|
|
|
|
def remove_vehicle_variants(case: dict, game_dir: Path, case_name: str) -> None:
|
|
for variant in case.get("vehicle_variants", []):
|
|
for path in variant_paths(game_dir, case_name, variant):
|
|
path.unlink(missing_ok=True)
|
|
|
|
|
|
def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> str:
|
|
"""Writes the case scenery into the game's scenery dir and returns its file name."""
|
|
scenery_dir = game_dir / "scenery"
|
|
# sceneries are cp1250; latin-1 round-trips every byte, so nothing gets mangled
|
|
text = (scenery_dir / case["base_scenery"]).read_bytes().decode("latin-1")
|
|
if case.get("strip_trainsets", True):
|
|
text, _ = split_trainsets(text)
|
|
if "time" in case:
|
|
text = set_start_time(text, case["time"])
|
|
if "track_friction" in case:
|
|
text = set_track_friction(text, case["track_friction"])
|
|
if "track_events" in case:
|
|
text = add_track_events(text, case["track_events"])
|
|
for old, new in case.get("replace", []):
|
|
if old not in text:
|
|
sys.exit(f"replace: the base scenery has no {old!r}")
|
|
text = text.replace(old, new)
|
|
# a case on a mission of the base scenery may have nothing to add but its test_config
|
|
fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1") if "fragment" in case else ""
|
|
# vars first: {{vehicle}} and {{timetable}} inside a var's value get filled in the second pass
|
|
variants = {f"variant_{v['name']}": variant_name(case_name, v["name"]) for v in case.get("vehicle_variants", [])}
|
|
fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle", "timetable", *variants})
|
|
fragment = fill_vars(fragment, {"vehicle": vehicle, "timetable": timetable_name(case_name), **variants})
|
|
# FirstInit binds event launchers to their events and links the tracks. so launchers and
|
|
# events of the case go in before it (read after it they never fire), trainsets after it
|
|
# (placed before it they stand on unlinked track and derail at once)
|
|
before, trainsets = split_trainsets(fragment)
|
|
# settings of the test mode, read like any other config block: the case's vehicle is the train under test,
|
|
# whose consist the pass and the standstill wait for, and the case's own (test.timeout and so on)
|
|
config = [f"test.vehicle {vehicle}", *case.get("test_config", [])]
|
|
before = "config\n" + "".join(line + "\n" for line in config) + "endconfig\n" + before
|
|
header = f"\n// ---- autotest: {case_name} ----\n"
|
|
firstinit = re.search(r"(?im)^\s*firstinit\b", text)
|
|
if firstinit:
|
|
text = text[: firstinit.start()] + header + before + "\n" + text[firstinit.start():]
|
|
else:
|
|
text += header + before + "\n"
|
|
text += header + trainsets + "\n"
|
|
# vehicles of the case's own, made from those of the game
|
|
write_vehicle_variants(case, game_dir, case_name)
|
|
name = f"autotest_{case_name}.scn"
|
|
(scenery_dir / name).write_bytes(text.encode("latin-1"))
|
|
# a timetable of the case's own, for a train whose timetable the sceneries of the game have none like
|
|
if "timetable" in case:
|
|
shutil.copyfile(CASES_DIR / case["timetable"], timetable_path(game_dir, case_name))
|
|
# the simulator caches the scenery's static geometry in <name>.sbt and reads it instead of
|
|
# the terrain in the .scn (tracks, events and trainsets always come from the .scn), so
|
|
# drop the cache once the base scenery, or the fragment of the case (its own terrain), has changed
|
|
cache = scenery_cache(game_dir, case_name)
|
|
sources = [scenery_dir / case["base_scenery"]] + ([CASES_DIR / case["fragment"]] if "fragment" in case else [])
|
|
if cache.exists() and cache.stat().st_mtime < max(source.stat().st_mtime for source in sources):
|
|
cache.unlink()
|
|
return name
|
|
|
|
|
|
# ---------------------------------------------------------------- run
|
|
|
|
|
|
def read_physicslog(path: Path) -> list[list[float]]:
|
|
"""Returns rows of columns, None for the text ones; skips the header and partial lines."""
|
|
rows = []
|
|
try:
|
|
lines = path.read_text(errors="replace").splitlines()
|
|
except FileNotFoundError:
|
|
return rows
|
|
for line in lines[1:]:
|
|
parts = line.split()
|
|
if len(parts) <= COL_BRAKE_PRESS:
|
|
continue # line still being written
|
|
try:
|
|
row = [float(p) for p in parts[: COL_BRAKE_PRESS + 1]]
|
|
except ValueError:
|
|
continue
|
|
for p in parts[COL_BRAKE_PRESS + 1:]:
|
|
try:
|
|
row.append(float(p))
|
|
except ValueError:
|
|
row.append(None)
|
|
rows.append(row)
|
|
return rows
|
|
|
|
|
|
def find_logs(game_dir: Path, scenery: str, since: float) -> dict[str, Path]:
|
|
"""The log.txt / errors.txt of one run; with multiplelogs each scenery gets its own files."""
|
|
stem = scenery.rsplit(".", 1)[0]
|
|
found = {}
|
|
for kind in ("log", "errors"):
|
|
files = [p for p in (game_dir / "logs").glob(f"{kind} ({stem}) *.txt") if p.stat().st_mtime >= since]
|
|
if files:
|
|
found[kind] = max(files, key=lambda p: p.stat().st_mtime)
|
|
return found
|
|
|
|
|
|
def read_text(path: Path | None) -> str:
|
|
try:
|
|
return path.read_text(errors="replace") if path else ""
|
|
except FileNotFoundError:
|
|
return ""
|
|
|
|
|
|
# the black box of a run, see blackbox_doc.md: written along with the physicslogs, to
|
|
# physicslog/<scenery>_<date>.blackbox. A header, then records: a byte of the kind, the length, the content
|
|
BLACKBOX_MAGIC = b"EU07BBX\0"
|
|
BLACKBOX_HEADER = 12 # the magic, the version of the format, two bytes reserved
|
|
BLACKBOX_TRACK = 0x10 # the map: a rail track, or one way of a switch, as points along it
|
|
BLACKBOX_VEHICLE = 0x12 # a vehicle: its number and its name
|
|
BLACKBOX_VEHICLES = 0x21 # once a second: the vehicles which moved, changed speed or got another driver
|
|
BLACKBOX_COUPLING = 0x37 # a coupler of a vehicle coupled, uncoupled, or its hoses and cables changed
|
|
BLACKBOX_DERAILMENT = 0x38 # a vehicle left the track, or came to rest off it (physics.derailment new)
|
|
DERAILMENT_CAUSES = {1: "flange climbed", 2: "overturned", 3: "end of track", 4: "pulled off", 5: "collision"}
|
|
COUPLING_COUPLER = 0x01 # of the bits telling what is coupled: the coupler itself
|
|
BLACKBOX_DRIVERS = {"none": 0, "user": 1, "ai": 2} # the driver byte of a vehicle state
|
|
|
|
|
|
@dataclass
|
|
class Coupling:
|
|
"""A coupling record: what a coupler of a vehicle is coupled to from `time` on."""
|
|
time: float
|
|
vehicle: int # vehicles by their numbers, 0 for none
|
|
side: int # 0 the front coupler, 1 the rear one
|
|
other: int
|
|
other_side: int
|
|
flags: int # what is coupled, 0 nothing
|
|
previous_flags: int
|
|
previous_other: int
|
|
|
|
|
|
@dataclass
|
|
class VehicleState:
|
|
"""A vehicle in a `vehicles` record: where it is and who drives it from `time` on, until its next one."""
|
|
time: float
|
|
position: tuple[float, float, float]
|
|
speed: float # km/h, positive along its front
|
|
driver: int # 0 none, 1 a user, 2 the AI
|
|
|
|
|
|
@dataclass
|
|
class Derailment:
|
|
"""A derailment record: a vehicle off the track as it left it (phase 0) or came to rest (phase 1)."""
|
|
time: float
|
|
vehicle: int
|
|
phase: int
|
|
cause: int # DERAILMENT_CAUSES
|
|
position: tuple[float, float, float]
|
|
heading: float # rad
|
|
speed: float # km/h
|
|
offset: float # m from the axis of the track, to the left of its front positive
|
|
roll: float # rad, to the left positive
|
|
travelled: float # m on the ground since it left the rails
|
|
lying: bool
|
|
|
|
|
|
@dataclass
|
|
class Track:
|
|
"""A `track` record: a plain track, or one way of a switch (several records under the number of the switch)."""
|
|
number: int
|
|
name: str
|
|
kind: int # 0 a plain track, 1 a way of a switch
|
|
branch: int # the switch position this way is taken in
|
|
points: list[tuple[float, float, float]]
|
|
|
|
|
|
@dataclass
|
|
class Blackbox:
|
|
vehicles: dict[int, str] = field(default_factory=dict) # names by number
|
|
tracks: list[Track] = field(default_factory=list) # the map, in the order written
|
|
couplings: list[Coupling] = field(default_factory=list) # in the order written
|
|
derailments: list[Derailment] = field(default_factory=list) # in the order written
|
|
states: dict[int, list[VehicleState]] = field(default_factory=dict) # of each vehicle by number, in time order
|
|
end_time: float = 0.0 # of the last `vehicles` record
|
|
|
|
|
|
def find_blackbox(game_dir: Path, scenery: str, since: float) -> Path | None:
|
|
"""The black box of one run: the simulator names it after the scenery and the time it started."""
|
|
stem = re.sub(r"[^0-9A-Za-z_-]", "_", scenery.rsplit(".", 1)[0])
|
|
# the whole name, so a case whose name another one starts with doesn't take that one's file
|
|
name = re.compile(re.escape(stem) + r"_\d{4}-\d\d-\d\d_\d\d-\d\d-\d\d\.blackbox")
|
|
files = [p for p in (game_dir / "physicslog").glob(f"{stem}_*.blackbox")
|
|
if name.fullmatch(p.name) and p.stat().st_mtime >= since]
|
|
return max(files, key=lambda p: p.stat().st_mtime, default=None)
|
|
|
|
|
|
def _blackbox_text(content: bytes, start: int) -> tuple[str, int]:
|
|
"""A text of a black box record at `start`, and where the field after it begins."""
|
|
# its length in 7 bit groups, low first, the high bit set on all but the last
|
|
size, shift = 0, 0
|
|
while True:
|
|
byte = content[start]
|
|
start += 1
|
|
size |= (byte & 0x7F) << shift
|
|
shift += 7
|
|
if byte < 0x80:
|
|
break
|
|
return content[start: start + size].decode("utf-8", errors="replace"), start + size
|
|
|
|
|
|
def read_blackbox(path: Path | None) -> Blackbox | None:
|
|
"""The map, the vehicles and the coupling records of a black box; None when there is none or it can't be read."""
|
|
try:
|
|
data = path.read_bytes() if path else b""
|
|
except FileNotFoundError:
|
|
return None
|
|
if data[:len(BLACKBOX_MAGIC)] != BLACKBOX_MAGIC:
|
|
return None
|
|
box = Blackbox()
|
|
at = BLACKBOX_HEADER
|
|
try:
|
|
while at + 5 <= len(data):
|
|
kind, length = struct.unpack_from("<BI", data, at)
|
|
content = data[at + 5: at + 5 + length]
|
|
if len(content) < length:
|
|
break # a record still being written when the run ended
|
|
at += 5 + length
|
|
if kind == BLACKBOX_VEHICLE:
|
|
number, = struct.unpack_from("<I", content)
|
|
box.vehicles[number], _ = _blackbox_text(content, 4)
|
|
elif kind == BLACKBOX_TRACK:
|
|
# the number, the name, the kind, the switch position of the way, the category, the points
|
|
number, = struct.unpack_from("<I", content)
|
|
name, start = _blackbox_text(content, 4)
|
|
track_kind, branch, _, count = struct.unpack_from("<BBBI", content, start)
|
|
points = [struct.unpack_from("<3f", content, start + 7 + 12 * i) for i in range(count)]
|
|
box.tracks.append(Track(number, name, track_kind, branch, points))
|
|
elif kind == BLACKBOX_VEHICLES:
|
|
# the time, a keyframe mark, the count, then 25 bytes a vehicle: number, position, heading, speed, driver
|
|
when, _, count = struct.unpack_from("<dBI", content)
|
|
box.end_time = when
|
|
for i in range(count):
|
|
number, x, y, z, _, speed, driver = struct.unpack_from("<I3fffB", content, 13 + 25 * i)
|
|
box.states.setdefault(number, []).append(VehicleState(when, (x, y, z), speed, driver))
|
|
elif kind == BLACKBOX_COUPLING:
|
|
# the position of the coupler follows
|
|
box.couplings.append(Coupling(*struct.unpack_from("<dIBIBBBI", content)))
|
|
elif kind == BLACKBOX_DERAILMENT:
|
|
when, number, phase, cause, x, y, z, heading, speed, offset, roll, travelled, lying = \
|
|
struct.unpack_from("<dIBB3dfffffB", content)
|
|
box.derailments.append(Derailment(when, number, phase, cause, (x, y, z), heading, speed, offset, roll,
|
|
travelled, bool(lying)))
|
|
except (struct.error, IndexError):
|
|
return None # a record shorter than its kind is
|
|
return box
|
|
|
|
|
|
# load problems that leave the case without its vehicle; no point waiting for the timeout
|
|
FATAL_LOG_LINES = ("Bad vehicle:", "Bad trainset:")
|
|
# wall seconds from start to the first physicslog row before giving up. "Scenario loading
|
|
# time" in the log is not the end of loading (the trainsets after FirstInit still follow),
|
|
# and with several simulators loading at once the first rows took well over 15 s
|
|
STARTUP_TIMEOUT = 120.0
|
|
# wall seconds past a case's timeout before the runner kills a simulator that didn't end itself
|
|
KILL_GRACE = 30.0
|
|
|
|
|
|
@dataclass
|
|
class RunResult:
|
|
rows: list[list[float]] = field(default_factory=list)
|
|
exit_code: int | None = None # None: still running when we closed it (the normal end with --watch)
|
|
verdict: str = "" # the simulator's own line about the test result
|
|
failure: str = "" # why the run was cut short
|
|
wall_seconds: float = 0.0
|
|
logs: dict[str, Path] = field(default_factory=dict)
|
|
blackbox: Path | None = None
|
|
|
|
|
|
def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog: Path,
|
|
duration: float | None, timeout: float, watch: bool, say, expect_rows: bool = True) -> RunResult:
|
|
"""Runs the simulator on the scenery. In test mode it quits by itself and the exit code
|
|
is the result; with watch it runs in a window and gets closed after `duration`."""
|
|
physicslog.unlink(missing_ok=True)
|
|
if watch:
|
|
cmd = [str(exe), "-s", scenery, "-v", "ghostview", "-ini", str(ini)]
|
|
else:
|
|
# the simulator's own watchdog ends a run that takes too long, with the timeout code and its verdict
|
|
cmd = [str(exe), "--test", "-s", scenery, "-ini", str(ini), "--test-wall-timeout", f"{timeout:g}"]
|
|
if duration is not None:
|
|
cmd += ["--test-timeout", f"{duration:g}"]
|
|
say(" $ " + " ".join(f'"{c}"' if " " in c else c for c in cmd), progress=True)
|
|
since = time.time() - 1
|
|
started = time.monotonic()
|
|
# the test result line goes to stdout; a file, not a pipe, so a chatty run can't block on it
|
|
stdout = (ini.parent / "stdout.txt").open("w+b")
|
|
proc = subprocess.Popen(cmd, cwd=game_dir, stdout=stdout, stderr=subprocess.STDOUT)
|
|
result = RunResult()
|
|
last_report = 0.0
|
|
try:
|
|
while True:
|
|
time.sleep(0.25) # at timespeed 20 that is 5 s of simulation
|
|
wall = time.monotonic() - started
|
|
# the whole file is read each time: in test mode, once there are rows, only for the progress line
|
|
if watch or not result.rows or wall - last_report >= 15:
|
|
result.rows = read_physicslog(physicslog)
|
|
sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0
|
|
if wall - last_report >= 15:
|
|
v = result.rows[-1][COL_VELOCITY] if result.rows else 0.0
|
|
say(f" ... {wall:5.0f}s wall, sim {sim_t:6.1f}s, v={v:6.1f} km/h", progress=True)
|
|
last_report = wall
|
|
if proc.poll() is not None:
|
|
result.exit_code = proc.returncode
|
|
break
|
|
if watch and sim_t >= duration:
|
|
break
|
|
# in test mode a little later than the simulator's own limit, for a run that can't even end itself
|
|
if wall > timeout + (0 if watch else KILL_GRACE):
|
|
result.failure = f"timed out after {wall:.0f}s before {duration}s of simulation"
|
|
break
|
|
# not for a case with physicslog off, which has no rows to wait for, nor for one on a mission of the
|
|
# base scenery: a big scenery loads for minutes, and a bad vehicle among its decorations isn't the
|
|
# case's (a missing test vehicle ends the test mode with `error` by itself)
|
|
if expect_rows and not result.rows:
|
|
result.logs = find_logs(game_dir, scenery, since)
|
|
fatal = [l.strip() for l in read_text(result.logs.get("errors")).splitlines()
|
|
if any(k in l for k in FATAL_LOG_LINES)]
|
|
if fatal:
|
|
result.failure = "vehicle failed to load: " + " | ".join(fatal)
|
|
break
|
|
if wall > STARTUP_TIMEOUT:
|
|
result.failure = f"no physicslog rows after {STARTUP_TIMEOUT:.0f}s"
|
|
break
|
|
finally:
|
|
if proc.poll() is None:
|
|
proc.terminate()
|
|
try:
|
|
proc.wait(timeout=10)
|
|
except subprocess.TimeoutExpired:
|
|
proc.kill()
|
|
result.wall_seconds = time.monotonic() - started
|
|
stdout.seek(0)
|
|
result.verdict = next((line.strip() for line in stdout.read().decode(errors="replace").splitlines()
|
|
if line.startswith("test:")), "")
|
|
stdout.close()
|
|
result.rows = read_physicslog(physicslog)
|
|
result.logs = find_logs(game_dir, scenery, since)
|
|
result.blackbox = find_blackbox(game_dir, scenery, since)
|
|
return result
|
|
|
|
|
|
# ---------------------------------------------------------------- checks
|
|
|
|
|
|
def check_starts(rows, min_speed, within, after=None):
|
|
for r in rows:
|
|
if r[COL_TIME] > within:
|
|
break
|
|
if r[COL_VELOCITY] >= min_speed:
|
|
# a case can also say the train mustn't leave before something it waits for (a converter starting)
|
|
if after is not None and r[COL_TIME] < after:
|
|
return False, f"reached {min_speed} km/h at t={r[COL_TIME]:.1f}s, before {after}s"
|
|
return True, f"reached {min_speed} km/h at t={r[COL_TIME]:.1f}s"
|
|
top = max((r[COL_VELOCITY] for r in rows if r[COL_TIME] <= within), default=0.0)
|
|
return False, f"top speed in the first {within}s was {top:.1f} km/h, wanted {min_speed}"
|
|
|
|
|
|
def check_max_speed(rows, limit, tolerance=0.0):
|
|
worst = max(rows, key=lambda r: r[COL_VELOCITY])
|
|
v, t = worst[COL_VELOCITY], worst[COL_TIME]
|
|
ok = v <= limit + tolerance
|
|
return ok, f"top speed {v:.1f} km/h at t={t:.1f}s (limit {limit} +{tolerance})"
|
|
|
|
|
|
def _first_moving(rows, moving_speed):
|
|
return next((i for i, r in enumerate(rows) if r[COL_VELOCITY] >= moving_speed), None)
|
|
|
|
|
|
def _distances(rows):
|
|
"""Metres travelled up to each row, from the speed; the physicslog has no position."""
|
|
out, d = [0.0], 0.0
|
|
for a, b in zip(rows, rows[1:]):
|
|
d += (a[COL_VELOCITY] + b[COL_VELOCITY]) / 2 / 3.6 * (b[COL_TIME] - a[COL_TIME])
|
|
out.append(d)
|
|
return out
|
|
|
|
|
|
def check_brakes(rows, min_pressure, moving_speed=20):
|
|
start = _first_moving(rows, moving_speed)
|
|
if start is None:
|
|
return False, "never moved, so never braked"
|
|
for r in rows[start:]:
|
|
if r[COL_BRAKE_PRESS] >= min_pressure:
|
|
return True, f"brake cylinder {r[COL_BRAKE_PRESS]:.2f} bar at t={r[COL_TIME]:.1f}s, v={r[COL_VELOCITY]:.1f} km/h"
|
|
return False, f"brake cylinder pressure never reached {min_pressure} bar after moving off"
|
|
|
|
|
|
def check_stops(rows, moving_speed, stop_speed, hold, min_distance=None, max_distance=None, max_time=None, nth=1):
|
|
"""The nth stop of `hold` seconds after moving off at `moving_speed` (each stop after the first counts once the
|
|
train is moving at `moving_speed` again)."""
|
|
start = _first_moving(rows, moving_speed)
|
|
if start is None:
|
|
return False, f"never reached {moving_speed} km/h"
|
|
dist = _distances(rows)
|
|
stopped_at = None
|
|
held = 0
|
|
moving = True
|
|
for i in range(start, len(rows)):
|
|
r = rows[i]
|
|
if not moving:
|
|
moving = r[COL_VELOCITY] >= moving_speed
|
|
continue
|
|
if r[COL_VELOCITY] <= stop_speed:
|
|
if stopped_at is None:
|
|
stopped_at = i
|
|
if r[COL_TIME] - rows[stopped_at][COL_TIME] >= hold:
|
|
held += 1
|
|
if held < nth:
|
|
stopped_at = None
|
|
moving = False
|
|
continue
|
|
where = dist[stopped_at]
|
|
when = rows[stopped_at][COL_TIME]
|
|
detail = f"came to a stop at t={when:.1f}s after {where:.0f} m"
|
|
if (min_distance is not None and where < min_distance) or (max_distance is not None and where > max_distance):
|
|
return False, f"{detail}, wanted between {min_distance} and {max_distance} m"
|
|
if max_time is not None and when > max_time:
|
|
return False, f"{detail}, wanted by t={max_time}s"
|
|
return True, detail
|
|
else:
|
|
stopped_at = None
|
|
if held:
|
|
return False, f"stopped {held} times for {hold}s after moving off, wanted stop {nth}"
|
|
return False, f"did not stay below {stop_speed} km/h for {hold}s after moving off"
|
|
|
|
|
|
def check_stays_stopped(rows, moving_speed, stop_speed):
|
|
"""Once stopped after moving off, never moves again (e.g. waiting at a red signal)."""
|
|
start = _first_moving(rows, moving_speed)
|
|
if start is None:
|
|
return False, f"never reached {moving_speed} km/h"
|
|
stop = next((i for i in range(start, len(rows)) if rows[i][COL_VELOCITY] <= stop_speed), None)
|
|
if stop is None:
|
|
return False, f"never came down to {stop_speed} km/h"
|
|
moved = next((r for r in rows[stop:] if r[COL_VELOCITY] > stop_speed), None)
|
|
if moved is not None:
|
|
return False, f"stopped at t={rows[stop][COL_TIME]:.1f}s but moved again at t={moved[COL_TIME]:.1f}s, v={moved[COL_VELOCITY]:.1f} km/h"
|
|
return True, f"stopped at t={rows[stop][COL_TIME]:.1f}s and stayed until t={rows[-1][COL_TIME]:.1f}s"
|
|
|
|
|
|
def check_distance(rows, max=None, min=None):
|
|
"""Total distance travelled, in metres."""
|
|
d = _distances(rows)[-1]
|
|
ok = (max is None or d <= max) and (min is None or d >= min)
|
|
bounds = " ".join(s for s in (f">= {min}" if min is not None else "", f"<= {max}" if max is not None else "") if s)
|
|
return ok, f"travelled {d:.0f} m (wanted {bounds})"
|
|
|
|
|
|
def check_slips(rows, within=None):
|
|
"""The lead vehicle's wheels slip (or lock in a skid) at some point, e.g. to make sure a slippery rail case does what it's meant to."""
|
|
for r in rows:
|
|
if within is not None and r[COL_TIME] > within:
|
|
break
|
|
if len(r) > COL_WHEELSLIP and r[COL_WHEELSLIP]:
|
|
return True, f"wheels slipping at t={r[COL_TIME]:.1f}s, v={r[COL_VELOCITY]:.1f} km/h"
|
|
return False, "the wheels never slipped"
|
|
|
|
|
|
def check_holds_still(rows, moving_speed, stop_speed, max_distance):
|
|
"""Once stopped after moving off, the vehicle doesn't creep. Uses the vehicle speed rather than the
|
|
wheel speed, so it also catches a vehicle sliding on locked wheels."""
|
|
if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None:
|
|
return False, "the physicslog has no vehicle speed column, the build is too old"
|
|
speed = [abs(r[COL_VEHICLE_VELOCITY]) for r in rows]
|
|
start = next((i for i, v in enumerate(speed) if v >= moving_speed), None)
|
|
if start is None:
|
|
return False, f"never reached {moving_speed} km/h"
|
|
stop = next((i for i in range(start, len(rows)) if speed[i] <= stop_speed), None)
|
|
if stop is None:
|
|
return False, f"never came down to {stop_speed} km/h"
|
|
d, top, top_t = 0.0, 0.0, rows[stop][COL_TIME]
|
|
for i in range(stop + 1, len(rows)):
|
|
d += (speed[i - 1] + speed[i]) / 2 / 3.6 * (rows[i][COL_TIME] - rows[i - 1][COL_TIME])
|
|
if speed[i] > top:
|
|
top, top_t = speed[i], rows[i][COL_TIME]
|
|
held = rows[-1][COL_TIME] - rows[stop][COL_TIME]
|
|
detail = f"stopped at t={rows[stop][COL_TIME]:.1f}s, then moved {d:.3f} m in {held:.0f}s, top {top:.4f} km/h at t={top_t:.1f}s"
|
|
return d <= max_distance, detail
|
|
|
|
|
|
def check_ends_moving(rows, min_speed):
|
|
"""The run ended with the vehicle still moving, e.g. a pass that didn't wait for the trains to stop."""
|
|
if not rows:
|
|
return False, "the physicslog is empty"
|
|
last = rows[-1]
|
|
ok = last[COL_VELOCITY] >= min_speed
|
|
return ok, f"last row t={last[COL_TIME]:.1f}s, v={last[COL_VELOCITY]:.1f} km/h (wanted >= {min_speed})"
|
|
|
|
|
|
def check_keeps_moving(rows, moving_speed, min_speed, until_distance, from_distance=0.0):
|
|
"""(*vehicle speed*) Once at moving_speed, the speed stays at or above min_speed between the two distances (metres
|
|
travelled, from the vehicle speed), e.g. a train doesn't come to a stand on a gradient before a restriction or in
|
|
it. The vehicle speed, as wheels slipping at the start would count as moving off."""
|
|
if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None:
|
|
return False, "the physicslog has no vehicle speed column, the build is too old"
|
|
speed = [abs(r[COL_VEHICLE_VELOCITY]) for r in rows]
|
|
start = next((i for i, v in enumerate(speed) if v >= moving_speed), None)
|
|
if start is None:
|
|
return False, f"never reached {moving_speed} km/h"
|
|
dist, d = [0.0], 0.0
|
|
for i in range(1, len(rows)):
|
|
d += (speed[i - 1] + speed[i]) / 2 / 3.6 * (rows[i][COL_TIME] - rows[i - 1][COL_TIME])
|
|
dist.append(d)
|
|
span = [i for i in range(start, len(rows)) if from_distance <= dist[i] <= until_distance]
|
|
if not span or dist[-1] < until_distance:
|
|
return False, f"travelled {dist[-1]:.0f} m only, wanted {until_distance} m"
|
|
low = min(span, key=lambda i: speed[i])
|
|
r = rows[low]
|
|
detail = (f"lowest speed {speed[low]:.1f} km/h at t={r[COL_TIME]:.1f}s after {dist[low]:.0f} m "
|
|
f"(brake cylinder {r[COL_BRAKE_PRESS]:.2f} bar), wanted >= {min_speed} between {from_distance:.0f} and {until_distance} m")
|
|
return speed[low] >= min_speed, detail
|
|
|
|
|
|
def check_starts_again(rows, after, min_speed, within, max_rollback=None):
|
|
"""Standing at the time `after` (e.g. at a signal that clears then), the vehicle reaches min_speed within `within`
|
|
seconds; with max_rollback (*vehicle speed*), it rolls back no more than that many metres meanwhile."""
|
|
first = next((i for i, r in enumerate(rows) if r[COL_TIME] >= after), None)
|
|
if first is None:
|
|
return False, f"the physicslog ends before t={after}s"
|
|
if rows[first][COL_VELOCITY] > 1.0:
|
|
return False, f"moving at {rows[first][COL_VELOCITY]:.1f} km/h at t={after}s, wanted standing"
|
|
moved = next((r[COL_TIME] for r in rows[first:] if r[COL_VELOCITY] > 1.0), None)
|
|
reached = next((r[COL_TIME] for r in rows[first:] if r[COL_VELOCITY] >= min_speed), None)
|
|
rollback, back = 0.0, 0.0
|
|
if max_rollback is not None:
|
|
if len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None:
|
|
return False, "the physicslog has no vehicle speed column, the build is too old"
|
|
end = reached if reached is not None else after + within
|
|
for a, b in zip(rows[first:], rows[first + 1:]):
|
|
if b[COL_TIME] > end:
|
|
break
|
|
back += (a[COL_VEHICLE_VELOCITY] + b[COL_VEHICLE_VELOCITY]) / 2 / 3.6 * (b[COL_TIME] - a[COL_TIME])
|
|
rollback = max(rollback, -back)
|
|
detail = (f"moved off (1 km/h) {moved - after:.1f}s after t={after}s" if moved is not None else f"didn't move off after t={after}s")
|
|
detail += f", {min_speed} km/h after {reached - after:.1f}s" if reached is not None else f", never reached {min_speed} km/h"
|
|
if max_rollback is not None:
|
|
detail += f", rolled back {rollback:.2f} m (wanted <= {max_rollback})"
|
|
ok = reached is not None and reached - after <= within and (max_rollback is None or rollback <= max_rollback)
|
|
return ok, detail + f" (wanted {min_speed} km/h within {within}s)"
|
|
|
|
|
|
def check_slip_clears(rows, moving_speed, stop_speed, within):
|
|
"""Once the vehicle has stopped after moving off, its wheels stop slipping within `within` seconds
|
|
(a vehicle left skidding on locked wheels keeps its brakes capped by the sliding adhesion)."""
|
|
if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None:
|
|
return False, "the physicslog has no vehicle speed column, the build is too old"
|
|
start = next((i for i, r in enumerate(rows) if abs(r[COL_VEHICLE_VELOCITY]) >= moving_speed), None)
|
|
if start is None:
|
|
return False, f"never reached {moving_speed} km/h"
|
|
stop = next((i for i in range(start, len(rows)) if abs(rows[i][COL_VEHICLE_VELOCITY]) <= stop_speed), None)
|
|
if stop is None:
|
|
return False, f"never came down to {stop_speed} km/h"
|
|
deadline = rows[stop][COL_TIME] + within
|
|
late = [r for r in rows[stop:] if r[COL_TIME] > deadline and r[COL_WHEELSLIP]]
|
|
if late:
|
|
return False, f"stopped at t={rows[stop][COL_TIME]:.1f}s, wheels still slipping at t={late[0][COL_TIME]:.1f}s ({len(late)} rows after the {within}s grace)"
|
|
return True, f"stopped at t={rows[stop][COL_TIME]:.1f}s, no slipping after t={deadline:.1f}s"
|
|
|
|
|
|
def check_traction(rows, from_distance, to_distance, reaches=None, at_most=None, at_least=None):
|
|
"""The traction force of the vehicle in kN (the physicslog has it in N, whatever its header says) while it
|
|
runs between two points of its way, in metres travelled as in `distance`: the highest there `reaches` a
|
|
force, e.g. the power taken again behind a section without voltage; it stays `at_most` a force, e.g. none
|
|
taken where there is no voltage; it stays `at_least` a force, e.g. no power lost under an insulator."""
|
|
dist = _distances(rows)
|
|
window = [(d, r) for d, r in zip(dist, rows) if from_distance <= d <= to_distance]
|
|
if not window:
|
|
return False, f"never got between {from_distance} and {to_distance} m (travelled {dist[-1] if dist else 0:.0f} m)"
|
|
|
|
def describe(item):
|
|
d, r = item
|
|
return f"{r[COL_TRACTION_FORCE] / 1000:.1f} kN at {d:.0f} m, t={r[COL_TIME]:.1f}s, v={r[COL_VELOCITY]:.1f} km/h"
|
|
|
|
top = max(window, key=lambda item: item[1][COL_TRACTION_FORCE])
|
|
low = min(window, key=lambda item: item[1][COL_TRACTION_FORCE])
|
|
detail = (f"between {from_distance} and {to_distance} m (t={window[0][1][COL_TIME]:.1f}-{window[-1][1][COL_TIME]:.1f}s) "
|
|
f"the traction force was {describe(low)} at its lowest, {describe(top)} at its highest")
|
|
if reaches is not None and top[1][COL_TRACTION_FORCE] / 1000 < reaches:
|
|
return False, f"{detail}; wanted it to reach {reaches} kN"
|
|
if at_most is not None and top[1][COL_TRACTION_FORCE] / 1000 > at_most:
|
|
return False, f"{detail}; wanted at most {at_most} kN"
|
|
if at_least is not None and low[1][COL_TRACTION_FORCE] / 1000 < at_least:
|
|
return False, f"{detail}; wanted at least {at_least} kN"
|
|
return True, detail
|
|
|
|
|
|
def check_master_controller(rows, from_distance, to_distance, at_most):
|
|
"""The master controller of the vehicle stays at or below a position while it runs between two points of its
|
|
way (metres travelled, as in `distance`), e.g. at 0 where the scenery tells the driver to coast."""
|
|
dist = _distances(rows)
|
|
window = [(d, r) for d, r in zip(dist, rows) if from_distance <= d <= to_distance]
|
|
if not window:
|
|
return False, f"never got between {from_distance} and {to_distance} m (travelled {dist[-1] if dist else 0:.0f} m)"
|
|
d, top = max(window, key=lambda item: item[1][COL_MASTER_CONTROLLER])
|
|
detail = (f"between {from_distance} and {to_distance} m (t={window[0][1][COL_TIME]:.1f}-{window[-1][1][COL_TIME]:.1f}s) "
|
|
f"the master controller was at {top[COL_MASTER_CONTROLLER]:.0f} at most, at {d:.0f} m, t={top[COL_TIME]:.1f}s")
|
|
if top[COL_MASTER_CONTROLLER] > at_most:
|
|
return False, f"{detail}; wanted at most {at_most}"
|
|
return True, detail
|
|
|
|
|
|
def check_traction_power(rows, max_kw, min_peak_kw=None):
|
|
"""The power at the wheels, the traction force times the vehicle speed, stays at or below max_kw
|
|
and, given min_peak_kw, reaches it, e.g. a dual-mode vehicle on its genset (eu07/maszyna#536)."""
|
|
if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None:
|
|
return False, "the physicslog has no vehicle speed column"
|
|
power = [abs(r[COL_TRACTION_FORCE]) * abs(r[COL_VEHICLE_VELOCITY]) / 3.6 / 1000 for r in rows]
|
|
peak = max(range(len(rows)), key=power.__getitem__)
|
|
r = rows[peak]
|
|
detail = (f"peak {power[peak]:.0f} kW at t={r[COL_TIME]:.1f}s, v={r[COL_VEHICLE_VELOCITY]:.1f} km/h, "
|
|
f"Ft={r[COL_TRACTION_FORCE] / 1000:.1f} kN")
|
|
if power[peak] > max_kw:
|
|
return False, f"{detail}, above {max_kw} kW"
|
|
if min_peak_kw is not None and power[peak] < min_peak_kw:
|
|
return False, f"{detail}, below {min_peak_kw} kW"
|
|
return True, detail
|
|
|
|
|
|
CHECKS = {
|
|
"master_controller": check_master_controller,
|
|
"traction": check_traction,
|
|
"slips": check_slips,
|
|
"slip_clears": check_slip_clears,
|
|
"holds_still": check_holds_still,
|
|
"starts": check_starts,
|
|
"max_speed": check_max_speed,
|
|
"brakes": check_brakes,
|
|
"stops": check_stops,
|
|
"stays_stopped": check_stays_stopped,
|
|
"distance": check_distance,
|
|
"ends_moving": check_ends_moving,
|
|
"traction_power": check_traction_power,
|
|
"keeps_moving": check_keeps_moving,
|
|
"starts_again": check_starts_again,
|
|
}
|
|
|
|
|
|
def check_log_contains(log, pattern):
|
|
"""A line of the run's log.txt matches the regex, e.g. the "Bad driving" message of a collision."""
|
|
found = next((line.strip() for line in log.splitlines() if re.search(pattern, line)), None)
|
|
if found is None:
|
|
return False, f"no log line matches /{pattern}/"
|
|
return True, f"log: {found}"
|
|
|
|
|
|
def check_log_lacks(log, pattern):
|
|
"""No line of the run's log.txt matches the regex."""
|
|
found = [line.strip() for line in log.splitlines() if re.search(pattern, line)]
|
|
if found:
|
|
return False, f"{len(found)} log line(s) match /{pattern}/, first: {found[0]}"
|
|
return True, f"no log line matches /{pattern}/"
|
|
|
|
|
|
# checks on the text of the run's log.txt rather than on the physicslog rows
|
|
OVERLAP_LINE = re.compile(r"derailment: the bodies overlap by up to ([\d.]+) m(?: \((.*?)\))? over the last second, "
|
|
r"([\d.]+) m now(, all at rest)?")
|
|
|
|
|
|
def check_no_overlap(log, max_transient, max_at_rest):
|
|
"""physics.derailment new: the bodies of the vehicles off the track (and of those near them) don't go into each
|
|
other: the log has the most they overlapped by every second; at most `max_transient` m at any time, and at most
|
|
`max_at_rest` m once all of them came to rest."""
|
|
lines = [m for m in (OVERLAP_LINE.search(line) for line in log.splitlines()) if m]
|
|
if not lines:
|
|
return False, "no line of the overlap of the bodies in the log"
|
|
worst = max(lines, key=lambda m: float(m.group(1)))
|
|
rest = next((m for m in reversed(lines) if m.group(4)), None)
|
|
detail = f"most {float(worst.group(1)):.2f} m" + (f" ({worst.group(2)})" if worst.group(2) else "")
|
|
if rest is None:
|
|
return False, detail + ", the vehicles never all came to rest"
|
|
detail += f", {float(rest.group(3)):.2f} m at rest"
|
|
failed = []
|
|
if float(worst.group(1)) > max_transient:
|
|
failed.append(f"over {max_transient} m on the way")
|
|
if float(rest.group(3)) > max_at_rest:
|
|
failed.append(f"over {max_at_rest} m at rest")
|
|
return not failed, detail + ("" if not failed else ": " + "; ".join(failed))
|
|
|
|
|
|
LOG_CHECKS = {
|
|
"log_contains": check_log_contains,
|
|
"log_lacks": check_log_lacks,
|
|
"no_overlap": check_no_overlap,
|
|
}
|
|
|
|
|
|
def check_couples(box, vehicle, other):
|
|
"""The two vehicles couple in the run and stay coupled to its end; coupled from the start doesn't count."""
|
|
# the simulator reads the names of a scenery in lower case, whatever the scenery (or the case) writes
|
|
numbers = {name.lower(): number for number, name in box.vehicles.items()}
|
|
unknown = [name for name in (vehicle, other) if name.lower() not in numbers]
|
|
if unknown:
|
|
return False, f"the black box has no vehicle {' nor '.join(unknown)}"
|
|
pair = {numbers[vehicle.lower()], numbers[other.lower()]}
|
|
# of the two vehicles of a coupling the one with the lower number tells it, each change of that coupler
|
|
# under the same vehicle and side: the record which coupled the two, for as long as they stay coupled
|
|
made, parted = {}, None
|
|
for c in box.couplings:
|
|
coupler = (c.vehicle, c.side)
|
|
if {c.vehicle, c.other} == pair and c.flags & COUPLING_COUPLER:
|
|
made.setdefault(coupler, c)
|
|
elif coupler in made:
|
|
parted = (made.pop(coupler), c)
|
|
if not made:
|
|
if parted:
|
|
return False, f"{vehicle} and {other} coupled at t={parted[0].time:.1f}s but came apart at t={parted[1].time:.1f}s"
|
|
return False, f"none of the {len(box.couplings)} coupling record(s) of the black box couples {vehicle} and {other}"
|
|
c = min(made.values(), key=lambda c: c.time)
|
|
if c.time <= 0:
|
|
return False, f"{vehicle} and {other} were coupled when the recording started"
|
|
ends = ("front", "rear")
|
|
return True, (f"at t={c.time:.1f}s the {ends[c.side]} coupler of {box.vehicles[c.vehicle]} coupled to the "
|
|
f"{ends[c.other_side]} one of {box.vehicles[c.other]}, coupling 0x{c.flags:02X}")
|
|
|
|
|
|
def check_parts(box, vehicle, other, before=None):
|
|
"""The two vehicles, coupled to each other, come apart in the run: a coupler broken, or uncoupled."""
|
|
numbers = {name.lower(): number for number, name in box.vehicles.items()}
|
|
unknown = [name for name in (vehicle, other) if name.lower() not in numbers]
|
|
if unknown:
|
|
return False, f"the black box has no vehicle {' nor '.join(unknown)}"
|
|
pair = {numbers[vehicle.lower()], numbers[other.lower()]}
|
|
# the record of the coupler which let go: coupled to the other vehicle before, the coupler itself no more
|
|
c = next((c for c in box.couplings if {c.vehicle, c.previous_other} == pair
|
|
and c.previous_flags & COUPLING_COUPLER and not c.flags & COUPLING_COUPLER), None)
|
|
if c is None:
|
|
return False, f"none of the {len(box.couplings)} coupling record(s) of the black box parts {vehicle} and {other}"
|
|
if before is not None and c.time > before:
|
|
return False, f"{vehicle} and {other} came apart at t={c.time:.1f}s, after {before:g}s"
|
|
ends = ("front", "rear")
|
|
return True, (f"at t={c.time:.1f}s the {ends[c.side]} coupler of {box.vehicles[c.vehicle]} let go of "
|
|
f"{box.vehicles[c.previous_other]}, coupling 0x{c.previous_flags:02X} before")
|
|
|
|
|
|
def _vehicle_states(box, vehicle):
|
|
"""The states of the vehicle named, or None and why not."""
|
|
numbers = {name.lower(): number for number, name in box.vehicles.items()}
|
|
number = numbers.get(vehicle.lower())
|
|
if number is None:
|
|
return None, f"the black box has no vehicle {vehicle}"
|
|
states = box.states.get(number)
|
|
if not states:
|
|
return None, f"the black box has no state of {vehicle}"
|
|
return states, ""
|
|
|
|
|
|
def _driver_change(states, to):
|
|
"""The first state with the driver `to` after one with another driver; None when there is none."""
|
|
return next((now for before, now in zip(states, states[1:]) if now.driver == to and before.driver != to), None)
|
|
|
|
|
|
def check_driver_changes(box, vehicle, to, after=0.0, before=None):
|
|
"""The vehicle gets the driver `to` (none, ai, user) between the times given, and keeps it to the end."""
|
|
states, why = _vehicle_states(box, vehicle)
|
|
if states is None:
|
|
return False, why
|
|
wanted = BLACKBOX_DRIVERS[to]
|
|
names = {number: name for name, number in BLACKBOX_DRIVERS.items()}
|
|
change = _driver_change(states, wanted)
|
|
if change is None:
|
|
return False, f"{vehicle} starts with driver {names.get(states[0].driver)} and never changes to {to}"
|
|
if change.time < after or (before is not None and change.time > before):
|
|
return False, f"{vehicle} got driver {to} at t={change.time:.1f}s, outside {after:g}..{before if before is not None else 'end'}"
|
|
later = next((s for s in states if s.time > change.time and s.driver != wanted), None)
|
|
if later is not None:
|
|
return False, f"{vehicle} got driver {to} at t={change.time:.1f}s but {names.get(later.driver)} at t={later.time:.1f}s"
|
|
return True, f"{vehicle} has driver {to} from t={change.time:.1f}s to the end (t={box.end_time:.1f}s)"
|
|
|
|
|
|
def check_stops_driverless(box, vehicle, min_speed, within, stop_speed=0.5, max_creep=1.0, hold=60.0,
|
|
min_deceleration=None, max_deceleration=None):
|
|
"""The vehicle loses its driver at `min_speed` or faster, stands `within` seconds later and stays where it
|
|
stopped, to the end of the recording or until it gets a driver again. With the decelerations, the mean one of
|
|
that stop (from the speed and the way to the stop, m/s²) has to be within them: how well the train brakes."""
|
|
states, why = _vehicle_states(box, vehicle)
|
|
if states is None:
|
|
return False, why
|
|
left = _driver_change(states, BLACKBOX_DRIVERS["none"])
|
|
if left is None:
|
|
return False, f"{vehicle} never loses its driver"
|
|
if abs(left.speed) < min_speed:
|
|
return False, f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h, below {min_speed}"
|
|
after = [s for s in states if s.time >= left.time]
|
|
stop = next((s for s in after if abs(s.speed) <= stop_speed), None)
|
|
if stop is None or stop.time - left.time > within:
|
|
took = "never" if stop is None else f"after {stop.time - left.time:.0f}s"
|
|
return False, f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h and stood {took} (limit {within}s)"
|
|
# left alone until the recording ends, or a driver comes again
|
|
crewed = next((s for s in after if s.time > stop.time and s.driver != BLACKBOX_DRIVERS["none"]), None)
|
|
until = crewed.time if crewed else box.end_time
|
|
alone = "until a driver came" if crewed else "to the end"
|
|
if until - stop.time < hold:
|
|
return False, f"{vehicle} stood at t={stop.time:.1f}s, with no driver for {until - stop.time:.0f}s more {alone} (hold {hold}s)"
|
|
# a standing vehicle is listed again only in the keyframes, or when it moves
|
|
standing = [s for s in after if stop.time <= s.time <= until]
|
|
fastest = max(abs(s.speed) for s in standing)
|
|
creep = max(math.dist(s.position, stop.position) for s in standing)
|
|
if fastest > stop_speed or creep > max_creep:
|
|
return False, f"{vehicle} stood at t={stop.time:.1f}s, then moved {creep:.1f} m at up to {fastest:.1f} km/h with no driver"
|
|
way = sum(math.dist(a.position, b.position) for a, b in zip(after, after[1:]) if b.time <= stop.time)
|
|
stopped = (f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h, stood {stop.time - left.time:.0f}s "
|
|
f"and {way:.0f} m later")
|
|
# v² / 2s: the black box lists a vehicle once a second, so the way is closer to the truth than the time
|
|
deceleration = (abs(left.speed) / 3.6) ** 2 / (2 * way) if way > 0 else math.inf
|
|
if ((min_deceleration is not None and deceleration < min_deceleration)
|
|
or (max_deceleration is not None and deceleration > max_deceleration)):
|
|
bounds = f"{min_deceleration if min_deceleration is not None else 0:g}..{max_deceleration if max_deceleration is not None else 'any'}"
|
|
return False, f"{stopped}: a mean deceleration of {deceleration:.2f} m/s², outside {bounds}"
|
|
return True, f"{stopped} ({deceleration:.2f} m/s²), moved {creep:.2f} m in the {until - stop.time:.0f}s {alone}"
|
|
|
|
|
|
def check_moves(box, vehicle, min_speed, direction="front"):
|
|
"""The vehicle reaches `min_speed` with its front end leading, or its rear one (the physicslog has no direction)."""
|
|
states, why = _vehicle_states(box, vehicle)
|
|
if states is None:
|
|
return False, why
|
|
sign = {"front": 1.0, "rear": -1.0}[direction]
|
|
fastest = max(states, key=lambda s: sign * s.speed)
|
|
if sign * fastest.speed < min_speed:
|
|
return False, f"{vehicle} never reaches {min_speed} km/h {direction} end leading, at most {sign * fastest.speed:.1f}"
|
|
first = next(s for s in states if sign * s.speed >= min_speed)
|
|
return True, f"{vehicle} runs {direction} end leading: {min_speed} km/h at t={first.time:.1f}s, up to {sign * fastest.speed:.1f} km/h"
|
|
|
|
|
|
def check_leaves_track(box, vehicle, cause=None, min_offset=None, max_offset=None, min_distance=None, max_distance=None,
|
|
lying=None):
|
|
"""The vehicle leaves the track (physics.derailment new) and comes to rest off it: what derailed it, how far from
|
|
the axis of the track (either side) and how far it went on the ground, and whether it ends on its side."""
|
|
numbers = {name.lower(): number for number, name in box.vehicles.items()}
|
|
number = numbers.get(vehicle.lower())
|
|
if number is None:
|
|
return False, f"the black box has no vehicle {vehicle}"
|
|
records = [d for d in box.derailments if d.vehicle == number]
|
|
left = next((d for d in records if d.phase == 0), None)
|
|
if left is None:
|
|
return False, f"{vehicle} never left the track ({len(box.derailments)} derailment record(s) of others)"
|
|
rest = next((d for d in records if d.phase == 1 and d.time >= left.time), None)
|
|
detail = (f"{vehicle} left the track at t={left.time:.1f}s at {abs(left.speed):.0f} km/h "
|
|
f"({DERAILMENT_CAUSES.get(left.cause, left.cause)})")
|
|
if rest is None:
|
|
return False, detail + ", and never came to rest"
|
|
detail += (f", came to rest at t={rest.time:.1f}s {rest.travelled:.1f} m on, {rest.offset:+.1f} m from the axis of the "
|
|
f"track, roll {math.degrees(rest.roll):+.0f} deg{', on its side' if rest.lying else ''}")
|
|
failed = []
|
|
if cause is not None and DERAILMENT_CAUSES.get(left.cause) != cause:
|
|
failed.append(f"derailed by {DERAILMENT_CAUSES.get(left.cause, left.cause)}, wanted {cause}")
|
|
if min_offset is not None and abs(rest.offset) < min_offset:
|
|
failed.append(f"offset under {min_offset} m")
|
|
if max_offset is not None and abs(rest.offset) > max_offset:
|
|
failed.append(f"offset over {max_offset} m")
|
|
if min_distance is not None and rest.travelled < min_distance:
|
|
failed.append(f"went under {min_distance} m")
|
|
if max_distance is not None and rest.travelled > max_distance:
|
|
failed.append(f"went over {max_distance} m")
|
|
if lying is not None and rest.lying != lying:
|
|
failed.append("lying on its side" if rest.lying else "upright")
|
|
return not failed, detail + ("" if not failed else ": " + "; ".join(failed))
|
|
|
|
|
|
def check_consist_folds(box, vehicles, min_bend, min_folds=1, alternate=False, both_sides=False):
|
|
"""The vehicles of a train (names, front to back, comma separated) left the track (physics.derailment new) and came
|
|
to rest folded up: at least `min_folds` of the bends between neighbours at rest (the angle between their headings,
|
|
either way along) are `min_bend` degrees or more; with `alternate` the bends of neighbouring joints turn opposite
|
|
ways, a zigzag; with `both_sides` some of them rest on one side of the track and some on the other."""
|
|
numbers = {name.lower(): number for number, name in box.vehicles.items()}
|
|
names = [name.strip() for name in vehicles.split(",") if name.strip()]
|
|
rests = []
|
|
for name in names:
|
|
number = numbers.get(name.lower())
|
|
rests.append(next((d for d in box.derailments if number is not None and d.vehicle == number and d.phase == 1), None))
|
|
if all(rest is None for rest in rests):
|
|
return False, f"none of {', '.join(names)} came to rest off the track"
|
|
bends = []
|
|
for first, second in zip(rests, rests[1:]):
|
|
if first is None or second is None:
|
|
bends.append(None)
|
|
continue
|
|
# either way along: a vehicle turned about in the train has its heading the other way
|
|
bends.append(math.degrees(math.remainder(math.remainder(second.heading - first.heading, 2 * math.pi), math.pi)))
|
|
folds = [bend for bend in bends if bend is not None and abs(bend) >= min_bend]
|
|
sides = {1 if rest.offset > 0 else -1 for rest in rests if rest is not None and abs(rest.offset) > 0.5}
|
|
detail = "at rest: " + "; ".join(
|
|
f"{name} " + ("on the track" if rest is None else
|
|
f"{rest.travelled:.0f} m on, {rest.offset:+.1f} m, heading {math.degrees(rest.heading):+.0f} deg")
|
|
for name, rest in zip(names, rests))
|
|
detail += "; bends " + ", ".join("-" if bend is None else f"{bend:+.0f}" for bend in bends) + " deg"
|
|
failed = []
|
|
if len(folds) < min_folds:
|
|
failed.append(f"{len(folds)} bend(s) of {min_bend} deg or more, wanted {min_folds}")
|
|
if alternate:
|
|
pairs = [(a, b) for a, b in zip(bends, bends[1:]) if a is not None and b is not None
|
|
and abs(a) >= min_bend and abs(b) >= min_bend]
|
|
if not pairs or any(a * b > 0 for a, b in pairs):
|
|
failed.append("the bends don't alternate")
|
|
if both_sides and len(sides) < 2:
|
|
failed.append("all on one side of the track")
|
|
return not failed, detail + ("" if not failed else ": " + "; ".join(failed))
|
|
|
|
|
|
def _along_track(track, x, z):
|
|
"""Where the point (x, z) lies by the track: its level distance [m] from the line of the track, and how far along
|
|
the track [m] from its first point that nearest point of the line is."""
|
|
best, at, run_length = math.inf, 0.0, 0.0
|
|
if len(track.points) == 1:
|
|
return math.hypot(x - track.points[0][0], z - track.points[0][2]), 0.0
|
|
for (ax, _, az), (bx, _, bz) in zip(track.points, track.points[1:]):
|
|
dx, dz = bx - ax, bz - az
|
|
length = dx * dx + dz * dz
|
|
share = 0.0 if length == 0.0 else max(0.0, min(1.0, ((x - ax) * dx + (z - az) * dz) / length))
|
|
offset = math.hypot(x - (ax + share * dx), z - (az + share * dz))
|
|
if offset < best:
|
|
best, at = offset, run_length + share * math.sqrt(length)
|
|
run_length += math.sqrt(length)
|
|
return best, at
|
|
|
|
|
|
def _track_length(track):
|
|
return sum(math.hypot(b[0] - a[0], b[2] - a[2]) for a, b in zip(track.points, track.points[1:]))
|
|
|
|
|
|
def _track_label(track):
|
|
return f"{track.name or '#' + str(track.number)}" + (f" (way {track.branch})" if track.kind == 1 else "")
|
|
|
|
|
|
class _TrackMap:
|
|
"""The tracks of a black box as a network: the ends of the tracks (and of the ways of the switches) that meet are
|
|
one node, each track an edge of its length between its two ends."""
|
|
|
|
JOINT = 0.3 # ends closer than this [m], level, meet
|
|
|
|
def __init__(self, tracks):
|
|
self.tracks = tracks
|
|
self.lengths = [_track_length(t) for t in tracks]
|
|
nodes = [] # (x, z) of each node
|
|
self.ends = [] # the nodes of the first and the last point of each track
|
|
for track in tracks:
|
|
pair = []
|
|
for x, _, z in (track.points[0], track.points[-1]):
|
|
node = next((i for i, (nx, nz) in enumerate(nodes) if math.hypot(nx - x, nz - z) < self.JOINT), None)
|
|
if node is None:
|
|
nodes.append((x, z))
|
|
node = len(nodes) - 1
|
|
pair.append(node)
|
|
self.ends.append(tuple(pair))
|
|
self.edges = {} # node: [(other node, length)]
|
|
for (a, b), length in zip(self.ends, self.lengths):
|
|
self.edges.setdefault(a, []).append((b, length))
|
|
self.edges.setdefault(b, []).append((a, length))
|
|
|
|
def places(self, position, max_offset):
|
|
"""The tracks the position lies on: within max_offset [m] of their line, (track index, offset, along)."""
|
|
x, _, z = position
|
|
found = [(i, *_along_track(t, x, z)) for i, t in enumerate(self.tracks)]
|
|
near = [f for f in found if f[1] <= max_offset]
|
|
return near or [min(found, key=lambda f: f[1])]
|
|
|
|
def distance(self, one, other, limit):
|
|
"""The shortest way [m] along the tracks between two places (track index, offset, along), up to `limit`
|
|
(beyond it, infinity)."""
|
|
(i, _, s), (j, _, t) = one, other
|
|
if i == j:
|
|
return abs(s - t)
|
|
start = {self.ends[i][0]: s, self.ends[i][1]: self.lengths[i] - s}
|
|
goal = {self.ends[j][0]: t, self.ends[j][1]: self.lengths[j] - t}
|
|
reached = dict(start)
|
|
queue = [(cost, node) for node, cost in start.items()]
|
|
heapq.heapify(queue)
|
|
best = math.inf
|
|
while queue:
|
|
cost, node = heapq.heappop(queue)
|
|
if cost > reached.get(node, math.inf) or cost >= min(best, limit):
|
|
continue
|
|
if node in goal:
|
|
best = min(best, cost + goal[node])
|
|
for nxt, length in self.edges.get(node, []):
|
|
if cost + length < reached.get(nxt, math.inf):
|
|
reached[nxt] = cost + length
|
|
heapq.heappush(queue, (cost + length, nxt))
|
|
return best if best <= limit else math.inf
|
|
|
|
|
|
def _coupled_pairs(box, chosen, upto):
|
|
"""The pairs of vehicles (by number) among `chosen` whose couplers hold each other at the time `upto`."""
|
|
held = {}
|
|
for c in box.couplings:
|
|
if c.time > upto:
|
|
break
|
|
held[(c.vehicle, c.side)] = (c.other, c.flags)
|
|
return {tuple(sorted((vehicle, other))) for (vehicle, _), (other, flags) in held.items()
|
|
if flags & COUPLING_COUPLER and vehicle in chosen and other in chosen}
|
|
|
|
|
|
def check_on_track(box, vehicles, max_offset=0.75, max_detour=5.0):
|
|
"""Every vehicle whose name starts with `vehicles` stays on the line of a track in every state the black box has of
|
|
it, and the vehicles coupled to each other stay on one way: the way along the tracks from one to the other is no
|
|
more than `max_detour` [m] longer than the straight line between them. A vehicle thrown sideways has its middle off
|
|
any track; one with its bogies on two tracks that part too, once they are apart; and a train whose vehicles went
|
|
two ways at a switch runs on with two coupled vehicles on two tracks, side by side, with the way between them back
|
|
through the switch."""
|
|
if not box.tracks:
|
|
return False, "the black box has no map of the tracks"
|
|
chosen = {number: name for number, name in box.vehicles.items() if name.lower().startswith(vehicles.lower())}
|
|
if not chosen:
|
|
return False, f"the black box has no vehicle named {vehicles}..."
|
|
network = _TrackMap(box.tracks)
|
|
# the states of the chosen vehicles by time: a vehicle is listed when it moved, or every 60 s
|
|
times = sorted({s.time for number in chosen for s in box.states.get(number, [])})
|
|
if not times:
|
|
return False, f"the black box has no state of {', '.join(chosen.values())}"
|
|
latest, index, places = {}, {number: 0 for number in chosen}, {}
|
|
worst_offset, worst_detour, failures = None, None, []
|
|
for when in times:
|
|
for number in chosen:
|
|
states = box.states.get(number, [])
|
|
while index[number] < len(states) and states[index[number]].time <= when:
|
|
latest[number] = states[index[number]]
|
|
index[number] += 1
|
|
for number, state in latest.items():
|
|
if (number, state.time) in places:
|
|
continue
|
|
places[(number, state.time)] = network.places(state.position, max_offset)
|
|
nearest = min(places[(number, state.time)], key=lambda p: p[1])
|
|
if worst_offset is None or nearest[1] > worst_offset[0]:
|
|
worst_offset = (nearest[1], chosen[number], state, box.tracks[nearest[0]])
|
|
for one, other in _coupled_pairs(box, chosen, when):
|
|
if one not in latest or other not in latest:
|
|
continue
|
|
straight = math.dist(latest[one].position, latest[other].position)
|
|
at_one, at_other = places[(one, latest[one].time)], places[(other, latest[other].time)]
|
|
way = min(network.distance(a, b, straight + 1000.0) for a in at_one for b in at_other)
|
|
detour = way - straight
|
|
if worst_detour is None or detour > worst_detour[0]:
|
|
worst_detour = (detour, chosen[one], chosen[other], when, at_one, at_other)
|
|
offset, name, state, track = worst_offset
|
|
where = f"{name} at t={state.time:.1f}s ({abs(state.speed):.1f} km/h) {offset:.2f} m off {_track_label(track)}"
|
|
if offset > max_offset:
|
|
failures.append(f"{where}, more than {max_offset} m")
|
|
detail = f"the farthest off a track {where}"
|
|
if worst_detour is not None:
|
|
detour, one, other, when, at_one, at_other = worst_detour
|
|
tracks = (f"{_track_label(box.tracks[min(at_one, key=lambda p: p[1])[0]])} and "
|
|
f"{_track_label(box.tracks[min(at_other, key=lambda p: p[1])[0]])}")
|
|
length = "no way along the tracks" if math.isinf(detour) else f"the way along the tracks {detour:.1f} m longer than the straight line"
|
|
said = f"{one} and {other}, coupled, at t={when:.1f}s on {tracks}: {length}"
|
|
if detour > max_detour:
|
|
failures.append(f"{said}, more than {max_detour} m")
|
|
detail += f"; of the coupled ones {said}"
|
|
if failures:
|
|
return False, "; ".join(failures)
|
|
return True, f"{len(chosen)} vehicle(s), {detail}"
|
|
|
|
|
|
# checks on the black box of the run rather than on the physicslog rows
|
|
BLACKBOX_CHECKS = {
|
|
"leaves_track": check_leaves_track,
|
|
"consist_folds": check_consist_folds,
|
|
"couples": check_couples,
|
|
"parts": check_parts,
|
|
"driver_changes": check_driver_changes,
|
|
"stops_driverless": check_stops_driverless,
|
|
"moves": check_moves,
|
|
"on_track": check_on_track,
|
|
}
|
|
|
|
|
|
# ---------------------------------------------------------------- main
|
|
|
|
|
|
def find_exe(explicit: str | None) -> Path:
|
|
if explicit:
|
|
return Path(explicit).resolve()
|
|
candidates = sorted(REPO.glob("cmake-build-*/bin/Release/eu07*.exe"), key=lambda p: p.stat().st_mtime)
|
|
if not candidates:
|
|
sys.exit("no eu07 executable found under cmake-build-*/bin/Release, pass --exe")
|
|
return candidates[-1]
|
|
|
|
|
|
def count_lines(path: Path) -> int:
|
|
try:
|
|
return sum(1 for line in path.read_text(errors="replace").splitlines() if line.strip())
|
|
except FileNotFoundError:
|
|
return 0
|
|
|
|
|
|
def describe_exit(code: int | None) -> str:
|
|
if code is None:
|
|
return "none, still running"
|
|
name = EXIT_RESULTS.get(code)
|
|
return f"{code} ({name})" if name else f"{code} (0x{code & 0xFFFFFFFF:08X}, a crash?)"
|
|
|
|
|
|
def load_case(name: str) -> dict:
|
|
return json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8"))
|
|
|
|
|
|
def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool, say, seed: str | None = None) -> str:
|
|
"""Runs the case and returns PASS or FAIL; for a case marked `xfail` (a known, reported bug) XFAIL
|
|
when it fails as expected, and XPASS when it passes, which means the mark has to go."""
|
|
case = load_case(name)
|
|
ok = _run_case(name, case, exe, game_dir, timespeed, watch, say, seed)
|
|
if "xfail" not in case or watch:
|
|
return "PASS" if ok else "FAIL"
|
|
if ok:
|
|
say(f" XPASS the case passes although it is marked xfail ({case['xfail']}): remove the mark")
|
|
return "XPASS"
|
|
say(f" XFAIL fails as expected: {case['xfail']}")
|
|
return "XFAIL"
|
|
|
|
|
|
def exclusive_case(case: dict) -> bool:
|
|
"""A case on a mission of the base scenery with the physicslog on: it removes every physicslog written
|
|
while it ran, those of other cases running at the time too, so it has to run alone."""
|
|
return "vehicle" in case and case.get("physicslog", True)
|
|
|
|
|
|
def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float, watch: bool, say,
|
|
seed: str | None = None) -> bool:
|
|
say(f"\n=== {name}: {case.get('description', '')}")
|
|
out = OUT_DIR / name
|
|
shutil.rmtree(out, ignore_errors=True)
|
|
out.mkdir(parents=True)
|
|
|
|
# the lead vehicle is named after the case, so parallel runs never share a physicslog. a case on a
|
|
# mission of the base scenery (strip_trainsets false) names one of the scenery's own vehicles instead
|
|
own_vehicle = "vehicle" in case
|
|
vehicle = case.get("vehicle", f"autotest_{name}")
|
|
# a long run on a scenery with dozens of AI trains would write a physicslog for each of them into the
|
|
# game dir (3-4 kB per second of simulation and train); such a case turns them off and relies on the
|
|
# result of the test mode and on the log
|
|
with_physicslog = case.get("physicslog", True)
|
|
needs_physicslog = [c["type"] for c in case.get("checks", []) if c["type"] not in LOG_CHECKS]
|
|
if not with_physicslog and (watch or needs_physicslog):
|
|
sys.exit(f"{name}: with physicslog off a case can have log checks only ({', '.join(LOG_CHECKS)}), "
|
|
"and can't run with --watch")
|
|
duration = float(case["duration"]) if "duration" in case else None
|
|
# a case that only records `duration` seconds ends on the test timeout; one that says
|
|
# how the test ends (a pass event, a signal passed at danger...) expects that result
|
|
expect = case.get("expect", "timeout" if duration is not None else "pass")
|
|
if expect not in RESULTS:
|
|
sys.exit(f"{name}: expect must be one of {', '.join(RESULTS)}")
|
|
if watch and duration is None:
|
|
sys.exit(f"{name}: --watch needs a case with duration")
|
|
|
|
ini = out / "autotest.ini"
|
|
# the case's own settings go last, over the common ones; then the seed of this run of the suite, if any
|
|
settings = [*case.get("ini", []), *([f"randomseed {seed}"] if seed else [])]
|
|
ini.write_text(TEST_INI.format(timespeed=timespeed, physicslog="yes" if with_physicslog else "no")
|
|
+ "".join(line + "\n" for line in settings), encoding="ascii")
|
|
physicslog = game_dir / "physicslog" / f"{vehicle}.dat"
|
|
started = time.time() - 1
|
|
# from here on the case has files of its own in the game dir (the vehicle variants, the timetable)
|
|
try:
|
|
scenery = build_scenery(case, game_dir, name, vehicle)
|
|
result = run_simulator(exe, game_dir, scenery, ini, physicslog,
|
|
duration, float(case.get("timeout", 600)), watch, say,
|
|
expect_rows=with_physicslog and not own_vehicle)
|
|
finally:
|
|
# the case's own files go from the game dir also when the run is broken off (ctrl+c)
|
|
timetable_path(game_dir, name).unlink(missing_ok=True)
|
|
remove_vehicle_variants(case, game_dir, name)
|
|
# a case that asked for no geometry cache (file.binary.terrain no) leaves none of an earlier run behind
|
|
if any(line.split()[:2] == ["file.binary.terrain", "no"] for line in case.get("ini", [])):
|
|
scenery_cache(game_dir, name).unlink(missing_ok=True)
|
|
|
|
# the logs are ours alone (named after the case scenery), move them out of the game dir
|
|
for kind, path in result.logs.items():
|
|
shutil.move(path, out / f"{kind}.txt")
|
|
if physicslog.exists():
|
|
shutil.move(physicslog, out / physicslog.name)
|
|
# other trains of the case with a driver, named <something>_<vehicle>, log too
|
|
for other in physicslog.parent.glob(f"*_{vehicle}.dat"):
|
|
shutil.move(other, out / other.name)
|
|
# on a mission of the base scenery every train with a driver logs under its own name, the road vehicles
|
|
# too (250 files and 740 MB after 900 s of Wrzosy): the ones written in this run are removed, nothing
|
|
# checks them (so such a case can't share the game dir with another run at the time: main() runs it
|
|
# alone, see exclusive_case()). a file still held open by another simulator is left where it is
|
|
if own_vehicle and with_physicslog:
|
|
for other in physicslog.parent.glob("*.dat"):
|
|
try:
|
|
if other.stat().st_mtime >= started:
|
|
other.unlink()
|
|
except OSError as error:
|
|
say(f" left {other.name} in the game dir: {error}")
|
|
# the black box is named after the case scenery too
|
|
if result.blackbox:
|
|
result.blackbox = Path(shutil.move(result.blackbox, out / f"{vehicle}.blackbox"))
|
|
|
|
ok = True
|
|
sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0
|
|
say(f" ran {result.wall_seconds:.0f}s wall, {sim_t:.1f}s of physicslog, results in {out.relative_to(REPO)}")
|
|
if watch:
|
|
if result.exit_code is not None:
|
|
say(f" FAIL simulator exited on its own with code {result.exit_code}")
|
|
ok = False
|
|
else:
|
|
if result.verdict:
|
|
say(f" {result.verdict}")
|
|
got = EXIT_RESULTS.get(result.exit_code) if result.exit_code is not None else None
|
|
if got == "timeout" and "of real time" in result.verdict:
|
|
got = WALL_TIMEOUT
|
|
passed = got == expect
|
|
watchdog = ", from the real time watchdog" if got == WALL_TIMEOUT else ""
|
|
say(f" {'PASS' if passed else 'FAIL'} exit code {describe_exit(result.exit_code)}{watchdog}, expected {expect}")
|
|
ok &= passed
|
|
# a run cut short (the real time watchdog, an error, a crash, or closed by us) could have been writing
|
|
# the scenery's geometry cache. the simulator writes it through <name>.sbt.tmp and turns down a cut-short
|
|
# one, but older builds wrote it in place and checked only its header, so the next runs would read a
|
|
# truncated one. either is written again on the next run
|
|
if result.failure or (not watch and got in (None, "error", WALL_TIMEOUT)):
|
|
cache = scenery_cache(game_dir, name)
|
|
cache.unlink(missing_ok=True)
|
|
cache.with_name(cache.name + ".tmp").unlink(missing_ok=True)
|
|
if result.failure:
|
|
say(f" FAIL {result.failure}")
|
|
ok = False
|
|
if not result.rows and needs_physicslog:
|
|
if not result.failure:
|
|
say(f" FAIL no physicslog for '{vehicle}'")
|
|
return False
|
|
|
|
log = read_text(out / "log.txt")
|
|
box = read_blackbox(result.blackbox)
|
|
for check in case.get("checks", []):
|
|
params = {k: v for k, v in check.items() if k != "type"}
|
|
if check["type"] in LOG_CHECKS:
|
|
# with no log text a log check proves nothing, log_lacks would pass vacuously
|
|
if log.strip():
|
|
passed, detail = LOG_CHECKS[check["type"]](log, **params)
|
|
else:
|
|
passed, detail = False, "log.txt is missing or empty"
|
|
elif check["type"] in BLACKBOX_CHECKS:
|
|
if box is not None:
|
|
# vehicles are named as in the fragment
|
|
params = {k: v.replace("{{vehicle}}", vehicle) if isinstance(v, str) else v for k, v in params.items()}
|
|
passed, detail = BLACKBOX_CHECKS[check["type"]](box, **params)
|
|
elif result.blackbox:
|
|
passed, detail = False, f"{result.blackbox.name} is not a black box, or is damaged"
|
|
else:
|
|
passed, detail = False, "the run left no black box (physicslog/*.blackbox); the build is too old, or has blackbox no"
|
|
else:
|
|
passed, detail = CHECKS[check["type"]](result.rows, **params)
|
|
say(f" {'PASS' if passed else 'FAIL'} {check['type']}: {detail}")
|
|
ok &= passed
|
|
|
|
errors = count_lines(out / "errors.txt")
|
|
if errors:
|
|
say(f" note errors.txt has {errors} line(s)")
|
|
if case.get("fail_on_errors") and errors:
|
|
ok = False
|
|
return ok
|
|
|
|
|
|
def main() -> int:
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
ap.add_argument("cases", nargs="*", help="case names from cases/ (default: all)")
|
|
ap.add_argument("--game-dir", default=os.environ.get("EU07_GAME_DIR"),
|
|
help="game install with scenery/ and dynamic/ (or EU07_GAME_DIR)")
|
|
ap.add_argument("--exe", help="simulator executable (default: newest cmake-build-*/bin/Release/eu07*.exe)")
|
|
ap.add_argument("--watch", action="store_true",
|
|
help="run in a visible window in real time (see --timespeed) instead of the test mode, "
|
|
"closed after the case's duration; the exit code isn't checked")
|
|
ap.add_argument("--timespeed", type=float, default=1.0,
|
|
help="with --watch: simulation time multiplier, the simulator offers 1, 5, 20 and 60 (default 1)")
|
|
ap.add_argument("-j", "--jobs", type=int, default=1,
|
|
help="cases run at once, each in a simulator of its own (default 1)")
|
|
ap.add_argument("--seed", help="seed of the simulator's random numbers for this run (randomseed), a number or a "
|
|
"word; the default is the fixed one of the test mode. For bugs that show up only sometimes")
|
|
ap.add_argument("--slow", action="store_true",
|
|
help="with no cases named: run the ones marked slow too (they are skipped otherwise)")
|
|
args = ap.parse_args()
|
|
|
|
if not args.game_dir:
|
|
sys.exit("pass --game-dir or set EU07_GAME_DIR")
|
|
game_dir = Path(args.game_dir).resolve()
|
|
exe = find_exe(args.exe)
|
|
print(f"exe: {exe}\ngame: {game_dir}")
|
|
|
|
names = args.cases or sorted(p.stem for p in CASES_DIR.glob("*.json"))
|
|
missing = [n for n in names if not (CASES_DIR / f"{n}.json").exists()]
|
|
if missing:
|
|
sys.exit("no such case: " + ", ".join(missing))
|
|
# a case marked slow (a whole mission on a big scenery, many minutes) runs when named, or with --slow
|
|
if not args.cases and not args.slow:
|
|
slow = [n for n in names if load_case(n).get("slow")]
|
|
if slow:
|
|
names = [n for n in names if n not in slow]
|
|
print(f"skipped {len(slow)} slow case(s), run them by name or with --slow: {', '.join(slow)}")
|
|
|
|
started = time.monotonic()
|
|
results = {}
|
|
if args.jobs <= 1:
|
|
def say(line, progress=False):
|
|
print(line, flush=True)
|
|
for n in names:
|
|
results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, say, args.seed)
|
|
else:
|
|
# a case on a mission of the base scenery removes the physicslogs written while it ran, so it runs
|
|
# alone, after the others
|
|
alone = [n for n in names if exclusive_case(load_case(n))]
|
|
together = [n for n in names if n not in alone]
|
|
if alone:
|
|
print(f"run alone after the others, they clear the physicslogs of the game dir: {', '.join(alone)}")
|
|
# each case prints its block when it is done, so parallel output does not interleave
|
|
def job(n):
|
|
lines = []
|
|
def say(line, progress=False):
|
|
if not progress:
|
|
lines.append(line)
|
|
status = run_case(n, exe, game_dir, args.timespeed, args.watch, say, args.seed)
|
|
return n, status, lines
|
|
with ThreadPoolExecutor(max_workers=args.jobs) as pool:
|
|
for n in together:
|
|
print(f"started {n}", flush=True)
|
|
for fut in as_completed([pool.submit(job, n) for n in together]):
|
|
n, status, lines = fut.result()
|
|
print("\n".join(lines), flush=True)
|
|
results[n] = status
|
|
for n in alone:
|
|
results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch,
|
|
lambda line, progress=False: print(line, flush=True), args.seed)
|
|
|
|
print(f"\n=== summary ({time.monotonic() - started:.0f}s)")
|
|
for n in names:
|
|
print(f" {results[n]:5} {n}")
|
|
# a known failure keeps the suite green; one that stopped failing doesn't, so that its mark gets removed
|
|
return 0 if all(status in ("PASS", "XFAIL") for status in results.values()) else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|