File size: 5,904 Bytes
4cefcfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/* Next Balance Space: change load, delay, noise and friction; both controllers re-simulate in the browser. */
const { $, h, fmt, lineChart, legend, css } = NLUI;
let ctx, last, anim = null;
const COL = { pid: "#8a8f98", adaptive: "#0b6e4f", ref: "#b07d12" };
const SL = [
  ["payload0", "Initial payload (kg)", 1, 4, 0.1, 2.5],
  ["dm", "Payload change at t = 4 s (kg)", -1, 12, 0.5, 5],
  ["fric_gain", "Friction multiplier at t = 7 s", 1, 6, 0.1, 2.5],
  ["delay_ms", "Actuator delay (ms)", 0, 80, 10, 30],
  ["noise_mm", "Sensor noise std (mm)", 0, 10, 0.5, 2],
  ["seed", "Noise seed", 1, 50, 1, 7],
];

function scenario() {
  const v = id => Number($(id).value);
  return { payload0: v("payload0"), t_load: 4.0, dm: v("dm"), c0: 3.5, F0: 2.0, t_fric: 7.0, fric_gain: v("fric_gain"),
    delay: Math.round(v("delay_ms") / 10), noise: v("noise_mm") / 1000, T: 12.0, seed: v("seed") };
}

function run() {
  const sc = scenario();
  for (const s of SL) $(s[0] + "_v").textContent = $(s[0]).value;
  const res = {};
  for (const c of ["pid", "adaptive"]) {
    const tr = Core.simulate(sc, c, ctx.params[c], 1);
    res[c] = { tr, m: Core.metrics(sc, tr) };
  }
  last = { sc, res };
  draw();
  return res;
}

function draw() {
  const { sc, res } = last;
  const pts = (tr, key) => tr.t.map((t, i) => [t, tr[key][i]]).filter((_, i) => i % 2 === 0);
  const s1 = [{ name: "fixed PID", color: COL.pid, points: pts(res.pid.tr, "z") },
    { name: "adaptive (Next Balance)", color: COL.adaptive, points: pts(res.adaptive.tr, "z") }];
  lineChart($("zc"), s1, { xlabel: "time (s)", hlines: [{ y: Core.Z_REF, color: COL.ref }], ymin: Math.min(0, ...s1.flatMap(s => s.points.map(p => p[1]))) });
  legend($("zl"), s1.concat([{ name: "target 0.5 m", color: COL.ref }]));
  const s2 = [{ name: "fixed PID", color: COL.pid, points: pts(res.pid.tr, "u") }, { name: "adaptive", color: COL.adaptive, points: pts(res.adaptive.tr, "u") }];
  lineChart($("uc"), s2, { xlabel: "time (s)", height: 170 });
  const trueM = res.adaptive.tr.t.map(t => [t, 2 + sc.payload0 + (t >= sc.t_load ? sc.dm : 0)]).filter((_, i) => i % 2 === 0);
  const s3 = [{ name: "true mass", color: COL.ref, points: trueM, dash: [5, 4] }, { name: "adaptive estimate", color: COL.adaptive, points: pts(res.adaptive.tr, "m_hat") }];
  lineChart($("mc"), s3, { xlabel: "time (s)", height: 170 });
  legend($("ml"), s3);
  const rows = [["Largest deviation after load change", "max_deviation_m", "m", 3],
    ["Settling time (±1 cm, from load change)", "settling_time_s", "s", 2], ["Control energy ∫u² dt", "control_energy_kN2s", "kN²·s", 3],
    ["Step overshoot", "step_overshoot_m", "m", 3], ["Final error", "final_error_m", "m", 4]];
  const tb = $("tbl"); tb.innerHTML = "";
  tb.append(h("tr", {}, h("th", {}, "Metric"), h("th", { class: "num" }, "fixed PID"), h("th", { class: "num" }, "adaptive")));
  for (const [label, k, unit, d] of rows) {
    const cell = c => {
      let txt = fmt(res[c].m[k], d) + " " + unit;
      if (k === "settling_time_s" && !res[c].m.settled) txt = "not settled";
      return h("td", { class: "num" }, txt);
    };
    tb.append(h("tr", {}, h("td", {}, label), cell("pid"), cell("adaptive")));
  }
  playFrame(Math.floor(res.pid.tr.t.length * 0.5));
}

function playFrame(i) {
  const c = $("anim"), W = c.clientWidth || 400, H = 220, dpr = window.devicePixelRatio || 1;
  c.width = W * dpr; c.height = H * dpr; c.style.height = H + "px";
  const g = c.getContext("2d"); g.scale(dpr, dpr);
  g.fillStyle = css("--panel"); g.fillRect(0, 0, W, H);
  const { sc, res } = last, t = res.pid.tr.t[i];
  const Y = z => H - 30 - (z / 1.0) * (H - 60);
  g.strokeStyle = COL.ref; g.setLineDash([5, 4]); g.beginPath(); g.moveTo(0, Y(0.5)); g.lineTo(W, Y(0.5)); g.stroke(); g.setLineDash([]);
  const m = 2 + sc.payload0 + (t >= sc.t_load ? sc.dm : 0);
  [["pid", W * 0.28], ["adaptive", W * 0.72]].forEach(([k, x]) => {
    const z = Math.max(-0.2, Math.min(1.2, res[k].tr.z[i]));
    g.fillStyle = css("--line"); g.fillRect(x - 3, Y(z), 6, H - 20 - Y(z));
    g.fillStyle = COL[k]; g.fillRect(x - 50, Y(z) - 8, 100, 8);
    const box = 10 + 3 * m; g.fillStyle = css("--muted"); g.fillRect(x - box / 2, Y(z) - 8 - box, box, box);
    g.fillStyle = css("--ink"); g.font = "12px system-ui"; g.fillText(k === "pid" ? "fixed PID" : "adaptive", x - 28, H - 4);
  });
  g.fillStyle = css("--muted"); g.fillText(`t = ${t.toFixed(2)} s · mass ${m.toFixed(1)} kg`, 8, 14);
  $("scrub").value = i;
}

function play() {
  if (anim) { cancelAnimationFrame(anim); anim = null; $("play").textContent = "Play"; return; }
  $("play").textContent = "Pause";
  let i = 0; const n = last.res.pid.tr.t.length;
  const step = () => { playFrame(i); i += 4; if (i < n) anim = requestAnimationFrame(step); else { anim = null; $("play").textContent = "Play"; } };
  step();
}

window.__liveTest = function () {
  const before = run();
  $("dm").value = "11"; $("delay_ms").value = "60"; $("noise_mm").value = "6";
  $("dm").dispatchEvent(new Event("input"));
  const after = { pid: last.res.pid.m, adaptive: last.res.adaptive.m };
  const tableText = $("tbl").textContent;
  return { ok: after.pid.max_deviation_m !== before.pid.m.max_deviation_m && tableText.includes("adaptive") && last.sc.dm === 11 && last.sc.delay === 6,
    pid: after.pid, adaptive: after.adaptive };
};

NLUI.boot(Core, async c => {
  ctx = c;
  const box = $("sliders");
  for (const [id, label, lo, hi, step, val] of SL) {
    box.append(h("label", { for: id }, label, ": ", h("b", { id: id + "_v" }, String(val))),
      h("input", { type: "range", id, min: lo, max: hi, step, value: val, oninput: run }));
  }
  $("play").addEventListener("click", play);
  $("scrub").addEventListener("input", e => playFrame(Number(e.target.value)));
  window.addEventListener("resize", () => last && draw());
  run();
  $("scrub").max = last.res.pid.tr.t.length - 1;
});