File size: 5,441 Bytes
49ef597
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// MPPI over the world model's imagined futures: a port of cablepilot/planner/mppi.py (same config keys, same steps).
// Per tick: perturb the nominal plan with temporally correlated noise (coarse + fine scales), roll every candidate out
// through the world model, score it (task costs + smoothness), softmax with the temperature solved so the effective
// sample size stays at ess_target * S, move the nominal a step towards the weighted average, execute its first action.

export function rng(seed) {                      // mulberry32 + Box-Muller
  let a = seed >>> 0, spare = null;
  const u = () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
  return { u, n() { if (spare !== null) { const s = spare; spare = null; return s; }
    const r = Math.sqrt(-2 * Math.log(u() + 1e-12)), th = 2 * Math.PI * u(); spare = r * Math.sin(th); return r * Math.cos(th); } };
}

export const PLANNER = {           // configs/planner_learned.yaml
  dt: 0.2, horizon: 10, samples: 128, ess_target: 0.1,
  sigma: [0.06, 0.06, 0.03, 0.4, 0.0], noise_corr: 0.9, r_weights: [90, 90, 90, 1, 0],
  step_size: 0.3, sigma_scales: [1.0, 0.2], keep_rollouts: 12,
  a_min: [-0.3, -0.3, -0.3, -1.5, 0.0], a_max: [0.3, 0.3, 0.3, 1.5, 1.0],
};

export class MPPI {
  constructor(cfg, seed = 0) { this.cfg = cfg; this.r = rng(seed); this.nominal = null; }

  reset(aNow) {
    const { horizon: T } = this.cfg;
    this.nominal = new Float32Array(T * 5);
    for (let k = 0; k < T; k++) this.nominal.set(aNow, k * 5);
  }

  temperature(dJ) {                               // bisection on log-temperature: ESS = 1/sum(w^2) -> target
    const S = dJ.length, target = Math.max(1, this.cfg.ess_target * S);
    const sorted = Float64Array.from(dJ).sort(), scale = sorted[S >> 1] + 1e-9;
    let lo = -12, hi = 12;
    for (let it = 0; it < 30; it++) {
      const mid = (lo + hi) / 2, tmp = scale * 10 ** mid;
      let z = 0, z2 = 0;
      for (let i = 0; i < S; i++) { const e = Math.exp(-dJ[i] / tmp); z += e; z2 += e * e; }
      if (z * z / z2 < target) lo = mid; else hi = mid;
    }
    return scale * 10 ** hi;
  }

  /** rolloutFn(plans, S) -> Float32Array (S*T*14); costFn(states, plans, S) -> Float64Array (S); fixed {dim: value}.
   *  aPrev: the command being executed. Returns {action, info}. */
  plan(rolloutFn, costFn, aPrev, fixed = {}) {
    const c = this.cfg, S = c.samples, T = c.horizon, A = 5;
    if (!this.nominal) this.reset(aPrev);
    for (const [i, v] of Object.entries(fixed)) for (let k = 0; k < T; k++) this.nominal[k * A + +i] = v;
    const t0 = performance.now();
    // 1. candidates: nominal + AR(1) noise, scales cycled per sample, sample 0 = the nominal itself
    const cands = new Float32Array(S * T * A), rho = c.noise_corr, q = Math.sqrt(1 - rho * rho);
    const eps = new Float64Array(A);
    for (let s = 0; s < S; s++) {
      const sc = c.sigma_scales[s % c.sigma_scales.length];
      for (let k = 0; k < T; k++)
        for (let i = 0; i < A; i++) {
          const w = this.r.n();
          eps[i] = k === 0 ? w : rho * eps[i] + q * w;
          let e = s === 0 || i in fixed ? 0 : eps[i] * c.sigma[i] * sc;
          const v = this.nominal[k * A + i] + e;
          cands[(s * T + k) * A + i] = Math.min(c.a_max[i], Math.max(c.a_min[i], v));
        }
    }
    const t1 = performance.now();
    const states = rolloutFn(cands, S);
    const t2 = performance.now();
    // 3. costs: the task's terms + smoothness sum_k R (a_k - a_{k-1})^2
    const { J, terms } = costFn(states, cands, S);
    for (let s = 0; s < S; s++) {
      let sm = 0;
      for (let k = 0; k < T; k++)
        for (let i = 0; i < A; i++) {
          const prev = k === 0 ? aPrev[i] : cands[(s * T + k - 1) * A + i];
          const d = cands[(s * T + k) * A + i] - prev; sm += c.r_weights[i] * d * d;
        }
      J[s] += sm;
    }
    const t3 = performance.now();
    // 4. softmax at the ESS temperature, move the nominal towards the weighted average
    let Jmin = Infinity; for (let s = 0; s < S; s++) Jmin = Math.min(Jmin, J[s]);
    const dJ = J.map(v => v - Jmin), temp = this.temperature(dJ);
    const w = new Float64Array(S); let z = 0;
    for (let s = 0; s < S; s++) { w[s] = Math.exp(-dJ[s] / temp); z += w[s]; }
    let z2 = 0; for (let s = 0; s < S; s++) { w[s] /= z; z2 += w[s] * w[s]; }
    for (let k = 0; k < T; k++)
      for (let i = 0; i < A; i++) {
        let avg = 0; for (let s = 0; s < S; s++) avg += w[s] * cands[(s * T + k) * A + i];
        this.nominal[k * A + i] += c.step_size * (avg - this.nominal[k * A + i]);
      }
    const t3b = performance.now();
    const nomStates = rolloutFn(this.nominal, 1);
    const t4 = performance.now();
    const action = Array.from(this.nominal.subarray(0, A));
    const order = Array.from({ length: S }, (_, i) => i).sort((a, b) => J[a] - J[b]).slice(0, c.keep_rollouts);
    const best = order.map(s => states.subarray(s * T * 14, (s + 1) * T * 14));
    // receding horizon: shift, repeat the last
    this.nominal.copyWithin(0, A); this.nominal.set(this.nominal.subarray((T - 2) * A, (T - 1) * A), (T - 1) * A);
    return { action, info: { nominal: nomStates, rollouts: best, ess: 1 / z2, costMin: Jmin, terms,
      ms: { noise: t1 - t0, rollout: t2 - t1 + (t4 - t3b), cost: t3 - t2, update: t3b - t3, total: t4 - t0 } } };
  }
}