diff --git a/.gitignore b/.gitignore index d53dadc..279c4bb 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,8 @@ __pycache__/ venv/ env/ +esp/ + # Generated data files — ignore everything in logs/ simulation/logs/ *.log diff --git a/AGENTS.md b/AGENTS.md index 0dd05f7..b9eb3c1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -173,6 +173,15 @@ with `linkhub query` before writing one-off parsing code. Use the native See `design/linkhub.md` for the full interface. Do not export duplicate transport logs. +For timing, phase or spectra, use vehicle timestamps, not LinkHub receive +time: `DEBUG_FLOAT_ARRAY.time_usec` (rawes.lua boot time), +`ATTITUDE_QUATERNION.time_boot_ms` and `SERVO_OUTPUT_RAW.time_usec` share one +clock. `PID_TUNING` has no timestamp, so treat it as receive-timed (statistics +only). Expect dropouts; measure delivered rates rather than trusting requests. +Experiments made since the start-of-experiment snapshot hold the vehicle's +actual parameters in `parameters.json` and scripts in `scripts/`; prefer them +over `.parm` defaults (see `design/linkhub.md#experiments`). + ## Core Invariants (summary) - Frames: simulation physics runs NED world + FRD body. diff --git a/README.md b/README.md index 681c599..031b43b 100644 --- a/README.md +++ b/README.md @@ -211,7 +211,8 @@ if any installation or build fails; restart Windows if requested and rerun it. On native Linux, install uv, Node.js 24.x/npm, and Rust/Cargo before running `bash setup.sh`; system build prerequisites are not installed automatically. -`run_linkhub_ui.cmd --build ` calls `setup.cmd` before launching. +`run_linkhub_ui.cmd --build ` builds the LinkHub binary and UI +before launching, without the full project's setup and checks. Without `--build`, the launcher reuses existing artifacts, running setup automatically if the LinkHub binary or compiled UI is missing, or the binary rejects the launcher's arguments. See the [launcher documentation](linkhub-ui/README.md#live-ui). diff --git a/analysis/analyze_motor_sessions.py b/analysis/analyze_motor_sessions.py new file mode 100644 index 0000000..d8a60b5 --- /dev/null +++ b/analysis/analyze_motor_sessions.py @@ -0,0 +1,543 @@ +"""Analyze yaw control in LinkHub experiment and motor-session exports offline.""" + +from __future__ import annotations + +import argparse +import bisect +import json +import math +from collections import Counter, defaultdict +from dataclasses import dataclass +from pathlib import Path +from statistics import fmean + +from analysis.linkhub_journal import cursor_sequence +from groundstation.rawes_diag import diag_values + +BIN_S = 0.1 +HEARTBEAT_MAX_AGE_S = 3.0 +TRIM_MAX_AGE_S = 1.0 +WINDOW_S = 10.0 +# Vehicle-to-session clock offsets are re-estimated per chunk to follow drift +# between the autopilot crystal and the host clock. +CLOCK_CHUNK_S = 30.0 + + +@dataclass(frozen=True, slots=True) +class Point: + time: float + value: float + block: int + + +def vehicle_time_s(name: str, fields: dict) -> float | None: + """Vehicle boot time of a message, if it carries one. + + rawes.lua stamps DEBUG_FLOAT_ARRAY.time_usec with its boot time; ArduPilot + stamps SERVO_OUTPUT_RAW.time_usec and ATTITUDE*.time_boot_ms on the same + clock. PID_TUNING and RPM carry no timestamp. + """ + if name in ("DEBUG_FLOAT_ARRAY", "SERVO_OUTPUT_RAW"): + value = numeric(fields, "time_usec") + return value / 1e6 if value is not None and value > 0 else None + if name in ("ATTITUDE", "ATTITUDE_QUATERNION"): + value = numeric(fields, "time_boot_ms") + return value / 1e3 if value is not None and value > 0 else None + return None + + +class VehicleClock: + """Maps vehicle boot time onto the session's receive-time axis. + + Per clock epoch and CLOCK_CHUNK_S of vehicle time, the smallest + receive-minus-vehicle offset is the least-delayed delivery; offsets are + interpolated between those anchors. Receive time additionally carries + link batching, which this removes. + """ + + def __init__(self, samples: list[tuple[int, float, float]]): + lowest: dict[tuple[int, int], tuple[float, float]] = {} + for epoch, receive_s, vehicle_s in samples: + key = (epoch, math.floor(vehicle_s / CLOCK_CHUNK_S)) + offset = receive_s - vehicle_s + if key not in lowest or offset < lowest[key][1]: + lowest[key] = (vehicle_s, offset) + self.anchors: dict[int, list[tuple[float, float]]] = defaultdict(list) + for (epoch, _), anchor in sorted(lowest.items()): + self.anchors[epoch].append(anchor) + latencies = [ + receive_s - mapped + for epoch, receive_s, vehicle_s in samples + if (mapped := self.session_time(epoch, vehicle_s)) is not None + ] + self.latency_ms = { + "samples": len(latencies), + "p50": percentile([1000 * value for value in latencies], 0.5), + "p95": percentile([1000 * value for value in latencies], 0.95), + "max": max((1000 * value for value in latencies), default=None), + } + + def session_time(self, epoch: int, vehicle_s: float) -> float | None: + anchors = self.anchors.get(epoch) + if not anchors: + return None + index = bisect.bisect_left(anchors, (vehicle_s, -math.inf)) + if index == 0: + return vehicle_s + anchors[0][1] + if index == len(anchors): + return vehicle_s + anchors[-1][1] + (t0, o0), (t1, o1) = anchors[index - 1], anchors[index] + return vehicle_s + o0 + (o1 - o0) * (vehicle_s - t0) / (t1 - t0) + + +def percentile(values: list[float], fraction: float) -> float | None: + if not values: + return None + ordered = sorted(values) + position = (len(ordered) - 1) * fraction + lo = math.floor(position) + hi = math.ceil(position) + return ordered[lo] + (ordered[hi] - ordered[lo]) * (position - lo) + + +def bins(points: list[Point]) -> dict[tuple[int, int], list[float]]: + result: dict[tuple[int, int], list[float]] = defaultdict(list) + for point in points: + result[point.block, math.floor(point.time / BIN_S + 1e-9)].append(point.value) + return result + + +def summarize(points: list[Point], unit: str) -> dict: + grouped = bins(points) + means = {key: fmean(values) for key, values in grouped.items()} + values = list(means.values()) + mean = fmean(values) if values else None + rms = math.sqrt(fmean(fmean(value * value for value in group) for group in grouped.values())) if values else None + steps = [ + value - means[block, index - 1] + for (block, index), value in means.items() + if (block, index - 1) in means + ] + gaps = [ + right.time - left.time + for left, right in zip(points, points[1:]) + if left.block == right.block + ] + longest = run = 0 + previous: tuple[int, int] | None = None + for key in means: + run = run + 1 if previous == (key[0], key[1] - 1) else 1 + longest = max(longest, run) + previous = key + return { + "unit": unit, + "samples": len(points), + "bins": len(values), + "span_s": points[-1].time - points[0].time if points else 0, + "adjacent_bin_duration_s": len(steps) * BIN_S, + "longest_contiguous_bin_span_s": max(0, longest - 1) * BIN_S, + "max_sample_gap_s": max(gaps, default=None), + "mean": mean, + "rms": rms, + "std": math.sqrt(max(0, rms * rms - mean * mean)) if rms is not None and mean is not None else None, + "min": min(values, default=None), + "max": max(values, default=None), + "raw_peak_abs": max((abs(point.value) for point in points), default=None), + "p95_abs": percentile([abs(value) for value in values], 0.95), + "rms_step_per_100ms": math.sqrt(fmean(step * step for step in steps)) if steps else None, + "p95_abs_slew_per_s": percentile([abs(step) / BIN_S for step in steps], 0.95), + "peak_abs_slew_per_s": max((abs(step) / BIN_S for step in steps), default=None), + "total_variation_per_s": fmean(abs(step) for step in steps) / BIN_S if steps else None, + } + + +def numeric(fields: dict, key: str) -> float | None: + value = fields.get(key) + return float(value) if isinstance(value, (int, float)) and math.isfinite(value) else None + + +def reduction(early: float | None, late: float | None) -> float | None: + return 100 * (early - late) / early if early is not None and early > 1e-12 and late is not None else None + + +def trends(series: dict[str, list[Point]], modes: dict[int, int]) -> list[dict]: + result = [] + for block, mode in modes.items(): + error = [point for point in series["rate_error"] if point.block == block] + if not error or error[-1].time - error[0].time < 8: + continue + start, end = error[0].time, error[-1].time + quarter = (end - start) / 4 + windows = {} + for name, lo, hi in (("early", start, start + quarter), ("late", end - quarter, end)): + windows[name] = { + key: summarize( + [point for point in series[key] if point.block == block and lo <= point.time <= hi], + "deg/s" if key == "rate_error" else "percentage_points", + ) + for key in ("rate_error", "pid_feedback", "trim") + } + if any(windows[name]["rate_error"]["adjacent_bin_duration_s"] < 1 for name in windows): + continue + result.append({ + "block": block, + "mode": mode, + "start_s": start, + "end_s": end, + "windows": windows, + "error_rms_reduction_percent": reduction( + windows["early"]["rate_error"]["rms"], windows["late"]["rate_error"]["rms"], + ), + "pid_feedback_rms_reduction_percent": reduction( + windows["early"]["pid_feedback"]["rms"], windows["late"]["pid_feedback"]["rms"], + ), + }) + return result + + +WINDOW_UNITS = { + "rate_desired": "deg/s", "rate_achieved": "deg/s", "rate_error": "deg/s", + "pid_feedback": "percentage_points", "trim": "percentage_points", + "lua_applied": "percentage_points", "servo9": "us", "motor_rpm": "rpm", +} + + +def segment_summaries(series: dict[str, list[Point]], marks: list[dict], end_s: float) -> list[dict]: + """Signals between each `experiment.mark` and the next mark or the end.""" + if not marks: + return [] + bounds = [mark["time_s"] for mark in marks[1:]] + [end_s] + return [ + { + "label": mark["label"], + "start_s": mark["time_s"], + "end_s": end, + "signals": { + name: summarize( + [point for point in series[name] if mark["time_s"] <= point.time < end], unit, + ) + for name, unit in WINDOW_UNITS.items() + }, + } + for mark, end in zip(marks, bounds, strict=True) + ] + + +def window_summaries(series: dict[str, list[Point]], modes: dict[int, int]) -> list[dict]: + units = WINDOW_UNITS + grouped: dict[tuple[int, int], dict[str, list[Point]]] = defaultdict(lambda: defaultdict(list)) + for name in units: + for point in series[name]: + grouped[point.block, math.floor(point.time / WINDOW_S)][name].append(point) + return [ + { + "block": block, + "mode": modes[block], + "start_s": index * WINDOW_S, + "end_s": (index + 1) * WINDOW_S, + "signals": {name: summarize(points.get(name, []), unit) for name, unit in units.items()}, + } + for (block, index), points in sorted(grouped.items()) + ] + + +def analyze_session(path: Path, rate_band_deg_s: float = 5.0) -> dict: + if not math.isfinite(rate_band_deg_s) or rate_band_deg_s <= 0: + raise ValueError("Rate band must be finite and positive") + with path.open(encoding="utf-8") as stream: + session = json.load(stream) + if "experiment" in session: + experiment = session["experiment"] + metadata = { + **experiment, + "start_time_ns": experiment["started_at_ns"], + "end_time_ns": experiment["stopped_at_ns"], + } + if session["record_count"] != len(session["records"]): + raise ValueError(f"{path}: experiment record count does not match records") + else: + metadata = session["metadata"] + records = session["records"] + expected = cursor_sequence(metadata["start_cursor"]) + identities = { + (record["data"]["system_id"], record["data"]["component_id"]) + for record in records + if record["kind"] == "mavlink.rx" + and record["data"]["message_name"] == "HEARTBEAT" + and record["data"]["fields"].get("autopilot", {}).get("type") == "MAV_AUTOPILOT_ARDUPILOTMEGA" + } + if len(identities) > 1: + raise ValueError(f"{path}: expected at most one ArduPilot heartbeat identity, found {identities}") + identity = next(iter(identities), None) + origin = metadata["start_time_ns"] + clock = VehicleClock([ + (record["sim_clock"]["epoch"], (record["ingest_time_ns"] - origin) / 1e9, stamp) + for record in records + if record["kind"] == "mavlink.rx" + and (record["data"]["system_id"], record["data"]["component_id"]) == identity + and (stamp := vehicle_time_s(record["data"]["message_name"], record["data"]["fields"])) is not None + ]) + series: dict[str, list[Point]] = defaultdict(list) + counts: Counter[str] = Counter() + quality: Counter[str] = Counter() + heartbeat_time: float | None = None + state: tuple[bool, int, int] | None = None + trim: tuple[float, float, int] | None = None + block = 0 + modes: dict[int, int] = {} + previous_ns = origin + rpm_peak: float | None = None + motor_events = [] + marks: list[dict] = [] + + def add(name: str, time: float, value: float) -> None: + series[name].append(Point(time, value, block)) + + for record in records: + if record["sequence"] != expected: + raise ValueError(f"{path}: non-contiguous journal at {expected}") + expected += 1 + ns = record["ingest_time_ns"] + if ns < previous_ns: + raise ValueError(f"{path}: journal ingestion clock moved backwards") + previous_ns = ns + if record["kind"] == "diagnostic.event": + event = record["data"] + if event.get("source") == "linkhub.motor" and event.get("event") in ( + "motor.command", "motor.stop_requested", "motor.stopped", + ): + motor_events.append({ + "time_s": (ns - origin) / 1e9, + "event": event["event"], + "speed_percent": event.get("fields", {}).get("speed_percent"), + }) + elif event.get("event") == "experiment.mark": + marks.append({"time_s": (ns - origin) / 1e9, "label": event["fields"]["label"]}) + if record["kind"] != "mavlink.rx": + continue + data = record["data"] + if (data["system_id"], data["component_id"]) != identity: + continue + name, fields = data["message_name"], data["fields"] + counts[name] += 1 + time = (ns - origin) / 1e9 + if name == "RPM": + rpm = numeric(fields, "rpm1") + if rpm is not None and rpm >= 0: + rpm_peak = rpm if rpm_peak is None else max(rpm_peak, rpm) + if name == "HEARTBEAT": + flags = fields["base_mode"].split(" | ") + new_state = ( + "MAV_MODE_FLAG_SAFETY_ARMED" in flags, + int(fields["custom_mode"]), + record["sim_clock"]["epoch"], + ) + if new_state != state or heartbeat_time is None or time - heartbeat_time > HEARTBEAT_MAX_AGE_S: + block += 1 + trim = None + state = new_state + heartbeat_time = time + if state[0]: + modes[block] = state[1] + if name not in ("PID_TUNING", "DEBUG_FLOAT_ARRAY", "SERVO_OUTPUT_RAW", "RPM"): + continue + if name == "PID_TUNING" and fields.get("axis", {}).get("type") != "PID_TUNING_YAW": + continue + if state is None or heartbeat_time is None or time - heartbeat_time > HEARTBEAT_MAX_AGE_S: + quality["samples_without_fresh_heartbeat"] += 1 + continue + if record["sim_clock"]["epoch"] != state[2]: + quality["samples_from_changed_clock_epoch"] += 1 + continue + if not state[0]: + quality["disarmed_samples_excluded"] += 1 + continue + # Gating above uses receive time; stamped samples are placed at their + # vehicle time so link batching does not distort their spacing. + stamp = vehicle_time_s(name, fields) + if stamp is not None and (mapped := clock.session_time(record["sim_clock"]["epoch"], stamp)) is not None: + time = mapped + quality["vehicle_timed_samples"] += 1 + if name == "RPM": + rpm = numeric(fields, "rpm1") + if rpm is not None and rpm >= 0: + add("motor_rpm", time, rpm) + elif name == "PID_TUNING": + values = [numeric(fields, key) for key in ("desired", "achieved", "P", "I", "D", "FF")] + if any(value is None for value in values): + quality["invalid_pid_samples"] += 1 + continue + desired, achieved, p, i, d, ff = values + assert desired is not None and achieved is not None + assert p is not None and i is not None and d is not None and ff is not None + add("rate_desired", time, math.degrees(desired)) + add("rate_achieved", time, math.degrees(achieved)) + add("rate_error", time, math.degrees(desired - achieved)) + for key, value in (("pid_p", p), ("pid_i", i), ("pid_d", d), ("pid_ff", ff)): + add(key, time, value * 100) + feedback = p + i + d + add("pid_feedback", time, feedback * 100) + if trim is not None and trim[2] == block and 0 <= time - trim[0] <= TRIM_MAX_AGE_S: + add("trim_plus_reported_pid_terms", time, (trim[1] + feedback + ff) * 100) + else: + quality["pid_samples_without_recent_trim_frame"] += 1 + elif name == "DEBUG_FLOAT_ARRAY": + decoded = diag_values(int(fields["array_id"]), fields["data"]) + for key, signal, scale in ( + ("YFF_T", "trim", 100), ("YFF_U", "lua_applied", 100), + ("YFF_GZ", "lua_gyro", 180 / math.pi), + ): + value = numeric(decoded, key) + if value is not None: + add(signal, time, value * scale) + elif key in decoded: + quality["invalid_diag_values"] += 1 + current_trim = numeric(decoded, "YFF_T") + trim = (time, current_trim, block) if current_trim is not None else None + applied = numeric(decoded, "YFF_U") + if applied is not None and current_trim is not None: + add("applied_minus_trim", time, (applied - current_trim) * 100) + elif fields.get("port") == 0: + pwm = numeric(fields, "servo9_raw") + if pwm is not None and pwm >= 500: + add("servo9", time, pwm) + else: + quality["disabled_or_invalid_servo_samples"] += 1 + if expected - 1 != cursor_sequence(metadata["end_cursor"]): + raise ValueError(f"{path}: export ends before its declared end cursor") + for points in series.values(): + points.sort(key=lambda point: point.time) + + names = ( + "rate_desired", "rate_achieved", "rate_error", "pid_p", "pid_i", "pid_d", + "pid_ff", "pid_feedback", "trim", "lua_applied", "applied_minus_trim", + "trim_plus_reported_pid_terms", "servo9", "lua_gyro", "motor_rpm", + ) + summaries = { + key: summarize(series[key], "us" if key == "servo9" else "rpm" if key == "motor_rpm" else + "deg/s" if key.startswith("rate_") or key == "lua_gyro" else "percentage_points") + for key in names + } + error_bins = bins(series["rate_error"]) + in_band = sum(max(abs(value) for value in values) <= rate_band_deg_s for values in error_bins.values()) + warnings = [ + "Observational comparisons cannot isolate the causal benefit of trim from PID, RPM, load or setpoint changes.", + "100 ms bin means suppress residual timing spikes, but cannot prove high-frequency actuator smoothness; " + "PID_TUNING and RPM have no vehicle timestamp and stay on receive time.", + "Missing pre-session state is not reconstructed; only fresh armed vehicle heartbeats enable control analysis.", + "A recent Lua diagnostic frame does not prove its persisted trim/readback values were recently updated.", + "Trim plus reported PID terms is not an actuator command: D_FF, feedforward scaling, mixer offsets/gates and mapping are not reconstructed.", + ] + if identity is None: + warnings.append("No ArduPilot heartbeat observed; vehicle control analysis is unavailable.") + for key in names: + if not series[key]: + warnings.append(f"No usable armed {key} samples; metrics are null.") + if summaries["rate_error"]["longest_contiguous_bin_span_s"] < 2: + warnings.append("Less than 2 seconds of contiguous armed yaw PID data; effectiveness is inconclusive.") + if summaries["trim"]["max_sample_gap_s"] is not None and summaries["trim"]["max_sample_gap_s"] > TRIM_MAX_AGE_S: + warnings.append("Trim frame gaps exceed the age limit; unmatched PID samples do not assume zero trim.") + applied_values = [point.value for point in series["lua_applied"]] + servo_values = [point.value for point in series["servo9"]] + if applied_values and servo_values and max(map(abs, applied_values)) < 1e-6 and max(servo_values) - min(servo_values) > 20: + warnings.append("Lua reports zero applied throttle while SERVO9 PWM varies by >20 us; inspect readback mapping before judging trim.") + if quality: + warnings.append("Excluded or unmatched samples are counted in quality.exclusions.") + return { + "file": str(path), + "metadata": metadata, + "duration_s": (metadata["end_time_ns"] - origin) / 1e9, + "vehicle": {"system_id": identity[0], "component_id": identity[1]} if identity else None, + "peak_motor_rpm": rpm_peak, + "armed_blocks": [{"block": key, "mode": mode} for key, mode in modes.items()], + "quality": { + "vehicle_message_counts": dict(counts), + "exclusions": dict(quality), + "receive_latency_ms_after_vehicle_time": clock.latency_ms, + }, + "signals": summaries, + "tracking": { + "rate_band_deg_s": rate_band_deg_s, + "observed_bins_fully_within_band_percent": 100 * in_band / len(error_bins) if error_bins else None, + }, + "early_late_comparisons": trends(series, modes), + "motor_events": motor_events, + "marks": marks, + "segments": segment_summaries(series, marks, (metadata["end_time_ns"] - origin) / 1e9), + "windows": window_summaries(series, modes), + "warnings": warnings, + } + + +def analyze(input_path: Path, rate_band_deg_s: float = 5.0) -> dict: + if input_path.is_dir() and not (input_path / "index.json").exists(): + source = input_path + paths = sorted(input_path.glob("*/mavlog.json")) + if (input_path / "mavlog.json").is_file(): + paths.insert(0, input_path / "mavlog.json") + else: + source = input_path / "index.json" if input_path.is_dir() else input_path + with source.open(encoding="utf-8") as stream: + data = json.load(stream) + paths = [source.parent / session["file"] for session in data["sessions"]] if "sessions" in data else [source] + del data + if not paths: + raise ValueError(f"{source}: no sessions") + return { + "schema_version": 1, + "input": str(source), + "method": { + "time_basis": ( + "Session seconds from LinkHub ingest_time_ns. DEBUG_FLOAT_ARRAY and SERVO_OUTPUT_RAW " + "are placed at their vehicle time_usec, mapped per clock epoch by the lowest " + "receive-minus-vehicle offset in each 30 s chunk; PID_TUNING, RPM and heartbeat " + "gating use receive time." + ), + "bin_seconds": BIN_S, + "statistics": "Bins have equal weight; RMS uses within-bin mean squares, not squared bin means. Raw peaks retain extremes.", + "smoothness": "Adjacent bins within one armed/mode/clock block only; missing bins are not bridged.", + "heartbeat_max_age_s": HEARTBEAT_MAX_AGE_S, + "trim_max_age_s": TRIM_MAX_AGE_S, + "early_late": "First/last quarter of each >=8 s armed PID block; each window needs >=1 s adjacent-bin coverage.", + "windows": "Fixed 10 s session-time windows split by armed/mode/clock block; short or sparse windows are not steady-state proof.", + "segments": "From each experiment.mark to the next mark or the experiment end; includes the transition after each mark.", + "pid_terms": "Trim + reported P + I + D + FF is a partial, unclamped sum; it omits D_FF, feedforward scaling, mixer offsets/gates and mapping.", + "trim_units": "Percentage points of normalized throttle; no assumed servo calibration or observer gain.", + }, + "sessions": [analyze_session(path, rate_band_deg_s) for path in paths], + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("input", type=Path, help="Experiment, session export, index.json, or directory of exports") + parser.add_argument("--output", type=Path, help="Default: yaw_analysis.json beside the input") + parser.add_argument("--rate-band-deg-s", type=float, default=5.0) + args = parser.parse_args() + result = analyze(args.input, args.rate_band_deg_s) + parent = args.input if args.input.is_dir() else args.input.parent + output = args.output or parent / "yaw_analysis.json" + sources = {Path(session["file"]).resolve() for session in result["sessions"]} + if not args.input.is_dir(): + sources.add(args.input.resolve()) + elif (args.input / "index.json").exists(): + sources.add((args.input / "index.json").resolve()) + if output.resolve() in sources: + raise ValueError("Output must not overwrite an input session or index") + output.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n", encoding="utf-8") + print("Session error RMS deg/s PID RMS pp trim mean pp") + for session in result["sessions"]: + signals = session["signals"] + values = [signals[key][metric] for key, metric in + (("rate_error", "rms"), ("pid_feedback", "rms"), ("trim", "mean"))] + formatted = ["n/a" if value is None else f"{value:.3f}" for value in values] + path = Path(session["file"]) + label = path.parent.name if path.name == "mavlog.json" else path.stem + print(f"{label:40} {' '.join(value.rjust(12) for value in formatted)}") + for warning in session["warnings"]: + print(f" WARNING: {warning}") + print(f"Saved {output}") + + +if __name__ == "__main__": + main() diff --git a/analysis/yaw_digital_twin.py b/analysis/yaw_digital_twin.py new file mode 100644 index 0000000..bf3e491 --- /dev/null +++ b/analysis/yaw_digital_twin.py @@ -0,0 +1,823 @@ +"""Offline yaw hypotheses using the real Lua observer and Python AP PID port. + +The plant and its excitation are assumptions, not an identified hardware model. +This tool must not be used to select or deploy flight-controller parameters. +""" + +from __future__ import annotations + +import argparse +import json +import math +from collections import deque +from dataclasses import asdict, dataclass, replace +from pathlib import Path +from typing import Literal + +import numpy as np +from scipy import optimize, signal + +from arduloop.params import RateAxisParams +from arduloop.pid import AC_PID +from groundstation.rawes_diag import diag_values +from simulation.rawes_lua_harness import RawesLua +from simulation.torque_model import HubParams, HubState, step + +DT = 0.0025 +LUA_INTERVAL = 4 +# rawes.lua constants: 100 Hz tick with a fixed dt, fixed slope-conversion span +# and bench-default slope used when RAWES_YAW_SLP is 0. +LUA_DT = 0.01 +SERVO9_SPAN_US = 1000.0 +DEFAULT_YAW_SLOPE_RPM_PER_US = 0.504 +# Vehicle-clock spacing beyond which a 200 Hz stream is treated as a dropout. +MAX_STREAM_GAP_S = 0.03 +PEAK_SEARCH_HZ = (3.0, 15.0) +# Transition skipped after an experiment.mark before its segment is analysed. +MARK_SETTLE_S = 1.0 +Hypothesis = Literal["sensor", "torque"] + + +@dataclass(frozen=True) +class ObserverReplay: + """The deployed Lua observer re-run on vehicle-timed servo and gyro data.""" + + segments: int + replay_seconds: float + compared_samples: int + servo_min_us: float + servo_span_us: float + servo_map_rms: float + gyro_alignment_rms_deg_s: float + gyro_alignment_lag_ms: float + default_trim_rms: float + fitted_tau_s: float + fitted_slope_rpm_per_us: float + fitted_trim_rms: float + recorded_trim_amplitude: float + replayed_trim_amplitude: float + output_amplitude: float + + +@dataclass(frozen=True) +class Observation: + start_s: float + end_s: float + yaw_std_deg_s: float + p_std: float + trim_mean: float + trim_std: float + output_std: float + motor_rpm_mean: float + motor_rpm_std: float + pid_samples: int + diagnostic_samples: int + excluded_samples: int + vehicle_mode: int + phase_blocks: int + output_relative_gyro_phase_deg: float | None + stream_coverage_fraction: float + diagnostic_interval_ms: float + diagnostic_lost_fraction: float + peak_hz: float | None + gyro_peak_amplitude_deg_s: float | None + replay: ObserverReplay | None + replay_note: str | None + + +def harmonic_amplitude(t: np.ndarray, x: np.ndarray, frequency_hz: float) -> float: + """Sinusoid amplitude at a known frequency for irregular, gapped samples.""" + t = np.asarray(t, dtype=float) + x = np.asarray(x, dtype=float) + omega = math.tau * frequency_hz + basis = np.column_stack( + [np.sin(omega * t), np.cos(omega * t), np.ones_like(t), t - t.mean()] + ) + coefficients, *_ = np.linalg.lstsq(basis, x, rcond=None) + return float(math.hypot(coefficients[0], coefficients[1])) + + +def peak_frequency(t: np.ndarray, x: np.ndarray) -> tuple[float, float]: + """Frequency and amplitude of the strongest sinusoid in PEAK_SEARCH_HZ.""" + candidates = np.arange(PEAK_SEARCH_HZ[0], PEAK_SEARCH_HZ[1] + 1e-9, 0.02) + amplitudes = [harmonic_amplitude(t, x, f) for f in candidates] + best = int(np.argmax(amplitudes)) + return float(candidates[best]), float(amplitudes[best]) + + +def _vehicle_series(samples: list[tuple[float, ...]], columns: int) -> np.ndarray: + a = np.asarray(samples, dtype=float).reshape(-1, columns) + if np.any(np.diff(a[:, 0]) < 0): + raise ValueError("Vehicle clock moved backward or wrapped in an observation window") + _, index = np.unique(a[:, 0], return_index=True) + return a[index] + + +def _covered_spans(times: np.ndarray, max_gap: float) -> list[tuple[float, float]]: + if len(times) < 2: + return [] + breaks = np.flatnonzero(np.diff(times) > max_gap) + starts = np.r_[0, breaks + 1] + ends = np.r_[breaks, len(times) - 1] + return [(float(times[s]), float(times[e])) for s, e in zip(starts, ends, strict=True) if e > s] + + +def _intersect(a: list[tuple[float, float]], b: list[tuple[float, float]]) -> list[tuple[float, float]]: + spans = [] + for a0, a1 in a: + for b0, b1 in b: + start, end = max(a0, b0), min(a1, b1) + if end > start: + spans.append((start, end)) + return sorted(spans) + + +def _inside(t: np.ndarray, spans: list[tuple[float, float]]) -> np.ndarray: + mask = np.zeros(len(t), dtype=bool) + for start, end in spans: + mask |= (t >= start) & (t <= end) + return mask + + +def _replay_segments( + tau_s: float, + slope_rpm_per_us: float, + segments: list[tuple[np.ndarray, np.ndarray, np.ndarray, float]], +) -> list[np.ndarray]: + """Trim from the actual Lua observer for each (ticks, u, gyro, seed) segment.""" + lua = RawesLua(RAWES_YFF_TAU=tau_s, RAWES_YAW_SLP=slope_rpm_per_us) + results = [] + for _, u, gyro, seed in segments: + lua.fns.yaw_trim_reset() + lua.fns.yaw_trim_step(1e6, seed, 0.0) + results.append(np.array([ + float(lua.fns.yaw_trim_step(LUA_DT, float(a), float(b))) + for a, b in zip(u, gyro, strict=True) + ])) + return results + + +def replay_observer( + attitude: np.ndarray, servo: np.ndarray, diagnostic: np.ndarray, frequency_hz: float +) -> ObserverReplay: + """Re-run rawes.lua's yaw_trim_step on vehicle-timed servo 9 PWM and gyro z. + + The servo PWM-to-throttle map is fitted from the recorded YFF_U readback, + so it is the map Lua actually used. Each dropout-free span is seeded from + the recorded YFF_T and compared with later YFF_T samples in that span. + """ + attitude_spans = _covered_spans(attitude[:, 0], MAX_STREAM_GAP_S) + servo_spans = _covered_spans(servo[:, 0], MAX_STREAM_GAP_S) + spans = [s for s in _intersect(attitude_spans, servo_spans) if s[1] - s[0] >= 0.2] + t_diag, trim, readback, gyro_used = diagnostic.T + covered = _inside(t_diag, spans) + pwm_at_diag = np.interp(t_diag, servo[:, 0], servo[:, 1]) + mapped = covered & (readback > 0.02) & (readback < 0.98) + if mapped.sum() < 10: + raise ValueError("Too few unclamped YFF_U samples inside covered spans") + slope, offset = np.polyfit(pwm_at_diag[mapped], readback[mapped], 1) + if slope <= 0: + raise ValueError("YFF_U does not increase with servo 9 PWM") + servo_map_rms = float(np.sqrt(np.mean( + (slope * pwm_at_diag[mapped] + offset - readback[mapped]) ** 2 + ))) + lags = np.arange(-0.02, 0.02001, 0.0025) + alignment = [ + float(np.sqrt(np.mean(( + np.interp(t_diag[covered] + lag, attitude[:, 0], attitude[:, 1]) - gyro_used[covered] + ) ** 2))) + for lag in lags + ] + best_lag = int(np.argmin(alignment)) + + segments = [] + compare: list[tuple[np.ndarray, np.ndarray, np.ndarray]] = [] + for start, end in spans: + inside = np.flatnonzero((t_diag >= start) & (t_diag <= end)) + if len(inside) < 3: + continue + seed_time = t_diag[inside[0]] + ticks = np.arange(seed_time + LUA_DT, end, LUA_DT) + if len(ticks) < 10: + continue + u = np.clip(slope * np.interp(ticks, servo[:, 0], servo[:, 1]) + offset, 0.0, 1.0) + g = np.interp(ticks, attitude[:, 0], attitude[:, 1]) + segments.append((ticks, u, g, float(trim[inside[0]]))) + later = inside[1:][t_diag[inside[1:]] <= ticks[-1]] + compare.append((ticks, t_diag[later], trim[later])) + compared = sum(len(c[1]) for c in compare) + if not segments or compared < 10: + raise ValueError("Too few dropout-free spans with diagnostic samples to replay") + + def rms(tau_s: float, slope_rpm: float) -> float: + replayed = _replay_segments(tau_s, slope_rpm, segments) + errors = np.concatenate([ + np.interp(times, ticks, values) - recorded + for (ticks, times, recorded), values in zip(compare, replayed, strict=True) + ]) + return float(np.sqrt(np.mean(errors ** 2))) + + default_rms = rms(0.3, DEFAULT_YAW_SLOPE_RPM_PER_US) + fit = optimize.minimize( + lambda x: rms(math.exp(x[0]), math.exp(x[1])), + x0=[math.log(0.3), math.log(DEFAULT_YAW_SLOPE_RPM_PER_US)], + method="Nelder-Mead", + options={"xatol": 1e-3, "fatol": 1e-7, "maxiter": 120}, + ) + tau_fit, slope_fit = (math.exp(v) for v in fit.x) + replayed = _replay_segments(tau_fit, slope_fit, segments) + all_ticks = np.concatenate([s[0] for s in segments]) + all_u = np.concatenate([s[1] for s in segments]) + return ObserverReplay( + segments=len(segments), + replay_seconds=float(len(all_ticks) * LUA_DT), + compared_samples=compared, + servo_min_us=float(-offset / slope), + servo_span_us=float(1 / slope), + servo_map_rms=servo_map_rms, + gyro_alignment_rms_deg_s=float(np.degrees(alignment[best_lag])), + gyro_alignment_lag_ms=float(lags[best_lag] * 1000), + default_trim_rms=default_rms, + fitted_tau_s=tau_fit, + fitted_slope_rpm_per_us=slope_fit, + fitted_trim_rms=float(fit.fun), + recorded_trim_amplitude=harmonic_amplitude( + t_diag[covered], trim[covered], frequency_hz + ), + replayed_trim_amplitude=harmonic_amplitude( + all_ticks, np.concatenate(replayed), frequency_hz + ), + output_amplitude=harmonic_amplitude(all_ticks, all_u, frequency_hz), + ) + + +def observed_phase( + attitude: list[tuple[float, float]], servo: list[tuple[float, float]] +) -> tuple[int, float | None]: + """Estimate 8.33 Hz output/gyro phase using unbridged 0.6 s boot-clock blocks.""" + if len(attitude) < 2 or len(servo) < 2: + return 0, None + a, s = np.asarray(attitude), np.asarray(servo) + if np.any(np.diff(a[:, 0]) < 0) or np.any(np.diff(s[:, 0]) < 0): + raise ValueError("Source clock moved backward or wrapped in an observation window") + _, ai = np.unique(a[:, 0], return_index=True) + _, si = np.unique(s[:, 0], return_index=True) + a, s = a[ai], s[si] + if len(a) < 2 or len(s) < 2: + return 0, None + grid = np.arange(max(a[0, 0], s[0, 0]), min(a[-1, 0], s[-1, 0]), 0.02) + + def valid(t: np.ndarray) -> np.ndarray: + index = np.searchsorted(t, grid).clip(1, len(t) - 1) + return (t[index] - t[index - 1]) <= 0.1 + + selected = np.flatnonzero(valid(a[:, 0]) & valid(s[:, 0])) + if not len(selected): + return 0, None + spans = np.split(selected, np.flatnonzero(np.diff(selected) > 1) + 1) + gyro = np.interp(grid, a[:, 0], a[:, 1]) + output = np.interp(grid, s[:, 0], s[:, 1]) + cross = [] + for span in spans: + for offset in range(0, len(span) - 29, 30): + part = span[offset:offset + 30] + frequencies, spectrum = signal.csd( + gyro[part], output[part], fs=50, window="hann", nperseg=30, detrend="linear" + ) + cross.append(spectrum[int(np.argmin(abs(frequencies - 8.3333333333)))]) + if not cross or abs(np.mean(cross)) < 1e-15: + return len(cross), None + return len(cross), float(np.degrees(np.angle(np.mean(cross)))) + + +def observations(path: Path, windows: list[tuple[float, float]]) -> list[Observation]: + """Read selected receive-time windows; PID and diagnostics are not paired.""" + data = json.loads(path.read_bytes()) + if data["record_count"] != len(data["records"]): + raise ValueError(f"{path}: record count mismatch") + origin = data["experiment"]["started_at_ns"] + collected: list[dict[str, list[float]]] = [ + {"yaw": [], "p": [], "trim": [], "output": [], "rpm": []} for _ in windows + ] + clocked: list[dict[str, list[tuple[float, ...]]]] = [ + {"attitude": [], "servo": [], "diagnostic": []} for _ in windows + ] + epochs: list[set[int]] = [set() for _ in windows] + modes: list[set[int]] = [set() for _ in windows] + excluded = [0 for _ in windows] + heartbeat_time: float | None = None + heartbeat_epoch: int | None = None + heartbeat_mode: int | None = None + armed = False + for record in data["records"]: + if record["kind"] != "mavlink.rx": + continue + message = record["data"] + if (message["system_id"], message["component_id"]) != (1, 1): + continue + t = (record["ingest_time_ns"] - origin) / 1e9 + fields = message["fields"] + name = message["message_name"] + if name == "HEARTBEAT": + heartbeat_time = t + heartbeat_epoch = record["sim_clock"]["epoch"] + heartbeat_mode = int(fields["custom_mode"]) + armed = "MAV_MODE_FLAG_SAFETY_ARMED" in fields["base_mode"].split(" | ") + if name not in ("PID_TUNING", "DEBUG_FLOAT_ARRAY", "RPM", + "ATTITUDE_QUATERNION", "SERVO_OUTPUT_RAW"): + continue + for index, ((start, end), out, clocks, seen_epochs, seen_modes) in enumerate(zip( + windows, collected, clocked, epochs, modes, strict=True + )): + if not start <= t < end: + continue + if (heartbeat_time is None or t - heartbeat_time > 3 or not armed + or record["sim_clock"]["epoch"] != heartbeat_epoch or heartbeat_mode is None): + excluded[index] += 1 + continue + seen_modes.add(heartbeat_mode) + if name == "PID_TUNING" and fields["axis"]["type"] == "PID_TUNING_YAW": + out["yaw"].append(float(fields["achieved"])) + out["p"].append(float(fields["P"])) + elif name == "DEBUG_FLOAT_ARRAY": + values = diag_values(fields["array_id"], fields["data"]) + if "YFF_T" in values and "YFF_U" in values: + out["trim"].append(values["YFF_T"]) + out["output"].append(values["YFF_U"]) + if "YFF_GZ" in values: + # time_usec is rawes.lua's vehicle boot time (ms resolution). + clocks["diagnostic"].append(( + fields["time_usec"] / 1e6, + values["YFF_T"], values["YFF_U"], values["YFF_GZ"], + )) + elif name == "RPM" and fields["rpm1"] >= 0: + out["rpm"].append(float(fields["rpm1"])) + elif name == "ATTITUDE_QUATERNION": + clocks["attitude"].append((fields["time_boot_ms"] / 1000, fields["yawspeed"])) + seen_epochs.add(record["sim_clock"]["epoch"]) + elif name == "SERVO_OUTPUT_RAW" and fields["port"] == 0: + clocks["servo"].append((fields["time_usec"] / 1e6, fields["servo9_raw"])) + seen_epochs.add(record["sim_clock"]["epoch"]) + + result = [] + for (start, end), out, clocks, seen_epochs, seen_modes, dropped in zip( + windows, collected, clocked, epochs, modes, excluded, strict=True + ): + if end <= start or any(len(values) < 10 for values in out.values()): + raise ValueError(f"Insufficient samples in {start}-{end} s") + if not all(np.isfinite(values).all() for values in out.values()): + raise ValueError(f"Non-finite telemetry in {start}-{end} s") + if len(seen_epochs) > 1: + raise ValueError(f"Multiple boot epochs in {start}-{end} s") + if len(seen_modes) != 1: + raise ValueError(f"Expected one armed vehicle mode in {start}-{end} s") + blocks, phase = observed_phase(clocks["attitude"], clocks["servo"]) + attitude = _vehicle_series(clocks["attitude"], 2) + servo = _vehicle_series(clocks["servo"], 2) + diagnostic = _vehicle_series(clocks["diagnostic"], 4) + coverage = sum(e - s for s, e in _intersect( + _covered_spans(attitude[:, 0], MAX_STREAM_GAP_S), + _covered_spans(servo[:, 0], MAX_STREAM_GAP_S), + )) + interval = float(np.median(np.diff(diagnostic[:, 0]))) if len(diagnostic) > 2 else math.nan + if len(diagnostic) > 2: + expected = (diagnostic[-1, 0] - diagnostic[0, 0]) / interval + 1 + lost = max(0.0, float(1 - len(diagnostic) / expected)) + else: + lost = math.nan + peak = peak_amplitude = None + replay = None + note = None + if len(attitude) >= 200: + peak, peak_amplitude = peak_frequency(attitude[:, 0], attitude[:, 1]) + try: + replay = replay_observer(attitude, servo, diagnostic, peak) + except ValueError as error: + note = str(error) + else: + note = "Too few vehicle-timed attitude samples for spectrum and replay" + result.append(Observation( + start_s=start, end_s=end, + yaw_std_deg_s=float(np.degrees(out["yaw"]).std()), + p_std=float(np.std(out["p"])), + trim_mean=float(np.mean(out["trim"])), + trim_std=float(np.std(out["trim"])), + output_std=float(np.std(out["output"])), + motor_rpm_mean=float(np.mean(out["rpm"])), + motor_rpm_std=float(np.std(out["rpm"])), + pid_samples=len(out["yaw"]), diagnostic_samples=len(out["trim"]), + excluded_samples=dropped, vehicle_mode=next(iter(seen_modes)), + phase_blocks=blocks, output_relative_gyro_phase_deg=phase, + stream_coverage_fraction=float(coverage / (end - start)), + diagnostic_interval_ms=interval * 1000, + diagnostic_lost_fraction=lost, + peak_hz=peak, + gyro_peak_amplitude_deg_s=( + float(np.degrees(peak_amplitude)) if peak_amplitude is not None else None + ), + replay=replay, replay_note=note, + )) + return result + + +@dataclass(frozen=True) +class Configuration: + trim_equilibrium: float + motor_rpm: float + gear_ratio: float = 10.88 + frequency_hz: float = 8.3 + delay_s: float = 0.005 + yaw_angle_p: float = 5.8 + yaw_rate_p: float = 0.12 + yaw_rate_i: float = 0.018 + yaw_rate_d: float = 0.0 + yaw_rate_ff: float = 0.0 + yaw_rate_imax: float = 1.0 + target_filter_hz: float = 20.0 + error_filter_hz: float = 15.0 + derivative_filter_hz: float = 10.0 + trim_tau_s: float = 0.3 + yaw_slope_rpm_per_us: float = DEFAULT_YAW_SLOPE_RPM_PER_US + duration_s: float = 10.0 + settle_s: float = 5.0 + rotor_step_fraction: float = 0.0 + rotor_step_time_s: float = 3.0 + + +# Captured vehicle parameters and the Configuration fields they set. +PARAMETER_FIELDS = { + "ATC_ANG_YAW_P": "yaw_angle_p", + "ATC_RAT_YAW_P": "yaw_rate_p", + "ATC_RAT_YAW_I": "yaw_rate_i", + "ATC_RAT_YAW_D": "yaw_rate_d", + "ATC_RAT_YAW_FF": "yaw_rate_ff", + "ATC_RAT_YAW_IMAX": "yaw_rate_imax", + "ATC_RAT_YAW_FLTT": "target_filter_hz", + "ATC_RAT_YAW_FLTE": "error_filter_hz", + "ATC_RAT_YAW_FLTD": "derivative_filter_hz", + "RAWES_YFF_TAU": "trim_tau_s", + "RAWES_YAW_SLP": "yaw_slope_rpm_per_us", +} + + +def captured_parameters(experiment: Path) -> dict[str, float] | None: + """Configuration overrides from the experiment's start snapshot, if any.""" + path = experiment.parent / "parameters.json" + if not path.exists(): + return None + values = { + entry["name"]: float(entry["value"]) + for entry in json.loads(path.read_text(encoding="utf-8"))["parameters"] + } + overrides = { + field: values[name] for name, field in PARAMETER_FIELDS.items() if name in values + } + # rawes.lua uses its bench default when RAWES_YAW_SLP is 0. + if overrides.get("yaw_slope_rpm_per_us", 1.0) <= 0: + overrides["yaw_slope_rpm_per_us"] = DEFAULT_YAW_SLOPE_RPM_PER_US + return overrides + + +@dataclass(frozen=True) +class Strategy: + rate_p: float + trim_tau_s: float | None + error_notch_hz: float = 0.0 + + +@dataclass(frozen=True) +class Metrics: + measured_yaw_std_deg_s: float + actual_yaw_std_deg_s: float + output_std: float + trim_std: float + p_std: float + heading_std_deg: float + heading_mean_deg: float + trim_mean: float + motor_rpm_std: float + output_floor_fraction: float + peak_hz: float | None + output_relative_gyro_phase_deg: float | None + + +def simulate(config: Configuration, hypothesis: Hypothesis, amplitude: float, strategy: Strategy) -> Metrics: + """Run one illustrative closed loop, assuming completed runup and linear DDFP.""" + if hypothesis not in ("sensor", "torque"): + raise ValueError(f"Unknown hypothesis: {hypothesis}") + values = ( + config.trim_equilibrium, config.motor_rpm, config.gear_ratio, + config.frequency_hz, config.delay_s, config.yaw_angle_p, + config.yaw_rate_p, config.yaw_rate_i, config.yaw_rate_d, config.yaw_rate_ff, + config.yaw_rate_imax, config.target_filter_hz, config.error_filter_hz, + config.derivative_filter_hz, config.trim_tau_s, config.yaw_slope_rpm_per_us, + config.duration_s, config.settle_s, config.rotor_step_fraction, + config.rotor_step_time_s, amplitude, strategy.rate_p, + strategy.error_notch_hz, + ) + if not all(math.isfinite(value) for value in values): + raise ValueError("Non-finite model configuration") + if not ( + 0 < config.trim_equilibrium < 1 and config.motor_rpm > 0 + and config.gear_ratio > 0 and 0 < config.frequency_hz < 1 / (2 * DT) + and config.delay_s >= 0 and config.yaw_angle_p >= 0 + and config.yaw_rate_p >= 0 and config.yaw_rate_i >= 0 and config.error_filter_hz >= 0 + and config.yaw_rate_d >= 0 and config.yaw_rate_ff >= 0 and config.yaw_rate_imax > 0 + and config.target_filter_hz >= 0 and config.derivative_filter_hz >= 0 + and config.yaw_slope_rpm_per_us > 0 + and config.trim_tau_s > 0 and config.duration_s > config.settle_s >= 0 + and config.rotor_step_fraction > -1 and 0 <= config.rotor_step_time_s < config.duration_s + and amplitude >= 0 and strategy.rate_p >= 0 and strategy.error_notch_hz >= 0 + and (strategy.trim_tau_s is None or ( + math.isfinite(strategy.trim_tau_s) and strategy.trim_tau_s > 0 + )) + ): + raise ValueError("Invalid model configuration") + delay_steps = round(config.delay_s / DT) + if not math.isclose(delay_steps * DT, config.delay_s, abs_tol=1e-9): + raise ValueError("Delay must be a whole number of 2.5 ms steps") + + omega_motor = config.motor_rpm * math.tau / 60 + omega_rotor = omega_motor / config.gear_ratio + plant = HubParams( + gear_ratio=config.gear_ratio, + rpm_scale=omega_motor / config.trim_equilibrium, + ) + lua = RawesLua( + RAWES_YFF_TAU=strategy.trim_tau_s or config.trim_tau_s, + RAWES_YAW_SLP=config.yaw_slope_rpm_per_us, + ) + lua.fns.yaw_trim_reset() + lua.fns.yaw_trim_step(1e6, config.trim_equilibrium, 0) + trim = config.trim_equilibrium + params = RateAxisParams( + P=strategy.rate_p, I=config.yaw_rate_i, D=config.yaw_rate_d, FF=config.yaw_rate_ff, + IMAX=config.yaw_rate_imax, FLTT=config.target_filter_hz, + FLTE=config.error_filter_hz, FLTD=config.derivative_filter_hz, + NEF_center_hz=strategy.error_notch_hz, + NEF_bandwidth_hz=4.0 if strategy.error_notch_hz else 0.0, + NEF_attn_db=30.0, + ) + pid = AC_PID(params, 1 / DT) + state = HubState(psi=0, psi_dot=0.01, omega_motor=(omega_rotor + 0.01) * config.gear_ratio) + history = deque([trim] * (delay_steps + 1), maxlen=delay_steps + 1) + saturated = False + samples: list[tuple[float, float, float, float, float, float, float]] = [] + for index in range(round(config.duration_s / DT)): + t = index * DT + disturbance = amplitude * math.sin(math.tau * config.frequency_hz * t) + gyro = state.psi_dot + (disturbance if hypothesis == "sensor" else 0.0) + target = -config.yaw_angle_p * state.psi + pid_output = pid.update_all(target, gyro, DT, limit=saturated, sim_time_s=t) + yaw_command = max(-1.0, min(1.0, pid_output)) + demand = trim + yaw_command + saturated = demand <= 0.0 or demand >= 1.0 + output = max(0.0, min(1.0, demand)) + if index % LUA_INTERVAL == 0 and strategy.trim_tau_s is not None: + trim = float(lua.fns.yaw_trim_step(LUA_INTERVAL * DT, output, gyro)) + history.append(output) + rotor = omega_rotor * (1 + config.rotor_step_fraction if t >= config.rotor_step_time_s else 1) + state = step(state, rotor, history[0], plant, DT) + if hypothesis == "torque": + # External hub torque, reflected through the assumed rigid gear. + delta_motor = disturbance / config.gear_ratio * DT / plant.j_total() + delta_rate = delta_motor / config.gear_ratio + state = HubState( + psi=state.psi + delta_rate * DT, + psi_dot=state.psi_dot + delta_rate, + omega_motor=state.omega_motor + delta_motor, + ) + if t >= config.settle_s: + samples.append((gyro, state.psi_dot, output, trim, pid.debug.P, state.psi, state.omega_motor)) + a = np.asarray(samples) + if len(a) < 800 or not np.isfinite(a).all(): + raise ValueError("Simulation requires at least two seconds of finite post-settle samples") + frequencies, power = signal.welch(a[:, 0], fs=1 / DT, nperseg=min(len(a), 1600), detrend="linear") + mask = (frequencies >= 1) & (frequencies <= 15) + peak_index = np.flatnonzero(mask)[np.argmax(power[mask])] + peak = float(frequencies[peak_index]) if power[peak_index] > 1e-15 else None + _, cross = signal.csd(a[:, 0], a[:, 2], fs=1 / DT, nperseg=min(len(a), 1600), detrend="linear") + return Metrics( + measured_yaw_std_deg_s=float(np.degrees(a[:, 0]).std()), + actual_yaw_std_deg_s=float(np.degrees(a[:, 1]).std()), + output_std=float(a[:, 2].std()), + trim_std=float(a[:, 3].std()), + p_std=float(a[:, 4].std()), + heading_std_deg=float(np.degrees(a[:, 5]).std()), + heading_mean_deg=float(np.degrees(a[:, 5]).mean()), + trim_mean=float(a[:, 3].mean()), + motor_rpm_std=float((a[:, 6] * 60 / math.tau).std()), + output_floor_fraction=float(np.mean(a[:, 2] <= 0)), + peak_hz=peak, + output_relative_gyro_phase_deg=( + float(np.degrees(np.angle(cross[peak_index]))) + if peak is not None and abs(cross[peak_index]) > 1e-15 else None + ), + ) + + +def fit_amplitude(config: Configuration, hypothesis: Hypothesis, target_deg_s: float) -> float: + """Fit one excitation amplitude to the calibration window's yaw std only.""" + if not math.isfinite(target_deg_s) or target_deg_s <= 0: + raise ValueError("Calibration yaw std must be positive and finite") + baseline = Strategy(config.yaw_rate_p, config.trim_tau_s) + + def residual(amplitude: float) -> float: + return simulate(config, hypothesis, amplitude, baseline).measured_yaw_std_deg_s - target_deg_s + + if residual(0.0) >= 0: + raise ValueError("Unforced model exceeds the observed calibration yaw variation") + upper = 0.25 + while residual(upper) < 0 and upper < 16: + upper *= 2 + if residual(upper) < 0: + raise ValueError("Could not bracket an excitation amplitude") + solution = optimize.root_scalar(residual, bracket=(0.0, upper), method="brentq", xtol=1e-5) + if not solution.converged: + raise ValueError(f"Excitation fit did not converge: {solution.flag}") + return float(solution.root) + + +def configure(path: Path, calibration: Observation) -> tuple[Configuration, dict[str, str]]: + """Model configuration and where each value came from.""" + defaults = Configuration(trim_equilibrium=calibration.trim_mean, motor_rpm=calibration.motor_rpm_mean) + provenance = {name: "assumed" for name in asdict(defaults)} + provenance |= { + "trim_equilibrium": "calibration window mean YFF_T", + "motor_rpm": "calibration window mean RPM", + } + overrides: dict[str, float] = {} + if calibration.peak_hz is not None: + overrides["frequency_hz"] = calibration.peak_hz + provenance["frequency_hz"] = "calibration window vehicle-timed gyro peak" + replay = calibration.replay + if replay is not None: + # Fitted observer values are used only when they clearly beat the + # rawes.lua defaults; a marginal gain means they are not identified. + if replay.fitted_trim_rms < 0.5 * replay.default_trim_rms: + overrides["trim_tau_s"] = replay.fitted_tau_s + overrides["yaw_slope_rpm_per_us"] = replay.fitted_slope_rpm_per_us + source = "identified by replaying rawes.lua on the calibration window" + else: + source = "rawes.lua default, consistent with observer replay" + provenance["trim_tau_s"] = provenance["yaw_slope_rpm_per_us"] = source + captured = captured_parameters(path) + if captured: + overrides |= captured + provenance |= {field: "captured parameters.json" for field in captured} + return replace(defaults, **overrides), provenance + + +def study(path: Path, windows: list[tuple[float, float]]) -> dict: + calibration, smooth, holdout = observations(path, windows) + config, provenance = configure(path, calibration) + strategies = { + "baseline": Strategy(config.yaw_rate_p, config.trim_tau_s), + "fixed_trim": Strategy(config.yaw_rate_p, None), + "slow_trim": Strategy(config.yaw_rate_p, 2.0), + "half_p": Strategy(config.yaw_rate_p / 2, config.trim_tau_s), + "higher_p": Strategy(config.yaw_rate_p * 1.5, config.trim_tau_s), + "error_notch_at_peak": Strategy(config.yaw_rate_p, config.trim_tau_s, config.frequency_hz), + } + hypotheses = {} + for hypothesis in ("sensor", "torque"): + amplitude = fit_amplitude(config, hypothesis, calibration.yaw_std_deg_s) + smooth_config = replace( + config, trim_equilibrium=smooth.trim_mean, motor_rpm=smooth.motor_rpm_mean + ) + smooth_amplitude = fit_amplitude(smooth_config, hypothesis, smooth.yaw_std_deg_s) + results = { + name: asdict(simulate(config, hypothesis, amplitude, strategy)) + for name, strategy in strategies.items() + } + delay_sensitivity = { + str(delay): { + name: asdict(simulate( + replace(config, delay_s=delay), hypothesis, amplitude, strategies[name] + )) + for name in ("baseline", "half_p", "higher_p", "error_notch_at_peak") + } + for delay in (0.0, 0.005, 0.01, 0.015) + } + hypotheses[hypothesis] = { + "fitted_excitation_amplitude": amplitude, + "excitation_unit": "rad/s" if hypothesis == "sensor" else "N m at hub", + "smooth_separately_fitted_amplitude": smooth_amplitude, + "smooth_separately_fitted_baseline": asdict(simulate( + smooth_config, hypothesis, smooth_amplitude, strategies["baseline"] + )), + "results": results, + "delay_sensitivity_s": delay_sensitivity, + } + rotor_step = { + name: asdict(simulate( + replace(config, rotor_step_fraction=0.05), "torque", 0.0, strategies[name] + )) + for name in ("baseline", "fixed_trim", "slow_trim") + } + return { + "warning": ( + "Exploratory hypotheses, not a validated hardware twin or a tuning recommendation. " + "The excitation is fitted to the calibration yaw standard deviation; see " + "configuration_provenance for which values are captured, identified or assumed. " + "Smooth and rough excitation amplitudes are fitted independently; the model " + "does not predict the dependence on collective." + ), + "experiment": str(path), + "time_bases": { + "window_selection_and_heartbeat_gating": "LinkHub receive time", + "PID_TUNING": "LinkHub receive time (the message has no vehicle timestamp)", + "DEBUG_FLOAT_ARRAY": "vehicle boot time_usec (ms resolution, set by rawes.lua)", + "ATTITUDE_QUATERNION": "vehicle time_boot_ms", + "SERVO_OUTPUT_RAW": "vehicle time_usec", + }, + "observations": { + "calibration_rough": asdict(calibration), + "smooth_separately_fitted": asdict(smooth), + "rough_holdout": asdict(holdout), + }, + "configuration": asdict(config), + "configuration_provenance": provenance, + "implementation_assumptions": { + "controller": ( + "Python AC_PID port with the configured P/I/D/FF/IMAX and FLTT/FLTE/FLTD " + "(0 disables a filter, as in AP); no D_FF, slew or dynamic scaling; " + "completed rotor runup" + ), + "mixer": "Active DDFP, linear normalized output, no collective-yaw offset or voltage compensation", + "observer": ( + "Current Lua yaw_trim_step at 100 Hz with the configured RAWES_YFF_TAU and " + "RAWES_YAW_SLP; adaptive or pinned" + ), + "plant": ( + "Existing torque_model rigid gear and governed motor with default inertia, " + "ESC gain and torque limit; fixed rotor speed, inferred RPM/throttle ratio" + ), + "sample_time_s": DT, + "sensor_hypothesis": "Additive sinusoid on measured gyro; heading uses true body angle", + "torque_hypothesis": "Sinusoidal external torque on the hub; gyro measures true body rate", + }, + "strategies": {name: asdict(value) for name, value in strategies.items()}, + "hypotheses": hypotheses, + "rotor_speed_step_5_percent_no_periodic_forcing": rotor_step, + } + + +def mark_windows(path: Path) -> dict[str, tuple[float, float]]: + """Receive-time window after each `experiment.mark`, skipping its transition. + + A window runs from MARK_SETTLE_S after the mark to the next mark or the + experiment's end. A repeated label keeps its last segment. + """ + data = json.loads(path.read_bytes()) + origin = data["experiment"]["started_at_ns"] + end = (data["experiment"]["stopped_at_ns"] - origin) / 1e9 + marks = [ + ((record["ingest_time_ns"] - origin) / 1e9, record["data"]["fields"]["label"]) + for record in data["records"] + if record["kind"] == "diagnostic.event" and record["data"].get("event") == "experiment.mark" + ] + if not marks: + return {} + bounds = [time for time, _ in marks[1:]] + [end] + return { + label: (time + MARK_SETTLE_S, stop) + for (time, label), stop in zip(marks, bounds, strict=True) + if stop > time + MARK_SETTLE_S + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--experiment", required=True, type=Path, help="LinkHub experiment mavlog.json") + parser.add_argument("--rough", nargs=2, type=float, default=(140, 146), metavar=("START", "END")) + parser.add_argument("--smooth", nargs=2, type=float, default=(152, 156), metavar=("START", "END")) + parser.add_argument("--holdout", nargs=2, type=float, default=(164, 166), metavar=("START", "END")) + for name in ("rough", "smooth", "holdout"): + parser.add_argument( + f"--{name}-mark", metavar="LABEL", + help=f"Use the segment after this experiment mark instead of --{name}", + ) + parser.add_argument("--output", type=Path, help="Save JSON report; otherwise print it") + args = parser.parse_args() + segments = mark_windows(args.experiment) + windows = [] + for name in ("rough", "smooth", "holdout"): + label = getattr(args, f"{name}_mark") + if label is None: + start, end = getattr(args, name) + elif label not in segments: + parser.error(f"No experiment mark {label!r}; marks: {sorted(segments)}") + else: + start, end = segments[label] + windows.append((start, end)) + report = study(args.experiment, windows) + text = json.dumps(report, indent=2, allow_nan=False) + "\n" + if args.output: + args.output.write_text(text, encoding="utf-8") + else: + print(text, end="") + + +if __name__ == "__main__": + main() diff --git a/arduloop/README.md b/arduloop/README.md index 8c9145a..78b3a6b 100644 --- a/arduloop/README.md +++ b/arduloop/README.md @@ -11,6 +11,8 @@ and rate-control stack. It has two layers: Both layers use ArduPilot-style parameter names. This models the control math only, not mode entry, arming/spool state, or failsafes — validate those in SITL. Python tuning results are not hardware acceptance. +The static notch coefficients use ArduPilot's attenuation and bandwidth +equations; dynamic notch retuning and its frequency-slew limits are not modeled. Current RAWES Lua steady/passive/takeoff behavior uses the direct-thrust Guided angle path (`set_target_angle_and_rate_and_throttle(...)`). This package also diff --git a/arduloop/filters.py b/arduloop/filters.py index cdd7bd2..98d84fb 100644 --- a/arduloop/filters.py +++ b/arduloop/filters.py @@ -71,24 +71,22 @@ def _notch_coeffs(center_hz: float, bandwidth_hz: float, sample_hz: float, Uses the same form as AP's `NotchFilter::init` (with attenuation control). """ - if center_hz <= 0.0 or bandwidth_hz <= 0.0 or sample_hz <= 0.0: - # Pass-through + if not (bandwidth_hz > 0.0 and center_hz > 0.5 * bandwidth_hz + and center_hz < 0.5 * sample_hz): return _BiquadCoeffs(1.0, 0.0, 0.0, 0.0, 0.0) - # Limit centre below Nyquist - center_hz = min(center_hz, 0.45 * sample_hz) omega = 2.0 * math.pi * center_hz / sample_hz - # Convert attenuation dB to amplitude factor A (≥1 → deeper notch) - A = 10.0 ** (attenuation_db / 40.0) - Q = center_hz / max(bandwidth_hz, 1e-9) + A = 10.0 ** (-attenuation_db / 40.0) + ratio = center_hz / (center_hz - bandwidth_hz / 2.0) + Q = ratio / (ratio * ratio - 1.0) alpha = math.sin(omega) / (2.0 * Q) cos_w = math.cos(omega) - a0 = 1.0 + alpha / A + a0 = 1.0 + alpha return _BiquadCoeffs( - b0=(1.0 + alpha * A) / a0, + b0=(1.0 + alpha * A * A) / a0, b1=(-2.0 * cos_w) / a0, - b2=(1.0 - alpha * A) / a0, + b2=(1.0 - alpha * A * A) / a0, a1=(-2.0 * cos_w) / a0, - a2=(1.0 - alpha / A) / a0, + a2=(1.0 - alpha) / a0, ) @@ -121,7 +119,8 @@ def set(self, center_hz: float, bandwidth_hz: float, sample_hz: float, if attenuation_db is not None: self.attenuation_db = attenuation_db self._c = _notch_coeffs(center_hz, bandwidth_hz, sample_hz, self.attenuation_db) - self.enabled = True + self.enabled = (bandwidth_hz > 0.0 and center_hz > 0.5 * bandwidth_hz + and center_hz < 0.5 * sample_hz) def disable(self) -> None: self.enabled = False @@ -129,7 +128,7 @@ def disable(self) -> None: def reset(self, value: float = 0.0) -> None: # Prime the transposed direct-form II delay line so steady-state DC # passes through cleanly. - self._z1 = value * (self._c.b1 - self._c.a1) + self._z1 = value * (1.0 - self._c.b0) self._z2 = value * (self._c.b2 - self._c.a2) def apply(self, x: float) -> float: diff --git a/calibrate/hw.py b/calibrate/hw.py index ced4548..2211770 100644 --- a/calibrate/hw.py +++ b/calibrate/hw.py @@ -7,6 +7,7 @@ import math import time from dataclasses import dataclass +from typing import overload from linkhub_client.client import LinkHubError from linkhub_client.messages import ( @@ -28,7 +29,7 @@ from .messages import read_one # --------------------------------------------------------------------------- -# Mutable global: eRPM -> RPM divisor (pole-pairs) +# Mutable global: pole-pairs used to derive eRPM from reported motor RPM # Seeded from the GB4008 default; overridden by _refresh_pole_pairs(). # --------------------------------------------------------------------------- _motor_pole_pairs = GB4008_POLE_PAIRS @@ -46,8 +47,8 @@ def _esc_telem_msg_for_channel(channel: int) -> tuple[str, int]: raise ValueError(f"no ESC_TELEMETRY message for output channel {channel}") -def _esc_erpm(msg: EscTelemetry | Message | RawMessage, channel: int) -> float | None: - """eRPM for 1-based output `channel` from an ESC_TELEMETRY_* msg, else None.""" +def _esc_motor_rpm(msg: EscTelemetry | Message | RawMessage, channel: int) -> float | None: + """Motor RPM for 1-based output `channel` from an ESC_TELEMETRY_* msg.""" if isinstance(msg, EscTelemetry): base = msg.first_channel idx = channel - base @@ -65,20 +66,25 @@ def _esc_erpm(msg: EscTelemetry | Message | RawMessage, channel: int) -> float | return rpm[idx] -def _rpm_triplet(erpm: float | None) -> tuple: - """eRPM -> (erpm, mech_rpm, rotor_rpm). (None, None, None) if erpm is None. - Uses the live SERVO_BLH_POLES-derived pole-pair count (_motor_pole_pairs).""" - if erpm is None: +@overload +def _rpm_triplet(mech_rpm: float) -> tuple[float, float, float]: ... + + +@overload +def _rpm_triplet(mech_rpm: None) -> tuple[None, None, None]: ... + + +def _rpm_triplet(mech_rpm: float | None) -> tuple[float | None, float | None, float | None]: + """Reported motor RPM -> (derived eRPM, motor RPM, estimated rotor RPM).""" + if mech_rpm is None: return None, None, None - mech_rpm = erpm / _motor_pole_pairs + erpm = mech_rpm * _motor_pole_pairs rotor_rpm = mech_rpm / GB4008_GEAR_RATIO return erpm, mech_rpm, rotor_rpm def _refresh_pole_pairs(session: LinkHubClient) -> None: - """Set the eRPM->RPM divisor from the FC's SERVO_BLH_POLES (poles/2), so the - RPM readout follows the param instead of a hardcode. Falls back to the - GB4008 default if the param is unreadable.""" + """Set the multiplier for derived eRPM from the FC's SERVO_BLH_POLES.""" global _motor_pole_pairs poles = session.get_param("SERVO_BLH_POLES") if poles is not None and poles >= 2: @@ -450,15 +456,14 @@ def _monitor_esc(session: LinkHubClient, duration: float = 10.0) -> None: last_print = now try: - rpm_e = msg.rpm[idx] + motor_rpm = msg.rpm[idx] volt = msg.voltage[idx] / 100.0 curr = msg.current[idx] / 100.0 temp = msg.temperature[idx] except (IndexError, TypeError): continue - mech_rpm = rpm_e / _motor_pole_pairs - rotor_rpm = mech_rpm / GB4008_GEAR_RATIO + rpm_e, mech_rpm, rotor_rpm = _rpm_triplet(motor_rpm) torque = curr * GB4008_KT / GB4008_GEAR_RATIO elapsed = duration - (deadline - now) print(f" {elapsed:<6.1f} {rpm_e:<8} {mech_rpm:<10.0f} {rotor_rpm:<11.1f}" diff --git a/calibrate/run.py b/calibrate/run.py index 8d4ca94..e7320b9 100644 --- a/calibrate/run.py +++ b/calibrate/run.py @@ -56,7 +56,7 @@ def getch(self): _send_set_servo, _set_safe_off_state, _esc_telem_msg_for_channel, - _esc_erpm, + _esc_motor_rpm, _rpm_triplet, ) from .messages import read_one @@ -1304,7 +1304,7 @@ def key_handler(k: bytes) -> None: # no live key tuning for this mode "mrpm_hist": [], # (t_rel, mech_rpm) for the 5 s rolling average on screen "vbat": None, "curr": None, - "erpm": None, + "motor_rpm": None, "yff_t": None, "yff_u": None, "yff_gz": None, @@ -1406,7 +1406,7 @@ def handle_msg(st: _ObservationState, msg: Message | RawMessage | EscTelemetry, state["yaw"] = math.degrees(msg.yaw) state["yaw_rate"] = msg.yawspeed # rad/s (mav_att_yaw_rate_rads) # Emit one CSV row per ATTITUDE message (typically 10-50 Hz) - _erpm, _mech, _rotor = _rpm_triplet(state["erpm"]) + _erpm, _mech, _rotor = _rpm_triplet(state["motor_rpm"]) _qw, _qx, _qy, _qz, _qerr_deg, _qerr_yaw_deg = _quat_error( state["att_q"], state["att_target_q"] ) @@ -1542,10 +1542,10 @@ def handle_msg(st: _ObservationState, msg: Message | RawMessage | EscTelemetry, if state["curr"] is None and getattr(msg, "current_battery") >= 0: state["curr"] = getattr(msg, "current_battery") / 100.0 elif isinstance(msg, EscTelemetry): - erpm = _esc_erpm(msg, MOTOR_ESC_CHANNEL) - if erpm is not None: - state["erpm"] = erpm - _, _m, _ = _rpm_triplet(erpm) + motor_rpm = _esc_motor_rpm(msg, MOTOR_ESC_CHANNEL) + if motor_rpm is not None: + state["motor_rpm"] = motor_rpm + _, _m, _ = _rpm_triplet(motor_rpm) if _m is not None: state["mrpm_hist"].append((t_rel, _m)) cutoff = t_rel - mot_window_s @@ -1598,7 +1598,7 @@ def _fresh_or_stale(value: float | None, value_ts: float | None, fmt: Callable[[ mot_avg_s = ( f"{sum(v for _, v in state['smot_hist']) / len(state['smot_hist']):.0f}" ) - _e, _m, _rotor = _rpm_triplet(state["erpm"]) + _e, _m, _rotor = _rpm_triplet(state["motor_rpm"]) mrpm_avg_s = None if state["mrpm_hist"]: mrpm_avg_s = ( @@ -1675,7 +1675,7 @@ def _update_live_view(st: object, t_rel: float) -> bool: def _update_passive_live_view(st: object, t_rel: float) -> bool: actual_q = state["att_q"] or (1.0, 0.0, 0.0, 0.0) _, _, _, _, qerr_deg, _ = _quat_error(state["att_q"], state["att_target_q"]) - _, _, rotor_rpm = _rpm_triplet(state["erpm"]) + _, _, rotor_rpm = _rpm_triplet(state["motor_rpm"]) return live_view.update( PassiveViewData( t=t_rel, diff --git a/calibrate/watch.py b/calibrate/watch.py index d57dc49..12a341d 100644 --- a/calibrate/watch.py +++ b/calibrate/watch.py @@ -14,7 +14,7 @@ from .constants import MOTOR_ESC_CHANNEL, _WATCH_STREAMS from .hw import ( _esc_telem_msg_for_channel, - _esc_erpm, + _esc_motor_rpm, _rpm_triplet, ) from .run import _RunLog, _observation_loop @@ -114,27 +114,27 @@ def render(st: object, t_rel: float) -> list[object]: ) -def _watch_esc(session: LinkHubClient, duration: float | None, log: _RunLog): +def _watch_esc(session: _ObservationSession, duration: float | None, log: _ObservationLog) -> None: # GB4008 bidir DShot telemetry (AUX 1 = SERVO9 -> ESC_TELEMETRY_9_TO_12[0]). cols = ["t_s", "erpm", "mech_rpm", "rotor_rpm", "voltage_v", "current_a", "temp_c"] esc_name, esc_id = _esc_telem_msg_for_channel(MOTOR_ESC_CHANNEL) idx = (MOTOR_ESC_CHANNEL - 1) % 4 - state: dict[str, float | None] = {"erpm": None, "volt": None, "curr": None, "temp": None} + state: dict[str, float | None] = {"motor_rpm": None, "volt": None, "curr": None, "temp": None} def handle(st: object, msg: object, t_rel: float) -> list[object] | None: if not isinstance(msg, EscTelemetry) or msg.message_name != esc_name: return None - erpm = _esc_erpm(msg, MOTOR_ESC_CHANNEL) + motor_rpm = _esc_motor_rpm(msg, MOTOR_ESC_CHANNEL) volt = msg.voltage[idx] / 100.0 if idx < len(msg.voltage) else None curr = msg.current[idx] / 100.0 if idx < len(msg.current) else None temp = msg.temperature[idx] if idx < len(msg.temperature) else None - state["erpm"], state["volt"], state["curr"], state["temp"] = ( - erpm, + state["motor_rpm"], state["volt"], state["curr"], state["temp"] = ( + motor_rpm, volt, curr, temp, ) - _e, mech, rotor = _rpm_triplet(erpm) + _e, mech, rotor = _rpm_triplet(motor_rpm) return [ f"{t_rel:.4f}", _fmt(_e), @@ -146,7 +146,7 @@ def handle(st: object, msg: object, t_rel: float) -> list[object] | None: ] def render(st: object, t_rel: float) -> list[object]: - _e, mech, rotor = _rpm_triplet(state["erpm"]) + _e, mech, rotor = _rpm_triplet(state["motor_rpm"]) return [ f"{t_rel:.1f}", f"{_e:.0f}" if _e is not None else None, diff --git a/design/calibration.md b/design/calibration.md index 7915aa6..6bbfc37 100644 --- a/design/calibration.md +++ b/design/calibration.md @@ -14,6 +14,47 @@ by [linkhub.md](linkhub.md). The repository ownership map lives at investigations are preserved in [HARDWARE_STARTUP.md](../HARDWARE_STARTUP.md); they are diagnostic context, not current operating instructions. +## Offline yaw analysis of motor-session exports + +Analyze saved LinkHub experiments without connecting to hardware: + +```powershell +uv run python -m analysis.analyze_motor_sessions simulation\logs\linkhub\experiments +``` + +The input can also be one experiment directory or its `mavlog.json`, a +motor-session export, or an export directory containing `index.json`. The utility +writes `yaw_analysis.json` beside the input (`--output` overrides this) and prints +one summary per session. Experiment record counts and journal cursor continuity +are checked before reporting results. +`--rate-band-deg-s` sets the tracking-error band (default 5 degrees/s). + +Reports include yaw PID tracking error, P/I/D/FF effort, trim/applied-output +statistics, SERVO9 PWM smoothness, and first/last-quarter comparisons within +each sufficiently long armed mode/clock block. Fixed 10-second windows report +the same armed signals alongside motor RPM; recorded Bluetooth motor command +events provide context but do not prove the actual motor speed. Short or sparse +windows and motor-speed changes are not steady-state comparisons. Rates from `PID_TUNING` are +radians/s internally and reported as degrees/s; normalized throttle is reported +in percentage points. Analysis weights 100 ms receive-time bins equally; RMS +uses within-bin mean squares so fast opposite errors cannot cancel. Smoothness +uses bin means; +slew/variation metrics never bridge missing bins or mode/arming/clock changes. +Raw peaks remain available. No servo calibration or observer gain is assumed. +The reported trim-plus-PID sum is only a partial sum of telemetry fields, not +an actuator command: derivative feedforward, feedforward scaling, mixer +offsets/gates and actuator mapping are not reconstructed. A recent Lua +diagnostic frame does not prove its persisted values were updated recently. + +Only the ArduPilot vehicle identity's heartbeats determine armed state; bridge +heartbeats cannot disarm the analysis. Unknown/stale heartbeat state, missing +diagnostic mask bits, stale trim, and short captures are reported rather than +replaced with zero. Experiments without a vehicle heartbeat have unavailable +control metrics rather than being mistaken for a disarmed vehicle. Early/late comparisons describe observed behavior, not a +causal proof of trim effectiveness: RPM, load, targets and PID settings can +change. See the [trim observer owner](flight_stack.md#52-yaw-actuator-boundary-and-trim-observer) +for the control law. + ## Connection ```bash @@ -253,6 +294,12 @@ duration is 10 s. | `attitude` | `ATTITUDE` | `t_s`, roll/pitch/yaw + body rates | | `power` | `BATTERY_STATUS`, `SYS_STATUS` | `t_s`, `vbat_v`, `current_a`, `power_w` | +ArduPilot's ESC telemetry reports motor mechanical RPM after its pole-count +conversion. `erpm` is calculated from that reported value and the configured +pole count (or the default if unavailable); `rotor_rpm` is an estimate using +the assumed gear ratio, not an independent rotor-speed measurement. See +[hardware.md](hardware.md#yaw-motor-and-dshot-telemetry). + `watch servos` records outputs 1–8 only. For output 9 or full journal evidence, use `status` or the LinkHub journal. diff --git a/design/flight_stack.md b/design/flight_stack.md index b555e1f..11bdc3a 100644 --- a/design/flight_stack.md +++ b/design/flight_stack.md @@ -306,6 +306,14 @@ the firmware (a custom message would need a custom firmware build). - LinkHub collapses `DEBUG_FLOAT_ARRAY` per `array_id` for `collapse=true` reads. The array has `time_usec` rather than `time_boot_ms`, so its journal records carry the last observed simulation time (`LastObserved`). +- `time_usec` is the script's vehicle boot time for the emitting tick + (millisecond resolution, `now_ms * 1000`), on the same clock as + `ATTITUDE_QUATERNION.time_boot_ms` and `SERVO_OUTPUT_RAW.time_usec`. Emission + is rate-gated on 10 ms ticks, so `RAWES_TEL_HZ=20` gives about 19 Hz + (51–56 ms spacing). A larger gap means a lost sample: `send_chan` drops a + message when the channel is full, and links drop bursts. Use `time_usec`, + not LinkHub receive time, for timing and phase; receive spacing of the same + samples ranges from about 1 ms to over 0.5 s. - Readers: `analysis/enrich_sitl_telemetry.py` (SITL telemetry columns), `calibrate/run.py`, the SITL torque/steady tests, and the LinkHub UI (`YFF_U`). This array is output only; ground-to-Lua inputs are the @@ -647,9 +655,11 @@ param:set("H_YAW_TRIM", trim) This estimates the throttle for zero yaw rate from applied output and gyro feedback; it is not a direct rotor-RPM feedforward calculation or a guarantee -of convergence. `YFF_A = RAWES_YAW_SLP × SERVO9_SPAN_US × 2π/60` (default ≈ 52.8 rad/s per -throttle unit; RAWES_YAW_SLP=0 uses the script fallback 0.504 RPM/µs). The AP yaw P/I-term handles -fast transients and residual drift; the observer is intended to carry DC trim. +of convergence. `YFF_A = RAWES_YAW_SLP × 1000 µs × 2π/60` (default ≈ 52.8 rad/s per +throttle unit; RAWES_YAW_SLP=0 uses the script fallback 0.504 RPM/µs). The +1000 µs conversion span is fixed in the script even when the output readback +uses different `SERVO9_MIN/MAX` limits. The AP yaw P/I-term handles fast +transients and residual drift; the observer is intended to carry DC trim. A non-negative `ENTER_PASSIVE` seed pins trim instead of adapting, while readback diagnostics continue. Disconnected-actuator caveats and cleanup requirements belong to [arming.md](arming.md#passive-bench-startup). diff --git a/design/hardware.md b/design/hardware.md index 42cd46e..8896087 100644 --- a/design/hardware.md +++ b/design/hardware.md @@ -37,7 +37,7 @@ definition asks for tape-measure confirmation of the physical dimensions. |---|---|---| | Flight controller | Pixhawk 6C | [HARDWARE_STARTUP.md](../HARDWARE_STARTUP.md) | | Swash servos | DS113MG V6.0 class (simulated slew 545 deg/s, travel 100 deg) | `servo_slew_rate_deg_s`, `servo_travel_deg` in the rotor definition | -| Yaw motor | EMAX GB4008, 66 RPM/V, 22 poles, 10:1 gear | `GB4008_KV`, `GB4008_POLES`, `GB4008_GEAR_RATIO` | +| Yaw motor | EMAX GB4008, 66 RPM/V, 22 poles, assumed 10:1 gear | `GB4008_KV`, `GB4008_POLES`, `GB4008_GEAR_RATIO` | | Yaw ESC | REVVitRC 50A, AM32 firmware, bidirectional DShot | [rawes_common_defaults.parm](../tests/sitl/rawes_common_defaults.parm) DShot block | Vendor datasheet data (dimensions, weights, radio specs, power budgets) is not @@ -74,8 +74,10 @@ bidirectional DShot and ESC RPM telemetry. The `SERVO_BLH_*`, `SERVO_DSHOT_*`, Wiring: AUX 1 signal and ground to the ESC signal and signal ground; power the ESC from the battery path, not the servo rail. -RPM conversion: eRPM / (poles / 2) gives motor RPM; dividing again by the 10:1 -gear ratio gives rotor RPM. The pole count must match `SERVO_BLH_POLES`. +ArduPilot converts eRPM using `SERVO_BLH_POLES` before reporting motor RPM in +ESC telemetry. Dividing motor RPM by the assumed 10:1 gear ratio estimates +rotor speed relative to the body, not an independent measurement of absolute +rotor speed. The installed ratio needs mechanical confirmation. Output 9 must stay mapped at boot (see the safe-off invariant in [arming.md](arming.md)). diff --git a/design/linkhub.md b/design/linkhub.md index 94614e3..bf9bf8f 100644 --- a/design/linkhub.md +++ b/design/linkhub.md @@ -253,6 +253,8 @@ The browser renews a 2 s lease every 500 ms only for a motor it explicitly started. Closing its motor panel, hiding the tab, or a request failure revokes renewal and attempts a stop. A suspended browser must not revive an expired lease, and reopening the panel never starts or adopts a running motor. +Renewal remains tied to the same active experiment and its completed snapshot. +Camera verification is required to start the motor, not to renew its lease. UI operation is described in the [motor panel guide](../linkhub-ui/README.md#bluetooth-motor-panel). The controller journals its state changes as diagnostics with source @@ -357,21 +359,63 @@ protect. `POST /v1/experiment/start` creates the experiment directory `/experiments/__/` and writes `experiment.txt` there with the entered name and description, the UTC start -time, the experiment ID and the run ID. It then records the journal cursor and -journals an `experiment.started` diagnostic marker. If the directory or text -file cannot be created, start fails and no experiment begins. The returned -experiment includes `directory`. `POST /v1/experiment/stop` journals +time, the experiment ID, the run ID and the client's optional +`telemetry_profile` (the UI sends its active profile). It then records the +journal cursor and journals an `experiment.started` diagnostic marker. If the +directory or text file cannot be created, start fails and no experiment +begins. The returned experiment includes `directory`, `telemetry_profile` and +`snapshot`. + +Start then captures the vehicle configuration in the background: +`AUTOPILOT_VERSION`, the full parameter table via MAVFTP +`@PARAM/param.pck?withdefaults=1` (saved raw as `param.pck` and decoded to +`parameters.json`, with `default` only where it differs from the value), and +every `*.lua` file in `/APM/scripts` (saved under `scripts/`, CRC-verified). +Script names must be plain filenames, without drive prefixes or path separators; +existing snapshot script files are never overwritten. Violations fail the snapshot. +`snapshot.json` records the firmware, parameter count, each script's size and +SHA-256, any error, and `message_intervals`: the vehicle's own +`MESSAGE_INTERVAL` on this link for the analysis streams (attitude, attitude +target, servo output, PID tuning, RPM, ESC telemetry, vibration, battery). A +rejected interval query is recorded per stream and does not fail the +snapshot. The experiment's `snapshot` reports `state` +`capturing`, `complete` or `failed`; the outcome is journaled as +`experiment.snapshot` before the state changes, so it appears in +`mavlog.json`. Without a MAVLink link the snapshot fails. Parameter writes +during the experiment remain visible as `PARAM_SET`/`PARAM_VALUE` records. +A snapshot still running at stop finishes writing its files afterwards. The +snapshot also lists the onboard (DataFlash) logs present at the start. + +`POST /v1/experiment/mark` with `{label}` journals an `experiment.mark` +diagnostic (`fields.label`) and returns the label, cursor and elapsed time. +Marks split the experiment into named segments for +`analysis/analyze_motor_sessions.py` (`segments`) and +`analysis/yaw_digital_twin.py` (`--rough-mark` etc.). + +`POST /v1/experiment/stop` journals `experiment.stopped`, then writes every journal record between the two markers to `mavlog.json` in the experiment directory. The file includes MAVLink rx/tx records and diagnostics. LinkHub writes a `.partial` file first and then renames it, so a crash cannot leave a truncated file under the final name. The file shape is `{schema_version: 1, experiment: {id, name, description, run_id, started_at_ns, -stopped_at_ns, start_cursor, end_cursor}, records: [...], record_count}`, and +stopped_at_ns, start_cursor, end_cursor, snapshot, telemetry_profile}, +records: [...], record_count}`, where `snapshot` is its status at stop, and each record uses the same JSON encoding as `GET /v1/mavlink/messages`. Experiment state lives in memory: restarting the service drops an active experiment without writing `mavlog.json`. The journal still holds the records. +After stop, LinkHub downloads every onboard log that is new or has a different +size than at the start as `onboard-.BIN`, through the ordinary transfer +registry (listed and cancellable at `/v1/mavlink/transfers`). +`onboard_logs.json` reports `downloading`, then `complete`, `failed` or +`skipped` with each log's size or error. Download start (when there are logs +to fetch), per-file byte progress at roughly 10% intervals, and the final +outcome are journaled as `experiment.onboard_logs` +after the experiment window. ArduPilot serves logs +only while disarmed, and a large log over a telemetry radio can take a long +time; cancel the transfer if it is not needed. + #### Phone video Phone browsers expose the camera only to secure contexts, so @@ -415,6 +459,23 @@ acknowledged without being rewritten, so phones retry safely after a lost response. A gap returns 409 `video_out_of_order`. LinkHub accepts the final chunk for 120 s after stop, then returns 409 `experiment_closed`. +The final chunk also finalizes the recording using **FFmpeg**, which must be +installed on LinkHub's `PATH`. This is a lossless remux (`-c copy`): WebM and +Matroska receive duration metadata and front-loaded Cues; MP4 receives a +finalized, front-loaded `moov` index (`+faststart`). Completed files are +seekable; files still being recorded are not guaranteed seekable. Finalization +has a 120 s timeout and writes a sibling temporary file before replacing the +original. `finished` becomes true only after successful replacement, and +`bytes` then reports the finalized file size. Failure returns HTTP 500 +`video_finalize_failed` with the FFmpeg error, preserves the uploaded original, +and leaves `finished` false. Retrying the final chunk retries finalization +without appending its bytes again. + +Video status advances only after each chunk is written and `sync_data` +succeeds. The UI uses that status, rather than a phone's heartbeat claim, to +verify recording before enabling arm/motor actions; see +[LinkHub UI experiments](../linkhub-ui/README.md#experiments). + The server only bounds the time window. It does not enforce arm or motor gating, and it does not stop actuators. The UI's experiment controller does both before calling stop; see @@ -591,8 +652,12 @@ packed parameter uploads. In Copter-4.7.1, and [uploads explicitly preserve all Int32 bits](https://github.com/ArduPilot/ardupilot/blob/Copter-4.7.1/libraries/AP_Filesystem/AP_Filesystem_Param.cpp#L607) when the uploaded and destination types both match Int32. This is a distinct ArduPilot-specific packed-file protocol, not `PARAM_EXT_*` or bytewise classic -parameter encoding. The typed parameter transaction API currently uses classic -messages; it does not yet implement packed-file parameter reads/writes. +parameter encoding. The typed parameter transaction API uses classic +messages; the only packed-file use is the read-only experiment snapshot +(`mavlink_protocol::client::decode_param_pack`). ArduPilot reports the virtual +file's size as an estimate (`count × 12` bytes), so MAVFTP reads of `@` paths +end at the first short chunk, or where a burst returns end-of-file before any +data, and skip the CRC check. The dialect cannot represent an enumeration value outside it. A frame that passes its CRC but does not decode as a typed message (for example an diff --git a/linkhub-ui/README.md b/linkhub-ui/README.md index f203716..54d10fb 100644 --- a/linkhub-ui/README.md +++ b/linkhub-ui/README.md @@ -138,8 +138,10 @@ For SITL: .\run_linkhub_ui.cmd tcp:127.0.0.1:5760 ``` -Add `--build` to run the complete project setup before launching -(Bluetooth support is always included): +Add `--build` to rebuild the browser assets and release LinkHub binary before +launching (Bluetooth support is always included). This prepares the build +dependencies but skips Python setup, Ruff, Pyright, and the standalone +TypeScript check: ```powershell .\run_linkhub_ui.cmd --build auto @@ -232,7 +234,33 @@ details in `experiment.txt` there. While locked, the terminal refuses `arm`, `ru `ARM_DISARM` arm requests, and the motor panel's **Turn on** is disabled. `stop`, `disarm`, `run collective`, and calibration commands stay available. +Start closes the dialog and shows **Stop** with the elapsed time as soon as +LinkHub creates the experiment. The terminal reports the parameter/script +snapshot and video checks separately as they update in the background. Arm and +motor controls still require a complete snapshot and, for every connected phone, +at least two uploaded chunks and a non-empty experiment video file. Video checks +that remain pending after 15 s are flagged as failed. A phone heartbeat +claiming to record is not enough: LinkHub must have saved the video data. +Experiments without connected phones remain allowed and are reported as such. +The snapshot status follows LinkHub's [capture result](../design/linkhub.md#experiments) +and reports the saved parameter count and script names, or the failure reason. +Failed checks do not end the experiment; Stop still performs the normal +shutdown and saves the journal. In the terminal or CLI, `experiment status` +reports the snapshot and `video_check` together. +The controller rechecks cameras on status refresh and before arm/motor actions. +Missing phones, finished recordings, or video with no new chunk for 10 s +block new arm and motor starts until verification recovers. They do not +interrupt lease renewals for a motor already running in the same experiment. +Phones seen +during an experiment remain required for that controller's lifetime, even if +they disconnect. Reloading discovers the phones currently registered on the +server. This check proves incoming data was saved, not that the image is +correctly aimed or that the whole file is playable. + While an experiment runs, the button shows **■ Stop** and the elapsed time. +Use `experiment mark LABEL` (for example `experiment mark collective high`) +at each change of test condition; each mark starts a named segment that the +analysis tools summarise separately. Stop runs these steps in order: 1. ramps the Bluetooth motor down and waits for the ramp to finish; @@ -241,7 +269,11 @@ Stop runs these steps in order: 3. applies canonical safe-off, which disarms the vehicle; 4. saves the experiment's journal window as `mavlog.json` in the experiment directory. With `run_linkhub_ui.cmd`, experiment directories land in - `simulation/logs/linkhub/experiments/`. + `simulation/logs/linkhub/experiments/`. LinkHub then downloads the + experiment's new onboard logs into the same directory as + `onboard-.BIN` (see [Experiments](../design/linkhub.md#experiments)). + The same browser terminal shows the log check, download start, periodic + per-file progress, and the result (including no new logs or an error). An experiment started with no motor or vehicle connected can stop and save without sending hardware commands. Initial MAVLink status has no mode flags @@ -262,6 +294,8 @@ warning and tap **Enable camera** once, then leave the page open. From then on, every phone records each experiment automatically into its own video file in the experiment directory, starting on **Start** and finishing on **Stop**. Tap **Disconnect** on the phone to finish any recording and remove it. +The camera header shows how many connected phones have verified recordings; +it only lights up when all connected phones are verified. Phones need the same network. They also need LinkHub on the LAN with HTTPS enabled; `run_linkhub_ui.cmd` does this on port 9443. See [phone video](../design/linkhub.md#phone-video). @@ -609,7 +643,13 @@ kept until the connection generation changes, then the connection/baud-based sel runs again. The Wi-Fi profile has `minbaud=1500000`; slower serial links get the Radio -profile. High-rate display streams share capacity with file/log transfers. +profile. A flight controller's native USB (LinkHub status `native_usb`, +identified by its board USB vendor ID) reports a nominal 115200 baud but is +not radio-limited, so it gets the highest-rate profile like a network link. +USB-serial adapters (FTDI, Silicon Labs and similar, as used by SiK radios) +and unrecognized boards keep the baud-based choice; select Wi-Fi manually for +an unrecognized board's USB. +High-rate display streams share capacity with file/log transfers. `PID_TUNING` is sent by the autopilot only for axes in `GCS_PID_MASK` (hardware defaults set it to 4, yaw). Rates persist on the vehicle, so every profile sets `PID_TUNING` @@ -777,6 +817,9 @@ Proposed, not implemented: The browser formats the throughput values reported by LinkHub; it does not estimate rates from filtered telemetry or HTTP payload size. +Next to RX/TX it displays the last reported battery voltage from +`BATTERY_STATUS` (or `SYS_STATUS` if available), and `—` when unavailable or +disconnected. ## Safety and boundaries diff --git a/linkhub-ui/index.html b/linkhub-ui/index.html index 6c4ac42..ecff20a 100644 --- a/linkhub-ui/index.html +++ b/linkhub-ui/index.html @@ -25,7 +25,7 @@

Live vehicle state

connecting
- + @@ -106,7 +106,8 @@

Terminal

Start experiment

-

Arming and the bench motor are enabled only while an experiment runs. +

The experiment starts immediately. Arming and the bench motor remain + locked until the background checks pass. Stopping ramps the motor down, waits for the rotor to stop, applies safe-off, and saves the MAVLink log as JSON.