// Robot Setup Advisor: project, robot, training, inference, compare, summary, start.
// Data lives in data.js; robots/reach.js holds the reach profiles baked from each robot's URDF.
const PAYLOADS = [0.1,0.2,0.3,0.5,0.75,1,1.5,2,3,4,5,7,10,12,15,20,25,30];
const SERIES = ['var(--s1)','var(--s2)','var(--s3)','var(--s4)'];
const STEPS = ['project', 'robot', 'train', 'infer', 'compare', 'summary', 'start'];
const TASKS = {tabletop:'One-arm pick & place', bimanual:'Two arms', mobile:'Mobile manipulation', humanoid:'Humanoid', interaction:'Human interaction'};
const MODES = {onboard:'On the robot', local:'Next to the robot', remote:'Remote or cloud GPU'};
const REACHED = 0.97; // share of the work area the gripper must reach
const $ = id => document.getElementById(id);
const byId = (list, id) => list.find(x => x.id === id);
const esc = t => String(t).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const link = (t, u) => `${t}`;
const radio = n => document.querySelector(`input[name=${n}]:checked`).value;
const money = n => n == null ? '–' : n > 0 && n < 1 ? '<$1' : n >= 10000 ? '$' + Math.round(n / 1000) + 'k' : n >= 1000 ? '$' + (n / 1000).toFixed(1).replace('.0', '') + 'k' : '$' + Math.round(n);
const kg = n => n >= 1000 ? (n / 1000).toFixed(n >= 10000 ? 0 : 1) + ' t' : Math.round(n) + ' kg';
const num = (n, d = 0) => n.toLocaleString('en-US', {maximumFractionDigits: d, minimumFractionDigits: d});
const hrs = h => h < 1 ? Math.round(h * 60) + ' min' : h < 10 ? num(h, 1) + ' h' : Math.round(h) + ' h';
const watts = (w, est) => (est ? '≈' : '') + num(w) + ' W';
const letter = i => String.fromCharCode(65 + i);
const LEROBOT = {native:['LeRobot native','ok'], plugin:['LeRobot plugin','ok'], community:['Community driver','warn']};
const robotQuotes = Object.create(null);
const robotPrice = u => u.price == null ? 'Quote required' : money(u.price);
const totalCost = m => money(m.life.cost) + (m.missingRobotPrice ? ' + robot quote' : '');
let step = 'project';
let view = null; // unit shown in the 3D viewer
let pick = {rid:null, gid:null, bid:null}; // the user's own choices, else the suggestion
let cmp = null; // edited comparison columns, else the suggestion
let lastRec = null;
// ---------- state
function readState() {
const s = {goal:radio('goal'), task:radio('task'), variety:radio('variety'), learning:radio('learning'), budget:radio('budget'), prio:radio('prio'),
compute:radio('compute'), infer:radio('infer'), data:radio('data'), payload:PAYLOADS[+$('payload').value],
ws:{w:+$('wsW').value / 100, d:+$('wsD').value / 100, h:+$('wsH').value / 100, g:+$('wsG').value / 100},
own:$('own').value, country:$('country').value, hours:+$('hours').value, days:+$('days').value, years:+$('years').value, runs:+$('runs').value};
s.C = COUNTRIES[s.country];
return s;
}
function resetPicks() { pick = {rid:null, gid:null, bid:null}; cmp = null; view = null; }
// A deployable unit: one robot, or two identical arms for a bimanual task.
function unit(id) {
if (!id) return null;
const pair = id.startsWith('pair:');
const r = byId(ROBOTS, pair ? id.slice(5) : id);
if (!r) return null;
const n = pair ? 2 : 1;
return {id, r, n, name:(n === 2 ? '2 × ' : '') + r.name, price:(robotQuotes[r.id] ?? r.price) == null ? null : (robotQuotes[r.id] ?? r.price) * n, mass:r.mass * n, power:r.power * n,
payload:r.payload, reach:r.reach, arms:n === 2 || r.kind === 'bimanual' ? 2 : 1, moves:r.kind === 'mobile' || r.id === 'g1'};
}
function unitsFor(task) {
const kinds = {tabletop:['arm'], bimanual:['bimanual'], mobile:['mobile'], humanoid:['humanoid'], interaction:['interaction']}[task];
const ids = ROBOTS.filter(r => kinds.includes(r.kind)).map(r => r.id);
if (task === 'bimanual') ROBOTS.filter(r => r.kind === 'arm').forEach(r => ids.push('pair:' + r.id));
if (task === 'humanoid' || task === 'interaction') ids.push('reachy2');
return ids.map(unit);
}
// ---------- reach: profiles baked from the URDF, or a sphere when no model exists
const modelOf = r => r.model || r.id;
const hasModel = r => ROBOT_MODELS.includes(modelOf(r));
// Where the robot model(s) and arm bases sit, in metres, x forward, z up.
function layout(u, s) {
const prof = REACH[modelOf(u.r)] || null;
const spread = Math.max(s.ws.w / 4, 0.15);
const twoModels = u.n === 2 || u.r.id === 'bi_so101';
const models = twoModels ? [{y:-spread}, {y:spread}] : [{y:0}];
let mounts;
if (twoModels) mounts = models.map(m => ({x:prof ? prof.x : 0, y:m.y + (prof ? prof.y : 0)}));
else if (u.arms === 2) mounts = prof ? [{x:prof.x, y:Math.abs(prof.y)}, {x:prof.x, y:-Math.abs(prof.y)}] : [{x:0, y:-spread}, {x:0, y:spread}];
else mounts = [{x:prof ? prof.x : 0, y:prof ? prof.y : 0}];
// arms mounted high (OpenArm's shoulders) work over a table at about elbow height
let table = 0;
if (prof) {
const k = prof.rmax.reduce((best, v, i) => (v || 0) > (prof.rmax[best] || 0) ? i : best, 0), zs = (k + 0.5) * prof.dz;
if (zs > 0.45) table = Math.round((zs - 0.35) * 20) / 20;
}
return {prof, models, mounts, table, R:0.9 * u.reach};
}
function reachable(L, x, y, z) {
return L.mounts.some(m => {
const r = Math.hypot(x - m.x, y - m.y);
if (!L.prof) return Math.hypot(r, z) <= L.R;
const k = Math.floor((z + L.table) / L.prof.dz), lo = L.prof.rmin[k], hi = L.prof.rmax[k];
return hi != null && r >= lo && r <= 0.97 * hi;
});
}
function boxPoints(s, n = 5) {
const pts = [], {w, d, h, g} = s.ws;
for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) for (let k = 0; k < n; k++)
pts.push([g + d * i / (n - 1), -w / 2 + w * j / (n - 1), Math.max(0.005, h * k / (n - 1))]);
return pts;
}
const reachCache = new Map();
function reachFrac(u, s) {
const key = u.id + JSON.stringify(s.ws);
if (!reachCache.has(key)) {
const L = layout(u, s), pts = boxPoints(s);
reachCache.set(key, pts.filter(p => reachable(L, ...p)).length / pts.length);
}
return reachCache.get(key);
}
function usable(u) {
if (!u.reach) return 0;
const prof = REACH[modelOf(u.r)];
if (!prof) return u.arms * (2 / 3) * Math.PI * ((0.9 * u.reach) ** 3 - (0.15 * u.reach) ** 3);
let v = 0;
prof.rmax.forEach((hi, k) => { if (hi != null) v += Math.PI * (hi * hi - prof.rmin[k] ** 2) * prof.dz; });
return u.arms * v;
}
function fit(u, s) {
if (s.task === 'interaction') return {ok:true, payload:true, reach:true, budget:true, frac:1, why:[], margin:1};
const frac = u.reach ? reachFrac(u, s) : 0;
const payload = u.payload >= s.payload, reach = u.moves || frac >= REACHED;
const cap = {low:1000, mid:10000}[s.budget];
const budget = s.budget === 'own' || !cap || (u.price != null && u.price <= cap);
const why = [];
if (!payload) why.push(`payload ${u.payload} kg < ${s.payload} kg`);
if (!reach) why.push(`reaches ${Math.round(frac * 100)}% of the work area`);
const far = Math.hypot(s.ws.g + s.ws.d, s.ws.w / (u.arms === 2 ? 4 : 2), s.ws.h);
return {ok:payload && reach, payload, reach, budget, frac, why, margin:Math.min(u.payload / s.payload, u.moves ? 9 : 0.9 * u.reach / far)};
}
// ---------- policy, training GPU, inference hardware
function pickPolicy(s, rid) {
if (rid === 'reachymini') return null;
if (s.learning === 'rl') return ['hilserl', 'act'];
if (s.task === 'humanoid') return s.compute === 'consumer' || s.compute === 'none' || s.infer === 'onboard' ? ['act', 'groot'] : ['groot', 'act'];
if (s.variety === 'multi') {
const big = s.infer !== 'onboard' && (s.compute === 'cluster' || (s.compute === 'cloud' && s.goal !== 'learn'));
return big ? ['pi05', 'smolvla'] : ['smolvla', 'pi05'];
}
return ['act', 'smolvla'];
}
function gpuFit(g, P) { return g.vram >= P.train ? 'ok' : g.vram >= P.tight ? 'tight' : 'no'; }
function training(g, P, s) {
const cloud = g.loc === 'cloud';
const h = P.local ? 3 : P.a100h / Math.min(g.speed, P.maxSpeed || 9); // RL: illustrative session allowance, not a convergence prediction.
const kWh = h * (g.w + g.hostW) / 1000 * (cloud ? CLOUD_PUE : 1);
return {h, kWh, cloud, cost:cloud ? h * g.hourly : kWh * s.C.usd, co2:kWh * (cloud ? COUNTRIES[CLOUD_GRID].g : s.C.g) / 1000,
fit:P.local && cloud ? 'no' : gpuFit(g, P)};
}
const ownedGpu = s => s.compute === 'consumer' ? 'rtx4090' : s.compute === 'cluster' ? 'a100' : null;
function defaultGpu(s, P) {
const cheapestCloud = () => GPUS.filter(g => g.loc === 'cloud' && gpuFit(g, P) === 'ok').sort((a, b) => training(a, P, s).cost - training(b, P, s).cost)[0].id;
if (P.local) return ownedGpu(s) || 'rtx4090';
if (s.compute === 'consumer') return gpuFit(byId(GPUS, 'rtx4090'), P) === 'ok' ? 'rtx4090' : cheapestCloud();
if (s.compute === 'cluster') return 'a100';
return cheapestCloud();
}
// Inference hardware: a board on or next to the robot, or a cloud GPU ("cloud:").
function runInfo(id, u) {
if (id.startsWith('cloud:')) {
const g = byId(GPUS, id.slice(6));
return {id, mode:'remote', cloud:true, g, name:'Cloud ' + g.name.replace('HF Jobs · ', ''), vram:g.vram, hourly:g.hourly, w:(g.w + g.hostW) * CLOUD_PUE, price:0};
}
const b = byId(BOARDS, id);
const mode = b.place === 'embedded' ? 'onboard' : 'local';
if (id === 'included') { const o = u && u.r.onboard; return {...b, mode, name:o ? o.name : b.name, vram:o ? o.vram : 0}; }
return {...b, mode};
}
function runOptions(mode, u) {
if (mode === 'onboard') return [...(u && u.r.onboard ? ['included'] : []), 'orinnano', 'orinnx', 'agxorin', 'thor'];
if (mode === 'local') return ['laptop', 'laptop4060', 'desk4090'];
return GPUS.filter(g => g.loc === 'cloud' && g.id !== 'a10g-large').map(g => 'cloud:' + g.id);
}
const runFit = (b, P) => !P ? 'ok' : (b.vram || 0) >= P.infer ? 'ok' : 'no';
function defaultRun(s, P, u, mode = s.infer) {
if (!P) return 'laptop';
const opts = runOptions(mode, u).map(id => runInfo(id, u)).filter(b => runFit(b, P) === 'ok');
if (mode === 'remote') return opts.sort((a, b) => a.hourly - b.hourly)[0].id;
if (mode === 'onboard' && opts.some(b => b.id === 'included')) return 'included';
return (opts.sort((a, b) => a.price - b.price)[0] || runInfo(mode === 'onboard' ? 'thor' : 'desk4090', u)).id;
}
// Everyone has a laptop; gaming-GPU owners already have the RTX desktop.
const ownsBoard = (s, b) => b.id === 'laptop' || (b.id === 'desk4090' && s.compute === 'consumer');
// ---------- full setup metrics
function metrics(setup, s) {
const u = unit(setup.rid), g = byId(GPUS, setup.gid), b = runInfo(setup.bid, u);
const pp = pickPolicy(s, u.r.id), P = pp ? POLICIES[pp[0]] : null;
const ownsRobot = s.budget === 'own' && s.own === u.id;
const ownsGpu = g.id === ownedGpu(s);
const T = P ? training(g, P, s) : {h:0, kWh:0, cost:0, co2:0, fit:'ok'};
const runs = P ? s.runs : 0;
const opH = s.hours * s.days;
// a cloud GPU still needs a computer at the robot: the robot's own, or a laptop
const local = b.cloud ? (u.r.onboard ? runInfo('included', u) : runInfo('laptop', u)) : b;
const powerW = u.power + local.w;
const opKWh = powerW * opH / 1000, cloudKWh = b.cloud ? b.w * opH / 1000 : 0;
const gpuBuy = P && g.loc === 'local' && !ownsGpu;
const ownB = ownsBoard(s, local);
const missingRobotPrice = !ownsRobot && u.price == null;
const hw = {robot:ownsRobot ? 0 : (u.price ?? 0), board:ownB ? 0 : local.price, gpu:gpuBuy ? g.price + g.host : 0};
const emb = {robot:ownsRobot ? 0 : u.mass * EMBODIED.robotPerKg,
board:local.id === 'included' || ownB ? 0 : local.id === 'desk4090' ? EMBODIED.pc + EMBODIED.gpuCard : local.id.startsWith('laptop') ? EMBODIED.pc : EMBODIED.board,
gpu:gpuBuy ? (g.id === 'a100' || g.id === 'h100' ? EMBODIED.server : g.id === 'mmax' ? EMBODIED.pc : EMBODIED.gpuCard + EMBODIED.pc) : 0};
const y = {train:runs * T.cost, infer:b.cloud ? b.hourly * opH : 0, elec:opKWh * s.C.usd,
kWh:opKWh + cloudKWh + runs * T.kWh, opCO2:opKWh * s.C.g / 1000 + cloudKWh * COUNTRIES[CLOUD_GRID].g / 1000, trainCO2:runs * T.co2};
const hardware = hw.robot + hw.board + hw.gpu, embodied = emb.robot + emb.board + emb.gpu;
const F = fit(u, s), space = usable(u);
return {u, g, b, local, P, pk:pp && pp[0], T, F, ownsRobot, ownsGpu, missingRobotPrice, hw, hardware, emb, embodied, y, powerW, space, bfit:runFit(b, P),
life:{hw:hardware, train:s.years * (y.train + y.infer), elec:s.years * y.elec, cost:hardware + s.years * (y.train + y.infer + y.elec),
emb:embodied, op:s.years * y.opCO2, tr:s.years * y.trainCO2, co2:embodied + s.years * (y.opCO2 + y.trainCO2)}};
}
function defaultSetup(s, u) {
const pp = pickPolicy(s, u.r.id), P = pp && POLICIES[pp[0]];
return {rid:u.id, gid:P ? defaultGpu(s, P) : 'l4x1', bid:defaultRun(s, P, u)};
}
function rankUnits(s) {
const list = unitsFor(s.task).map(u => { const m = metrics(defaultSetup(s, u), s); return {u, m, F:m.F}; });
const key = {size:x => x.u.mass * 1e6 + x.u.price, cost:x => x.m.missingRobotPrice ? Infinity : x.m.life.cost, co2:x => x.m.life.co2, margin:x => -x.F.margin}[s.prio];
const tier = x => (x.F.ok ? 0 : 4) + (x.F.budget ? 0 : 2) + (x.u.r.disc ? 1 : 0);
return list.sort((a, b) => tier(a) - tier(b) || key(a) - key(b));
}
// ---------- render
function stat(v, l) { return `
${v}${l}
`; }
function exampleList(r) {
if (!r.examples || !r.examples.length) return '';
return `
${r.examples.map(e => `
${link(esc(e.t), e.u)} ${esc(e.d)}
`).join('')}
`;
}
function fitTags(u, F, s) {
if (s.task === 'interaction') return '';
const t = [];
t.push(F.payload ? `✓ payload ×${num(u.payload / s.payload, 1)}` : `✗ payload ${u.payload} kg`);
if (u.moves) t.push('✓ moves to reach');
else t.push(F.reach ? '✓ reaches the whole area' : `✗ reaches ${Math.round(F.frac * 100)}%`);
if (!F.budget) t.push(`${u.price == null ? 'budget needs a quote' : 'over budget'}`);
t.push(u.r.lerobot ? `${LEROBOT[u.r.lerobot][0]}` : 'LeRobot adapter to validate');
if (u.r.open) t.push('Open hardware');
if (u.r.disc) t.push('discontinued');
return t.join('');
}
function render() {
const s = readState();
$('payloadOut').textContent = s.payload + ' kg';
['W', 'D', 'H', 'G'].forEach(k => $('ws' + k + 'Out').textContent = $('ws' + k).value + ' cm');
$('hoursOut').textContent = s.hours + ' h'; $('daysOut').textContent = s.days; $('yearsOut').textContent = s.years; $('runsOut').textContent = s.runs;
$('ownWrap').hidden = s.budget !== 'own';
const ranked = rankUnits(s);
let rec = ranked[0].u;
if (s.budget === 'own' && unit(s.own)) rec = unit(s.own);
const u = unit(pick.rid) || rec, R = u.r;
const pp = pickPolicy(s, R.id), pk = pp && pp[0], P = pk ? POLICIES[pk] : null, P2 = pp ? POLICIES[pp[1]] : null;
const gid = pick.gid || (P ? defaultGpu(s, P) : 'l4x1');
const bid = pick.bid && runOptions(s.infer, u).includes(pick.bid) ? pick.bid : defaultRun(s, P, u);
const M = metrics({rid:u.id, gid, bid}, s);
lastRec = {s, u, P, M, rec};
if (!view || !unit(view)) view = u.id;
renderSummary(s, M);
renderRobot(s, ranked, u, rec);
renderTraining(s, M, P, P2, pk);
renderInference(s, M, P, pk);
renderCompare(s, currentSetups(s, ranked, {rid:u.id, gid, bid}));
renderStart(s, M, R, pk);
renderOverview(s, M);
}
function renderSummary(s, M) {
$('sumProject').textContent = TASKS[s.task];
$('sumRobot').textContent = M.u.name;
$('sumTrain').textContent = M.P ? `${M.P.name} · ${M.g.name.replace('HF Jobs · ', 'HF Jobs ')}` : 'No training';
$('sumInfer').textContent = M.P ? M.b.name : 'Laptop';
$('sumCompare').textContent = `${totalCost(M)} · ${kg(M.life.co2)} CO2`;
}
function renderOverview(s, M) {
const rl = !!(M.P && M.P.local), F = fit(M.u, s), R = M.u.r;
const route = !M.P ? 'Python apps · no policy training' : rl ? 'Reinforcement learning · learn from rewards' : 'Imitation learning · learn from demonstrations';
$('sumOverview').textContent = !M.P ? 'Your app setup' : rl ? 'RL · rewards & practice' : 'IL · demonstrations';
const data = !M.P ? 'Start with a Reachy Mini app and test its interaction in your environment.' : rl
? 'Define a measurable reward, repeatable episode resets and a supervised practice environment. HIL-SERL uses demonstrations, a reward classifier and human interventions; confirm hardware and action-space support first.'
: 'Record representative successful demonstrations, train or fine-tune a policy, then evaluate on held-out conditions. Add corrections where it fails. Precision alone does not require RL.';
$('overview').innerHTML = `
YOUR LEARNING PATH
${route}
${data}
IL and RL are different learning objectives. They can be combined: demonstrations can seed RL, and a policy can be refined with rewards. Neither guarantees a target success rate.
Robot & integration
${esc(M.u.name)}
${F.ok ? 'Estimated payload and reach fit your work area.' : 'Review physical fit: '+esc(F.why.join('; '))+'.'} Collision, tooling and deployment validation are still required.
${R.lerobot ? esc(LEROBOT[R.lerobot][0]) : 'Custom integration required: verify a LeRobot Robot adapter before collecting data.'}
${rl ? 'Budget uses an illustrative 3-hour practice session. Real elapsed time depends on resets, task difficulty and interaction; it is not predicted from GPU speed.' : 'Training figures are indicative; benchmark on your own data.'}
Includes modeled hardware, compute and electricity. Excludes integration, grippers, safety systems and labor.
CO₂ is an unverified planning scenario, not a measured product footprint. Electricity factors come from Ember’s 2025 generation data; manufacturing still uses generic assumptions. Sources & limits.
Your next steps
Confirm robot integration, payload, reach and the task success criterion.
${!M.P ? 'Run and adapt an app.' : rl ? 'Validate rewards, resets and intervention controls; then configure the HIL-SERL actor and learner.' : 'Collect demonstrations covering the variation you expect in deployment.'}
Measure success on fresh trials before expanding the pilot.
${link('Read the companies guide summary', 'https://cetiennec-lerobot-for-companies.hf.space/summary/')}
`;
}
function pdfReport(s, M, now = new Date()) {
const rl = !!(M.P && M.P.local), R = M.u.r;
const usd = value => '$' + value.toLocaleString('en-US', {minimumFractionDigits:value > 0 && value < 10 ? 2 : 0, maximumFractionDigits:value > 0 && value < 10 ? 2 : 0});
const co2 = value => num(value, 1) + ' kg CO2e';
return {
robot:M.u.name,
date:now.toLocaleDateString('en-GB', {day:'numeric',month:'long',year:'numeric'}),
path:!M.P ? 'Python apps - no policy training' : rl ? 'Reinforcement learning - rewards & practice' : 'Imitation learning - demonstrations',
hardware:[
`Task: ${TASKS[s.task]}. Goal: ${s.goal}. Dataset visibility: ${s.data}.`,
`Robot: ${M.u.name} (${R.maker}). ${M.ownsRobot ? 'Already owned; no new purchase cost.' : M.u.price == null ? 'Vendor quote required; robot price is missing.' : 'Robot purchase allowance: ' + usd(M.u.price) + '.'}`,
`Integration: ${R.lerobot ? LEROBOT[R.lerobot][0] : 'Custom LeRobot adapter to validate'}.`,
`Payload requirement (object + gripper): ${s.payload} kg. Work area: ${num(s.ws.w*100)} x ${num(s.ws.d*100)} x ${num(s.ws.h*100)} cm; base gap ${num(s.ws.g*100)} cm.`,
M.F.ok ? 'Estimated payload and reach fit. Validate collisions, tooling and the real task.' : 'Physical fit needs review: ' + M.F.why.join('; ') + '.',
],
learning:!M.P ? ['Start with a Reachy Mini app. No policy training is modeled. Runtime: ' + M.b.name + '.'] : [
`Policy: ${M.P.name}. Training compute: ${M.g.name}.`,
`Runtime: ${M.b.name} (${MODES[s.infer]}).`,
rl ? 'HIL-SERL needs a measurable reward, repeatable resets, demonstrations and supervised practice. The modeled session is a 3-hour compute allowance, not a convergence prediction.' : 'Record representative successful demonstrations, train or fine-tune, then evaluate on fresh trials. Training time is an indicative model, not a benchmark for your dataset.',
`Modeled compute per ${rl ? 'session' : 'run'}: ${hrs(M.T.h)}, ${usd(M.T.cost)}, ${co2(M.T.co2)}. Planned frequency: ${s.runs}/year.`,
],
estimates:[
`${s.years}-year scenario: ${s.hours} hours/day, ${s.days} days/year; ${s.C.name}.`,
`Known cost: ${usd(M.life.cost)}${M.missingRobotPrice ? ' + robot quote (INCOMPLETE TOTAL)' : ''}. Hardware ${usd(M.life.hw)}; training/cloud ${usd(M.life.train)}; local electricity ${usd(M.life.elec)}.`,
`Indicative CO2e total: ${co2(M.life.co2)}. Manufacturing assumptions ${co2(M.life.emb)}; training electricity ${co2(M.life.tr)}; operation electricity ${co2(M.life.op)}.`,
`Local generation factor: ${s.C.g} g CO2e/kWh (Ember 2025). Manufacturing inputs are generic assumptions, not verified product footprints.`,
],
nextSteps:[
'Confirm robot integration, payload, reach and a measurable task success criterion.',
!M.P ? 'Run and adapt a Reachy Mini app in your environment.' : rl ? 'Validate reward, resets and intervention controls, then configure the HIL-SERL actor and learner.' : 'Collect demonstrations covering expected deployment variation; inspect the data before training.',
'Measure success on fresh trials and review failures before expanding the pilot.',
],
limits:[
'IL and RL are different learning objectives and can be combined. Neither guarantees a target success rate.',
'Costs exclude integration, grippers, safety systems and labor. Robot prices and session-only vendor quotes are planning inputs.',
'Electricity uses Ember 2025 lifecycle generation factors held constant across the scenario. These are not supplier-specific or corporate Scope 2 factors.',
`Cloud calculations assume ${COUNTRIES[CLOUD_GRID].name} (${COUNTRIES[CLOUD_GRID].g} g CO2e/kWh) and PUE ${CLOUD_PUE}; these are not verified provider measurements.`,
`Manufacturing assumptions: robot ${EMBODIED.robotPerKg} kg CO2e/kg; GPU ${EMBODIED.gpuCard} kg; server ${num(EMBODIED.server)} kg; PC ${EMBODIED.pc} kg; embedded board ${EMBODIED.board} kg. No new manufacturing is added for owned hardware; historical emissions are not zero.`,
'The scenario omits shared cloud hardware manufacturing, transport, maintenance and end-of-life. RL robot practice energy, resets and operator time need separate budgeting.',
],
links:[
{label:'CO2 sources, exact grid snapshot and calculation limits',url:'https://cetiennec-robot-setup-advisor.static.hf.space/sources.html'},
{label:!M.P?'Reachy Mini getting started':rl?'HIL-SERL walkthrough':'Imitation learning walkthrough',url:!M.P?'https://huggingface.co/reachy-mini':D+(rl?'hilserl':'il_robots')},
{label:'Robot setup advisor (opens a new default setup)',url:'https://cetiennec-robot-setup-advisor.static.hf.space/index.html'},
],
};
}
function renderRobot(s, ranked, u, rec) {
const V = unit(view), F = fit(V, s), R = V.r, space = usable(V);
const vm = metrics(defaultSetup(s, V), s);
// chips: the top candidates, plus the chosen and viewed robots
const top = ranked.filter(x => x.F.ok && x.F.budget).slice(0, 5).map(x => x.u.id);
[u.id, view].forEach(id => { if (!top.includes(id)) top.push(id); });
$('chips').innerHTML = top.map(id => {
const x = unit(id);
return ``;
}).join('');
const warn = !F.ok && V.id === rec.id ? `
No robot in the catalog for this task meets ${esc(F.why.join(' and '))}. Shown: the closest one; try a smaller work area or a lighter gripper.
`
: !F.budget && V.id === rec.id ? '
The suggested robot has no confirmed price within this budget. Browse alternatives or enter a vendor quote.
` : '');
const G = M.g, T = M.T;
let where;
if (P.local) where = 'HIL-SERL learns online, so the GPU sits next to the robot: a desktop with an RTX card is enough to start.';
else if (G.loc === 'cloud') where = `${s.compute === 'consumer' ? `Your 12–24 GB card is too small or tight for ${P.name}. ` : ''}Train on Hugging Face Jobs, billed by the second, with --job.target=${G.job}.`;
else if (s.compute === 'cluster') where = 'Your servers fit every LeRobot policy. Use accelerate launch --num_processes=N for near-linear speedup across GPUs.';
else where = pk === 'smolvla' ? 'Fits a 16–24 GB card. On 12 GB, keep freeze_vision_encoder=True and lower the batch size.' : 'Fits your card comfortably.';
const rows = GPUS.map(g => {
const t = training(g, P, s), sel = g.id === G.id;
const fitTxt = t.fit === 'ok' ? 'fits' : t.fit === 'tight' ? 'tight' : (P.local && g.loc === 'cloud' ? 'local practice required' : 'too small');
const buy = g.loc === 'cloud' ? 'per use' : g.id === ownedGpu(s) ? 'yours' : money(g.price + g.host);
return `
${esc(g.name)}
${g.vram} GB
${fitTxt}
${t.fit === 'no' ? '–' : hrs(t.h)}
${t.fit === 'no' ? '–' : money(t.cost)}
${buy}
${t.fit === 'no' ? '–' : num(t.co2, 2) + ' kg'}
`;
}).join('');
$('train').innerHTML = `
Training compute
${esc(G.name)}${G.loc === 'cloud' ? 'no GPU to buy' : ''}
${P.name} needs ${P.vramTxt}. ${P.local ? 'An illustrative practice session is budgeted at ' : 'One run (50 episodes) takes about '}${hrs(T.h)} and costs ${money(T.cost)}; ${s.runs} runs a year: ${money(s.runs * T.cost)} and ${kg(s.runs * T.co2)} CO2e.
${where}
GPU
Memory
${P.name}
Per run
Cost/run
To buy
CO2/run
${rows}
${P.local ? 'RL compute time is a 3-hour planning allowance, not a measured prediction. Budget robot energy during practice, resets and operator time separately.' : 'Click a row to train there. Times scale the LeRobot guide figures by each GPU’s relative throughput; HF Jobs prices from hf jobs hardware.'}
`;
}
function renderInference(s, M, P, pk) {
const u = M.u;
if (!P) {
$('inferHw').innerHTML = '
Hardware
Reachy Mini apps run on your laptop or on the wireless version’s own computer.
';
$('inferTech').innerHTML = '
How to deploy it
Install the Reachy Mini SDK and run an app from the Hub.
${P.name} needs ${P.infer ? 'about ' + P.infer + ' GB of GPU memory' : 'no GPU: a CPU can run it'}.${M.b.cloud ? ` At ${s.hours} h a day, ${s.days} days a year, this GPU costs ${money(M.y.infer)} a year.` : ''}
Computer
Memory
${P.name}
Power
Cost
${rows}
Click a row to use it.${s.infer === 'remote' ? ' Cloud prices use Hugging Face hourly GPU rates for every hour the robot runs.' : ''}
`;
$('inferTech').innerHTML = `
How to deploy it
${techniques(s, P, pk, u, M.b)}`;
}
// Deployment techniques per inference location, from the LeRobot rollout and remote inference docs.
const HOLD = {so101:'yes', bi_so101:'yes', omx:'yes', hopejr:'yes', lekiwi:'no', openarm:'config', reachy2:'config', g1:'sonic'};
function techniques(s, P, pk, u, b) {
const D2 = 'https://huggingface.co/docs/lerobot/';
const flow = pk === 'smolvla' || pk === 'pi05';
const items = [];
const add = (t, d) => items.push(`
${t}
${d}
`);
let warn = '';
if (s.infer === 'onboard') {
add('Run the policy where the robot is', `Start lerobot-rollout --strategy.type=base on the ${esc(b.name)} with --device=cuda. No network in the loop: latency is only the board’s compute time.`);
if (flow) add('Hide inference time with Real-Time Chunking', `Add --inference.type=rtc: ${P.name} computes the next chunk of actions in a background thread while the robot keeps moving. ${link('RTC guide', D2 + 'rtc')}`);
add('Speed up a fixed task', 'With --use_torch_compile=true inference gets faster once warmed up; leave it off while you change spoken instructions, since new shapes trigger recompilation.');
add('Keep the model small', pk === 'act' ? 'ACT is light: an Orin Nano class board is enough.' : `${P.name} needs about ${P.infer} GB of GPU memory, shared with the system on a Jetson; the ${esc(b.name)} has ${b.vram || 0} GB. ${pk === 'smolvla' ? 'A 16 GB Orin NX leaves headroom for cameras and recording.' : 'If a Thor-class board is too much for the battery, run it next to the robot instead.'}`);
add('Budget the power', `The board draws about ${num(b.w)} W on top of the robot; count it in your battery runtime.`);
} else if (s.infer === 'local') {
add('Policy on the computer wired to the robot', `Run lerobot-rollout on that computer.${flow ? ' Add --inference.type=rtc so the robot keeps moving while the next chunk is computed.' : ' Chunked policies such as ACT run smoothly synchronously.'} ${link('Deployment guide', D2 + 'inference')}`);
add('GPU box elsewhere on the network', `Start lerobot-policy-server on the GPU box, then lerobot-rollout --inference.type=remote --inference.endpoint=tcp/<gpu-box-ip>:7447 on the robot computer, which only handles cameras, motors and recording. ${link('Remote inference guide', D2 + 'remote_inference')}`);
add('Smooth the seams between chunks', 'Keep --inference.chunk_merge=aligned (the default) to drop steps the robot has already passed; add a short blend with --inference.blend_steps once the timing works.');
add('Stay on a trusted LAN', 'Bind the server to its LAN address only: plain TCP does not authenticate peers.');
} else {
add('Policy server in the cloud, robot client on site', `Run lerobot-policy-server on the ${esc(b.name)} and lerobot-rollout --inference.type=remote on the robot computer. The robot keeps executing buffered actions while the server computes the next chunk. ${link('Remote inference guide', D2 + 'remote_inference')}`);
add('Go through an authenticated router', 'Over the internet, connect both sides through a Zenoh router with TLS, mutual certificates and access rules (examples/remote_inference/zenoh), never bare TCP.');
add('Cut image bandwidth', 'Send camera frames as JPEG with --inference.encoding=jpeg --inference.jpeg_quality=90, then check that task success holds.');
add('Budget for latency', 'Set --inference.refill_seconds to cover the round trip plus jitter, and keep max_observation_age_s and action_starvation_grace_s tight so the robot holds still rather than acting on stale images.');
if (flow) add('Use RTC if the checkpoint supports it', `--inference.mode=rtc_guided makes ${P.name} condition each new chunk on the actions still queued.`);
warn = '
The LeRobot docs note that running a robot through a router or a hosted GPU has not been validated yet: measure the full turnaround before relying on it.
';
}
if (s.infer !== 'onboard') {
const h = HOLD[u.r.id] || (u.n === 2 ? 'config' : null);
const holdTxt = h === 'yes' ? `${esc(u.r.name)} can hold its position while it waits for actions, which a separate policy server requires.`
: h === 'no' ? 'Mobile bases cannot hold position between predictions, so a separate policy server is not supported for LeKiwi: run the policy on the robot or on the PC it is wired to.'
: h === 'config' ? `A separate policy server needs the robot to hold position while waiting; for ${esc(u.name)} it depends on the driver configuration.`
: h === 'sonic' ? 'The G1 supports a separate policy server only with the SONIC controller.'
: `A separate policy server needs the robot driver to declare position hold; check ${esc(u.r.name)} in the ${link('hardware table', D2 + 'integrate_hardware#waiting-between-predictions')}.`;
if (s.infer === 'remote' || h !== 'yes') warn += `
${holdTxt}
`;
if (pk === 'pi05' || pk === 'groot') warn += `
ACT and SmolVLA have run on real robots through a policy server; check ${P.name} in the ${link('policy support table', 'https://github.com/huggingface/lerobot/blob/main/src/lerobot/remote_inference/README.md#policy-support')}.
`;
}
if (pk === 'hilserl') warn += '
HIL-SERL trains while it runs: its learner needs a GPU next to the robot.
';
return `
${items.join('')}
${warn}`;
}
function currentSetups(s, ranked, mine) {
if (cmp) return cmp;
const out = [mine];
for (const x of ranked) {
if (out.length >= 3) break;
if (out.some(c => c.rid === x.u.id) || !x.F.ok) continue;
out.push(defaultSetup(s, x.u));
}
return out;
}
function renderCompare(s, setups) {
const Ms = setups.map(c => metrics(c, s));
$('cmpSub').textContent = `Each column is a complete setup: robot, GPU to train it, computer to run it. Over ${s.years} year${s.years > 1 ? 's' : ''} at ${s.hours} h a day, ${s.days} days a year in ${s.C.name} (${s.C.g} g CO2e/kWh, Ember 2025 generation, $${s.C.usd}/kWh).`;
const runOpts = (sel, m) => Object.keys(MODES).map(mode => ``).join('');
const head = Ms.map((m, i) => `
${rows.join('')}`;
if (Ms.some(m => m.missingRobotPrice)) $('costChart').textContent = 'Enter the missing robot quotes in the Robot step to compare complete lifetime costs. The table shows known costs plus the missing quotes.';
else stacked('costChart', Ms, m => [['Hardware', m.life.hw], ['Training & cloud inference', m.life.train], ['Electricity', m.life.elec]], money);
stacked('co2Chart', Ms, m => [['Manufacturing', m.life.emb], ['Training', m.life.tr], ['Operation', m.life.op]], kg);
$('costTitle').textContent = `Cost over ${s.years} year${s.years > 1 ? 's' : ''}`;
$('co2Title').textContent = `CO2 over ${s.years} year${s.years > 1 ? 's' : ''}`;
$('assume').innerHTML = [
`Fit: rated payload ≥ your heaviest object with gripper (${s.payload} kg), and the gripper reaches at least ${Math.round(REACHED * 100)}% of the work area. Reach comes from each robot’s URDF: joint angles sampled within their limits give, at each height, the nearest and farthest distance from the base axis the gripper can reach (3% margin). Robots without a model use a sphere at 90% of the rated reach.`,
'Usable space: the volume of that reachable region above the mounting surface (×2 for two arms).',
`Energy: (robot typical power + computer power) × ${s.hours} h × ${s.days} days, plus training and any cloud inference GPU. Typical power is the vendor figure where published (UR, UFACTORY, Kinova, Franka, AgileX), a reseller figure for FANUC, and an estimate marked ≈ elsewhere.`,
`Training: RL uses an illustrative 3-hour practice allowance; imitation learning uses the LeRobot guide time for 50 episodes on an A100, divided by each GPU’s relative speed; energy = time × (GPU + host power), × ${CLOUD_PUE} PUE in the cloud. Cloud GPUs (training and inference) use the ${COUNTRIES[CLOUD_GRID].name} grid (${COUNTRIES[CLOUD_GRID].g} g/kWh); local hardware uses ${s.C.name}.`,
`Manufacturing CO2 assumptions: robots ${EMBODIED.robotPerKg} kg CO2e per kg of mass; GPU cards ${EMBODIED.gpuCard} kg; servers ${EMBODIED.server} kg; PCs ${EMBODIED.pc} kg; embedded boards ${EMBODIED.board} kg. These generic factors are not verified product LCAs. Already-owned hardware adds no new manufacturing in this incremental model; its historical footprint is not zero.`,
'Grid provenance: Ember Yearly Electricity Data, 2025 Total generation rows, downloaded 23 October 2026. Lifecycle gCO2e/kWh of generation, held constant across the scenario; not supplier-specific or corporate Scope 2 factors. Source rows and version hash are linked in Sources & limits. US cloud location and PUE remain assumptions, not provider measurements.',
'Hardware cost: robot list or street price, plus the GPU card and a host PC when you would buy one. Integration, grippers, safety and labor are not included.',
].map(t => `
${esc(t)}
`).join('');
}
function optRobots(s, sel) {
const mine = unitsFor(s.task).map(u => u.id);
const groups = [['For this task', mine], ['Other robots', ROBOTS.map(r => r.id).filter(id => !mine.includes(id))]];
return groups.map(([label, ids]) => ``).join('');
}
function stacked(el, Ms, parts, fmt) {
const data = Ms.map(m => parts(m));
const max = Math.max(...data.map(d => d.reduce((a, p) => a + p[1], 0)), 1e-9);
const colors = ['var(--q1)', 'var(--q2)', 'var(--q3)'];
$(el).innerHTML = data.map((d, i) => {
const tot = d.reduce((a, p) => a + p[1], 0);
return `
`;
}).join('');
}
// ---------- step 6: tools and commands
function renderStart(s, M, R, pk) {
$('walkthrough').innerHTML = !pk ? link('Reachy Mini apps', 'https://huggingface.co/reachy-mini') : pk === 'hilserl' ? link('HIL-SERL: rewards, actor and learner', D + 'hilserl') : link('Imitation learning on real robots', D + 'il_robots');
$('startLead').textContent = M.P ? `${M.u.name}, ${M.P.name} trained on ${M.g.name.replace('HF Jobs · ', 'HF Jobs ')}, running ${MODES[s.infer].toLowerCase()} on ${M.b.name}: about ${totalCost(M)} and ${kg(M.life.co2)} CO2e over ${s.years} years.` : `${M.u.name} with Python apps.`;
const T = [];
const add = (n, u, d) => T.push(`
${link(n, u)}${d}
`);
if (s.goal === 'learn' || s.goal === 'research') add('Robot Learning tutorial', 'https://huggingface.co/spaces/lerobot/robot-learning-tutorial', 'Free course from behavioral cloning to VLAs, with runnable LeRobot code.');
if (['so101', 'bi_so101', 'lekiwi'].includes(R.id)) add('LeLab', 'https://huggingface.co/spaces/lerobot/LeLab', 'Calibrate, teleoperate, record and train your SO arm from the browser, no command line.');
if (R.lerobot !== 'native' && R.id !== 'reachymini') add('Bring your own robot', D + 'integrate_hardware', R.lerobot === 'plugin' ? 'A community plugin drives this robot; install it next to LeRobot.' : 'Write a small Robot class (connect, observation, action) to record and run policies on this robot.');
if (R.id !== 'reachymini') {
add(s.data === 'private' ? 'Private datasets on the Hub' : 'Datasets on the Hub', D + 'lerobot-dataset-v3', s.data === 'private' ? 'Record straight to a private repo; only your organization can see it.' : 'Record straight to the Hub and share with the community.');
add('Dataset visualizer', 'https://huggingface.co/spaces/lerobot/visualize_dataset', 'Replay every episode and spot bad demonstrations before training.');
}
if (pk && POLICIES[pk].base) add('Pretrained ' + POLICIES[pk].name, 'https://huggingface.co/' + POLICIES[pk].base, 'Fine-tune instead of training from scratch.');
if (s.variety === 'multi') add('Annotation Studio', 'https://huggingface.co/spaces/lerobot/annotation-studio', 'Label episodes with the language instructions your VLA will follow.');
if (s.variety === 'multi' || s.goal === 'research') add('Community Dataset v3', 'https://huggingface.co/datasets/lerobot/community_dataset_v3', '791 open datasets across 46 robot types for pretraining or co-training.');
if (M.g.loc === 'cloud' && pk) add('Hugging Face Jobs', 'https://huggingface.co/docs/hub/jobs', 'Train on Hub GPUs, billed by the second, straight from lerobot-train.');
if (pk && s.infer !== 'onboard') add('Remote inference', D + 'remote_inference', 'Run the policy on a GPU server while the robot computer keeps cameras and motors.');
if (pk && pk !== 'act' && pk !== 'hilserl') add('Real-Time Chunking', D + 'rtc', 'Keep the robot moving while a large policy computes its next chunk of actions.');
if (pk === 'hilserl') add('HIL-SERL guide', D + 'hilserl', 'Reinforcement learning on the real robot with a reward classifier and human corrections.');
if (s.goal === 'research' || s.task === 'humanoid') add('Simulation with EnvHub', D + 'envhub', 'Evaluate on LIBERO, MetaWorld or IsaacLab Arena scenes before touching hardware.');
if (s.goal === 'production') {
add('Storage Buckets', 'https://huggingface.co/docs/hub/storage-buckets', 'Mutable, S3-compatible storage for fleet logs and checkpoints, kept in LeRobotDataset format.');
add('Streaming training', D + 'training_dataset_streaming', 'Train straight from a dataset or a bucket without downloading it first.');
}
if (s.data === 'private' || s.goal === 'pilot' || s.goal === 'production') add('Enterprise Hub', 'https://huggingface.co/enterprise', 'Private organization, SSO, access control, audit logs and storage region for your robot data and models.');
add('USD & SimReady assets', 'https://huggingface.co/datasets/nvidia/simready-assets', 'Source 3D objects for simulation. This advisor previews geometry; physics and task configuration belong in your simulator.');
add('Back to the companies guide', 'https://huggingface.co/spaces/cetiennec/lerobot-for-companies#where-are-you-starting-from', 'Continue through Explore, Build, Pilot and Scale with your chosen setup.');
add('LeRobot Discord', 'https://discord.gg/q8Dzzpym3f', 'Ask the community and the Hugging Face team.');
$('tools').innerHTML = T.join('');
if (!pk) { $('cmd').textContent = '# Reachy Mini: install the SDK and run an app\n# See https://huggingface.co/reachy-mini for the getting-started guide'; return; }
const ds = '${HF_USER}/my_task', priv = s.data === 'private' ? ' \\\n --dataset.private=true' : '';
const rtype = R.type || '', tele = R.teleop || '';
const task = objects.length ? `Pick up the ${objects[0].name.replace(/ \(.*\)$/, '').toLowerCase()} and place it in the bin` : 'Pick up the part and place it in the bin';
let c = (R.lerobot === 'plugin' ? `# 0. Install the community plugin for ${R.name} (see the third-party robots page)\n\n` : !R.lerobot ? `# 0. LeRobot support for ${R.name} is not verified: validate or implement the Robot interface\n# https://huggingface.co/docs/lerobot/integrate_hardware\n\n` : '') +
`# 1. Record about 50 demonstrations\nlerobot-record \\\n --robot.type=${rtype} \\\n --teleop.type=${tele} \\\n --dataset.repo_id=${ds} \\\n --dataset.single_task="${task}" \\\n --dataset.num_episodes=50${priv}\n\n`;
if (pk === 'hilserl') { $('cmd').textContent = c + '# 2. Follow the HIL-SERL guide: train a reward classifier,\n# then run the actor and learner with gamepad corrections\n# https://huggingface.co/docs/lerobot/hilserl'; return; }
const job = M.g.loc === 'cloud' ? ` \\\n --job.target=${M.g.job}` : '';
const pol = `\${HF_USER}/${pk}_my_task`;
c += `# 2. Train${job ? ' on Hugging Face Jobs' : ''}\nlerobot-train \\\n ${POLICIES[pk].flag} \\\n --dataset.repo_id=${ds} \\\n --policy.repo_id=${pol}${s.data === 'private' ? ' \\\n --policy.private=true' : ''}${job}\n\n`;
const flow = pk === 'smolvla' || pk === 'pi05';
if (s.infer === 'remote' || (s.infer === 'local' && M.b.id !== 'laptop')) {
const ep = s.infer === 'remote' ? 'tls/:7447' : 'tcp/:7447';
c += `# 3. Run it: start the policy server on the GPU machine\n# (copy examples/remote_inference/server.yaml, set model.repo_or_path=${pol})\nlerobot-policy-server --config_path=server.yaml\n\n` +
`# 4. ...then the robot client, on the computer wired to the robot\nlerobot-rollout \\\n --inference.type=remote \\\n --inference.endpoint=${ep} \\\n --inference.deployment=manipulation \\\n --inference.mode=chunk \\\n --inference.chunk_merge=aligned \\\n --inference.semantics=${s.infer === 'remote' ? ' \\\n --inference.encoding=jpeg \\\n --inference.jpeg_quality=90' : ''} \\\n --robot.type=${rtype} \\\n --task="${task}" \\\n --interactive=true` +
(s.infer === 'local' ? `\n\n# If the GPU is in the PC wired to the robot, skip the server:\n# lerobot-rollout --strategy.type=base --policy.path=${pol} --robot.type=${rtype}${flow ? ' --inference.type=rtc' : ''}` : '');
} else {
c += `# 3. Run it ${s.infer === 'onboard' ? 'on the robot’s board' : 'on the computer wired to the robot'}\nlerobot-rollout \\\n --strategy.type=base \\\n --policy.path=${pol} \\\n --robot.type=${rtype} \\\n --task="${task}"${s.infer === 'onboard' ? ' \\\n --device=cuda' : ''}${flow ? ' \\\n --inference.type=rtc' : ''}`;
}
$('cmd').textContent = c;
}
function recommendationText() {
const M = lastRec.M, s = lastRec.s;
return `Robot: ${M.u.name} (${M.u.r.maker})\nPolicy: ${M.P ? M.P.name : 'Python apps'}\nTraining on: ${M.g.name}\nInference: ${MODES[s.infer]}, on ${M.b.name}\n` +
`Over ${s.years} years: cost ${totalCost(M)}, CO2 ${kg(M.life.co2)}, power at the robot ${num(M.powerW)} W\nHugging Face tools: ${Array.from(document.querySelectorAll('#tools li b')).map(b => b.textContent).join('; ')}`;
}
// ---------- objects the robot handles: SimReady assets from the Hub, your own 3D files, or a size
let objects = []; // {uid, name, size:[x,y,z] m, kg, thumb, glb, src, est}
let objSeq = 0, objShown = 30;
const hasCatalog = typeof OBJECTS !== 'undefined';
const thumbUrl = p => `${OBJECTS_SOURCE}/resolve/main/${p.split('/').map(encodeURIComponent).join('/')}`;
const gripKg = kg => kg < 1 ? 0.1 : 0.5;
const cm = m => Math.max(1, Math.round(m * 100));
const sizeTxt = s => `${cm(s[0])}×${cm(s[1])}×${cm(s[2])} cm`;
function addObject(o) {
objects.push({uid:'o' + (++objSeq), ...o});
syncObjects();
}
window.advisorAddObject = addObject;
window.advisorObjectMsg = t => { $('objMsg').textContent = t; };
// The payload and the work area follow the objects: heaviest object plus a gripper, and a work area that holds them.
function syncObjects() {
if (objects.length) {
const heavy = Math.max(...objects.map(o => o.kg));
const i = PAYLOADS.findIndex(p => p >= heavy + gripKg(heavy));
$('payload').value = i < 0 ? PAYLOADS.length - 1 : i;
const need = {wsW:Math.max(...objects.map(o => o.size[1])) + 0.1, wsD:Math.max(...objects.map(o => o.size[0])) + 0.1, wsH:Math.max(...objects.map(o => o.size[2])) + 0.05};
let grew = false;
Object.entries(need).forEach(([id, m]) => { const v = Math.ceil(m * 20) * 5; if (v > +$(id).value) { $(id).value = Math.min(v, +$(id).max); grew = true; } });
if (grew) document.querySelectorAll('input[name=ws]').forEach(r => r.checked = false);
}
cmp = null;
if (!pick.rid) view = null;
renderObjects();
render();
}
function renderObjects() {
$('objList').innerHTML = objects.map((o, i) => `
`).join('');
const heavy = objects.length ? Math.max(...objects.map(o => o.kg)) : null;
$('payloadHint').textContent = heavy != null ? `Heaviest object ${num(heavy, heavy < 1 ? 2 : 1)} kg + about ${gripKg(heavy)} kg of gripper, rounded up.` : 'Heaviest object with the gripper. Add your objects above and it is set for you.';
}
// Where the objects sit in the work area for the 3D view: rows across the width.
function placeObjects(s) {
const out = [], y0 = -s.ws.w / 2 + 0.03;
let y = y0, x = s.ws.g + 0.03, depth = 0;
objects.forEach(o => {
if (y + o.size[1] > s.ws.w / 2 && y > y0) { y = y0; x += depth + 0.03; depth = 0; }
out.push({uid:o.uid, src:o.src, glb:o.glb || null, size:o.size, x:x + o.size[0] / 2, y:y + o.size[1] / 2});
y += o.size[1] + 0.03; depth = Math.max(depth, o.size[0]);
});
return out;
}
function objMatches(q) {
const words = q.toLowerCase().split(/\s+/).filter(Boolean);
return OBJECTS.filter(o => { const t = `${o.name} ${o.cls || ''} ${o.doc} ${o.id}`.toLowerCase(); return words.every(w => t.includes(w)); });
}
function renderObjGrid() {
const list = objMatches($('objQuery').value);
$('objDlgSub').innerHTML = `${list.length} of ${OBJECTS.length} objects a robot arm can lift, from ${link('nvidia/simready-assets', OBJECTS_SOURCE)} (SimReady Central, CC-BY-4.0). Size and mass come from each asset’s physics data; masses are often computed for a solid object, so check them against yours.`;
$('objGrid').innerHTML = list.slice(0, objShown).map(o => ``).join('') || '
No object matches.
';
$('objMore').hidden = list.length <= objShown;
}
document.addEventListener('click', e => {
const t = e.target.closest('[data-oadd],[data-orm],#objBrowse,#objUpload,#objManual,#objMore,#objDlgClose');
if (!t) return;
if (t.dataset.oadd) {
const o = OBJECTS.find(x => x.id === t.dataset.oadd);
$('objDlg').close();
addObject({name:o.name, size:o.size, kg:o.kg, thumb:o.thumb, glb:`objects/${o.id}.glb`, src:'simready', est:'simready', hub:`${OBJECTS_SOURCE}/tree/main/${o.id}`});
} else if (t.dataset.orm) { objects.splice(+t.dataset.orm, 1); syncObjects(); }
else if (t.id === 'objBrowse') { objShown = 30; renderObjGrid(); $('objDlg').showModal(); $('objQuery').focus(); }
else if (t.id === 'objUpload') $('objFile').click();
else if (t.id === 'objManual') addObject({name:'My object', size:[0.1, 0.1, 0.1], kg:0.5, src:'manual', est:true});
else if (t.id === 'objMore') { objShown += 30; renderObjGrid(); }
else if (t.id === 'objDlgClose') $('objDlg').close();
});
$('objList').addEventListener('change', e => {
const o = objects[+e.target.dataset.oi];
if (o && +e.target.value > 0) { o.kg = +e.target.value; o.est = false; syncObjects(); }
});
$('objQuery').addEventListener('input', () => { objShown = 30; renderObjGrid(); });
if (!hasCatalog) { $('objBrowse').disabled = true; $('objBrowse').title = 'The object catalog is not available'; }
// ---------- navigation and events
function go(name) {
step = STEPS.includes(name) ? name : 'project';
STEPS.forEach(n => $('step-' + n).classList.toggle('on', n === step));
document.querySelectorAll('nav.steps button').forEach(b => { if (b.dataset.go === step) b.setAttribute('aria-current', 'step'); else b.removeAttribute('aria-current'); });
if (location.hash !== '#' + step) history.replaceState(null, '', '#' + step);
window.dispatchEvent(new CustomEvent('advisor:step', {detail:step}));
}
function editCmp(fn) {
const s = readState();
if (!cmp) { const r = lastRec; cmp = currentSetups(s, rankUnits(s), {rid:r.u.id, gid:r.M.g.id, bid:r.M.b.id}).map(c => ({...c})); }
fn(cmp, s);
render();
}
document.addEventListener('click', e => {
const t = e.target.closest('[data-go],[data-view],[data-choose],[data-add],[data-rm],[data-gpu],[data-run],[data-view3d],#addSetup,#resetCmp');
if (!t) return;
if (t.dataset.go) { go(t.dataset.go); window.scrollTo({top:0, behavior:'smooth'}); return; }
if (t.dataset.view) { const fromCatalog = !!t.closest('#rtable'); view = t.dataset.view; render(); if (fromCatalog) $('viewer').scrollIntoView({block:'start', behavior:'smooth'}); return; }
if (t.dataset.view3d) { view = t.dataset.view3d; render(); go('robot'); window.scrollTo({top:0}); return; }
if (t.dataset.choose) { pick.rid = t.dataset.choose; pick.bid = null; cmp = null; render(); return; }
if (t.dataset.add) { editCmp((c, s) => { if (c.length < 4 && !c.some(x => x.rid === t.dataset.add)) c.push(defaultSetup(s, unit(t.dataset.add))); }); return; }
if (t.dataset.rm) { editCmp(c => c.splice(+t.dataset.rm, 1)); return; }
if (t.dataset.gpu) { if (lastRec.P && training(byId(GPUS, t.dataset.gpu), lastRec.P, lastRec.s).fit === 'no') return; pick.gid = t.dataset.gpu; cmp = null; render(); return; }
if (t.dataset.run) { pick.bid = t.dataset.run; cmp = null; render(); return; }
if (t.id === 'addSetup') editCmp((c, s) => { const next = rankUnits(s).find(x => !c.some(y => y.rid === x.u.id)); if (next) c.push(defaultSetup(s, next.u)); });
if (t.id === 'resetCmp') { cmp = null; render(); }
});
document.addEventListener('keydown', e => {
const tr = e.target.closest && e.target.closest('tr[data-gpu],tr[data-run],tr[data-view]');
if (tr && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); tr.click(); }
});
$('cmp').addEventListener('change', e => {
const sel = e.target.closest('select[data-i]');
if (!sel) return;
editCmp((c, s) => {
const i = +sel.dataset.i;
if (sel.dataset.k === 'rid') c[i] = {...defaultSetup(s, unit(sel.value)), gid:c[i].gid};
else c[i][sel.dataset.k] = sel.value;
});
});
const tip = $('tip');
function showTip(el, x, y) {
const [v, l] = el.dataset.tip.split('|');
tip.innerHTML = '';
const b = document.createElement('b'); b.textContent = v; tip.append(b, document.createTextNode(l));
tip.style.display = 'block';
tip.style.left = Math.min(x + 12, innerWidth - tip.offsetWidth - 8) + 'px';
tip.style.top = (y - tip.offsetHeight - 10) + 'px';
}
document.addEventListener('pointermove', e => { const el = e.target.closest && e.target.closest('[data-tip]'); if (el) showTip(el, e.clientX, e.clientY); else tip.style.display = 'none'; });
document.addEventListener('focusin', e => { const el = e.target.closest('[data-tip]'); if (el) { const r = el.getBoundingClientRect(); showTip(el, r.left + r.width / 2, r.top); } });
document.addEventListener('focusout', () => tip.style.display = 'none');
function setWorkspace(v) {
const [w, d, h, g] = v.split(',');
$('wsW').value = w; $('wsD').value = d; $('wsH').value = h; $('wsG').value = g;
}
$('f').addEventListener('input', e => {
if (e.target.closest('#cmp, #viewer')) return;
if (e.target.dataset.quote) return;
if (e.target.dataset.oi) return; // masses apply on change, below
const n = e.target.name || e.target.id;
if (n === 'ws') setWorkspace(e.target.value);
if (['wsW', 'wsD', 'wsH', 'wsG'].includes(n)) document.querySelectorAll('input[name=ws]').forEach(r => r.checked = false);
if (['task', 'budget', 'own'].includes(n)) resetPicks();
if (['compute', 'learning', 'variety'].includes(n)) { pick.gid = null; cmp = null; }
if (n === 'learning') pick.bid = null;
if (n === 'infer') pick.bid = null;
if (['task', 'payload', 'wsW', 'wsD', 'wsH', 'wsG', 'ws', 'budget', 'own', 'prio', 'infer', 'compute'].includes(n)) cmp = null;
if (['payload', 'ws', 'budget', 'prio'].includes(n) && !pick.rid) view = null; // follow the new suggestion
render();
});
$('theme').addEventListener('click', () => {
const dark = document.documentElement.dataset.theme ? document.documentElement.dataset.theme === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches;
document.documentElement.dataset.theme = dark ? 'light' : 'dark';
try { localStorage.setItem('advisor-theme', document.documentElement.dataset.theme); } catch (e) {}
window.dispatchEvent(new CustomEvent('advisor:theme'));
});
window.addEventListener('hashchange', () => go(location.hash.slice(1)));
function startFrom(entry) {
const presets = {explore:{goal:'learn', budget:'low', data:'open'}, existing:{goal:'prototype', budget:'own', data:'private'}, assets:{goal:'research', budget:'high', data:'private'}, pilot:{goal:'pilot', budget:'high', data:'private'}};
if (!Object.hasOwn(presets, entry)) return;
for (const [name, value] of Object.entries(presets[entry])) document.querySelector(`input[name="${name}"][value="${value}"]`).checked = true;
resetPicks(); render(); go('robot');
const notes = {explore:'Explore · Set your payload and workspace, then compare affordable robots across manufacturers.', existing:'Build · Pick your robot under “I have one”. The catalog includes vendor robots that need a LeRobot adapter.', assets:'Simulation & assets · Add a SimReady object or preview a supported export. Keep your original USD stage for your simulator.', pilot:'Pilot · Start with payload, work area and an industrial robot. Data is set to private; refine the training and deployment steps next.'};
$('entryNote').firstChild.textContent = notes[entry] + ' ';
$('assetGuide').open = entry === 'assets';
const params = new URLSearchParams(location.search); params.set('entry', entry);
history.replaceState(null, '', location.pathname + '?' + params + '#robot');
if (entry === 'existing') $('own').focus();
else $('h-robot').scrollIntoView({block:'start'});
}
$('browseRobotCatalog').addEventListener('click', () => $('robotCatalog').scrollIntoView({block:'start', behavior:'smooth'}));
document.querySelectorAll('[data-entry]').forEach(b => b.addEventListener('click', () => startFrom(b.dataset.entry)));
$('resetRobotFilters').addEventListener('click', () => {
$('robotQuery').value = ''; $('robotMaker').value = ''; $('robotSupport').value = ''; $('robotFits').checked = false; render();
});
function applyQuote() {
const input = $('robotQuote');
if (!input || !input.reportValidity()) return;
const value = input.valueAsNumber;
if (Number.isFinite(value) && value > 0) robotQuotes[input.dataset.quote] = value;
else delete robotQuotes[input.dataset.quote];
render();
}
document.addEventListener('click', e => { if (e.target.closest('#applyQuote')) applyQuote(); });
document.addEventListener('keydown', e => {
if (e.target.dataset.quote && e.key === 'Enter') { e.preventDefault(); applyQuote(); }
});
(function init() {
const learning = new URLSearchParams(location.search).get('learning');
if (['imitation', 'rl'].includes(learning)) document.querySelector('input[name=learning][value=' + learning + ']').checked = true;
try { const t = localStorage.getItem('advisor-theme'); if (t) document.documentElement.dataset.theme = t; } catch (e) {}
$('country').innerHTML = Object.entries(COUNTRIES).map(([k, c]) => ``).join('');
$('robotMaker').innerHTML += [...new Set(ROBOTS.map(r => r.maker))].sort().map(m => ``).join('');
$('own').innerHTML = '' + ROBOTS.map(r => ``).join('');
setWorkspace(document.querySelector('input[name=ws]:checked').value);
renderObjects();
render();
const entry = new URLSearchParams(location.search).get('entry');
if (['explore', 'existing', 'assets', 'pilot'].includes(entry)) startFrom(entry);
else go(location.hash.slice(1) || 'project');
})();
$('downloadPdf').addEventListener('click', async () => {
const button = $('downloadPdf'), status = $('pdfStatus');
button.disabled = true; status.textContent = 'Preparing your PDF…';
try {
if (!window.jspdf || !window.AdvisorPdf) throw new Error('PDF library unavailable');
const report = pdfReport(lastRec.s, lastRec.M);
const doc = window.AdvisorPdf.create(report, window.jspdf.jsPDF);
const slug = lastRec.u.id.replace(/[^a-z0-9-]/gi, '-');
const date = new Date().toISOString().slice(0, 10);
await doc.save(`robot-setup-${slug}-${date}.pdf`, {returnPromise:true});
status.textContent = 'PDF ready. Check your browser’s downloads.';
} catch (error) {
status.textContent = 'The PDF could not be created. Reload the page and try again.';
console.error('PDF export failed:', error);
} finally { button.disabled = false; }
});