Spaces:
Running

OpenPELS / simulator_bridge.js
Elvis0001's picture
Integrate qualified 2:1 SP-SC topology in local OpenPELS
e3a78d8
Raw History Blame
12 kB
/* Same-origin asynchronous jobs, while retaining the original XFLY controls. */
async function openpelsSimulationFetch(path, options) {
const kind = path.endsWith("sweep-case") ? "sweep-case" : "run";
const response = await fetch("/api/simulation/jobs", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ kind, payload: JSON.parse(options.body) }),
});
if (!response.ok) return response;
const submitted = await response.json();
const started = Date.now();
// Include queue and post-processing time rather than abandoning a valid job.
while (Date.now() - started < 30 * 60 * 1000) {
await new Promise((resolve) => setTimeout(resolve, 500));
const poll = await fetch("/api/simulation/jobs/" + submitted.id, {
cache: "no-store",
signal: AbortSignal.timeout(15000),
});
if (!poll.ok) return poll;
const job = await poll.json();
if (job.state === "succeeded")
return new Response(JSON.stringify(job.result), {
status: 200,
headers: { "Content-Type": "application/json" },
});
if (job.state === "failed")
return new Response(JSON.stringify({ error: job.error }), {
status: 422,
headers: { "Content-Type": "application/json" },
});
}
return new Response(
JSON.stringify({ error: "The simulation did not finish in time." }),
{ status: 504 },
);
}
function openpelsRenderArtifacts(result) {
const target = document.getElementById("runArtifacts");
target.replaceChildren();
for (const artifact of result.artifacts ?? []) {
const url = new URL(artifact.url, location.href);
if (
url.origin !== location.origin ||
!url.pathname.startsWith("/simulator/runs/")
)
continue;
const link = document.createElement("a");
link.href = url.href;
link.textContent = "↓ " + artifact.name;
link.download = artifact.name;
target.append(link);
}
target.style.display = target.childElementCount ? "flex" : "none";
}
window.addEventListener("DOMContentLoaded", () => {
const select = document.getElementById("topologySelect");
const frequency = document.getElementById("frequency");
const frequencies = { xfly6s: 100, xfly8s: 50, c3l: 50, sp2: 2 };
const spec = JSON.parse(document.getElementById("sp2-contract").textContent);
const fixture = spec.request;
const form = document.getElementById("controls");
const parameter = document.getElementById("sp2-parameter");
const point = document.getElementById("sp2-point");
const sweepControl = document.getElementById("sp2-include-sweep");
const sp2Settings = document.getElementById("sp2-settings");
const sp2Result = document.createElement("dl");
sp2Result.id = "sp2-result";
sp2Result.hidden = true;
const sp2Sweep = document.createElement("section");
sp2Sweep.id = "sp2-sweep-results";
sp2Sweep.hidden = true;
document.getElementById("plotWrap").after(sp2Result, sp2Sweep);
for (const [id, axis] of Object.entries(spec.axes))
parameter.add(new Option(axis.label, id));
function loadPoint(iout) {
return spec.axes.load.points.find(([, value]) => Math.abs(value - iout) <= 1e-7);
}
function fillPoints(selected = "nominal") {
const axis = spec.axes[parameter.value];
point.replaceChildren(...axis.points.map(([id, value]) =>
new Option(`${value} ${axis.unit}${id === "nominal" ? " (nominal)" : ""}`, id)));
point.value = selected;
showSettings();
}
function showSettings() {
const p = {
fs: spec.fixed_parameters.fs_hz / 1e6,
cf: spec.fixed_parameters.cf_f_per_flying_cap * 1e6,
esr: spec.fixed_parameters.esr_ohm_per_flying_cap * 1e3,
rs: spec.fixed_parameters.ron_ohm_per_switch * 1e3,
load: fixture.output_current_a,
};
p[parameter.value] = Object.fromEntries(spec.axes[parameter.value].points)[point.value];
sp2Settings.textContent =
`${p.fs} MHz · ${p.cf} µF per flying cap · ${p.esr} mΩ ESR · ${p.rs} mΩ per switch · ${p.load} A load`;
return p;
}
parameter.addEventListener("change", () => {
fillPoints();
reportPoint();
});
point.addEventListener("change", () => {
showSettings();
reportPoint();
});
fillPoints();
function artifactImage(path, alt) {
const url = new URL(path, location.href);
if (url.origin !== location.origin || !url.pathname.startsWith("/simulator/runs/"))
throw new Error("Invalid simulator artifact URL.");
const image = document.createElement("img");
image.src = url.href;
image.alt = alt;
image.style.maxWidth = "100%";
return image;
}
function showMeasurements(m) {
sp2Result.replaceChildren();
for (const [label, value] of [
["Delivered output", `${m.vout_v.toFixed(5)} V at ${m.iout_a.toFixed(5)} A`],
["Output ripple", `${(1000*m.ripple_vpp).toFixed(3)} mV peak-to-peak`],
["Input / delivered power", `${m.input_w.toFixed(5)} / ${m.delivered_w.toFixed(5)} W`],
["Stage loss", `${(1000*m.stage_w).toFixed(3)} mW`],
["Supplemental gate estimate", `${(1000*m.supplemental_gate_w).toFixed(3)} mW`],
["Efficiency with gate estimate", `${(100*m.efficiency_with_gate).toFixed(3)} %`],
["R from stage loss / voltage droop",
`${(1000*m.resistance_power_ohm).toFixed(3)} / ${(1000*m.resistance_droop_ohm).toFixed(3)} mΩ`],
]) {
const term = document.createElement("dt"), description = document.createElement("dd");
term.textContent = label;
description.textContent = value;
sp2Result.append(term, description);
}
sp2Result.hidden = false;
}
function showSweep(run) {
const title = document.createElement("h3");
title.textContent = `${run.parameter.label} sweep`;
const table = document.createElement("table");
const header = table.createTHead().insertRow();
for (const label of [`Value (${run.parameter.unit})`, "Delivered Vout (V)",
"Stage loss (mW)", "Efficiency incl. modeled gate (%)"]) {
const th = document.createElement("th");
th.scope = "col";
th.textContent = label;
header.append(th);
}
const body = table.createTBody();
for (const m of run.sweep) {
const row = body.insertRow();
for (const value of [m.value,m.vout_v.toFixed(5),(1000*m.stage_w).toFixed(3),
(100*m.efficiency_with_gate).toFixed(3)])
row.insertCell().textContent = value;
}
sp2Sweep.replaceChildren(title,
artifactImage(run.sweep_plot_url, title.textContent + " efficiency plot"), table);
sp2Sweep.hidden = false;
}
form.addEventListener("submit", async (event) => {
if (select.value !== "sp2") return;
event.preventDefault();
event.stopImmediatePropagation();
const button = document.getElementById("runButton");
if (button.disabled) return;
const status = document.getElementById("status");
const plot = document.getElementById("plotWrap");
const settings = showSettings();
const request = {
...fixture, output_current_a: settings.load, parameter: parameter.value,
point: point.value, sweep: sweepControl.checked ? "on" : "off",
};
const controls = [select, button, parameter, point, sweepControl];
controls.forEach((control) => { control.disabled = true; });
sp2Result.hidden = sp2Sweep.hidden = true;
plot.replaceChildren();
openpelsRenderArtifacts({ artifacts: [] });
status.textContent = request.sweep === "on" ? "Running the three-point SP-SC sweep…" : "Running SP-SC…";
try {
const response = await openpelsSimulationFetch("/api/run", {body: JSON.stringify(request)});
const run = await response.json();
if (!response.ok) throw new Error(run.error);
plot.replaceChildren(artifactImage(run.plot_url, "SP-SC gate, flying-capacitor and output waveforms"));
showMeasurements(run.metrics[0]);
if (run.sweep.length) showSweep(run);
status.textContent = `Run ${run.run_id}${run.sweep.length ? " · sweep complete" : ""}`;
openpelsRenderArtifacts(run);
} catch (error) {
status.textContent = error.message;
} finally {
controls.forEach((control) => { control.disabled = false; });
}
}, true);
let previous = select.value;
function updateTopology() {
frequencies[previous] = frequency.value;
previous = select.value;
frequency.value = frequencies[previous];
form.classList.toggle("sp2-fixed", previous === "sp2");
document.getElementById("sp2-fixture-info").hidden = previous !== "sp2";
sp2Result.hidden = sp2Sweep.hidden = true;
document.querySelectorAll(".topology-card").forEach((card) => {
card.hidden = card.dataset.topology !== select.value;
});
document.getElementById("metricsTable").hidden = true;
document.querySelector("#metricsTable tbody").replaceChildren();
document
.querySelectorAll("#summaryMetrics .metric span")
.forEach((span) => (span.textContent = "-"));
document.getElementById("plotWrap").textContent =
"Run a simulation to show waveforms.";
document.getElementById("status").textContent = "Ready";
openpelsRenderArtifacts({ artifacts: [] });
resetSweep();
document.getElementById("sweepStatus").textContent =
"Optional · enable in the controls before running.";
}
function reportPoint() {
if (pendingReference || select.disabled) return;
parent.postMessage(
{
type: "pe:simulation-point",
topology: select.value,
vout: select.value === "sp2" ? fixture.target_vout : Number(document.getElementById("targetVout").value),
iout: select.value === "sp2" ? showSettings().load : Number(document.getElementById("iout").value),
},
location.origin,
);
}
select.addEventListener("change", () => {
updateTopology();
reportPoint();
});
document.getElementById("targetVout").addEventListener("input", reportPoint);
document.getElementById("iout").addEventListener("input", reportPoint);
let pendingReference = null;
function applyReference() {
if (!pendingReference || select.disabled) return;
const next = pendingReference;
pendingReference = null;
select.value = next.topology;
updateTopology();
if (next.topology === "sp2") {
const [load] = loadPoint(next.iout);
if (load !== "nominal" || showSettings().load !== next.iout) {
parameter.value = "load";
fillPoints(load);
}
} else {
document.getElementById("targetVout").value = next.vout;
document.getElementById("iout").value = next.iout;
document.getElementById("vin").value = next.ratio * next.vout;
updateLabels();
}
parent.postMessage(
{
type: "pe:reference-applied",
topology: next.topology,
ratio: next.ratio,
vout: next.vout,
iout: next.iout,
},
location.origin,
);
}
window.addEventListener("message", (event) => {
if (
event.origin !== location.origin ||
event.source !== parent ||
event.data?.type !== "pe:select-topology"
)
return;
const next = event.data;
if (
!Object.hasOwn(frequencies, next.topology) ||
(next.topology === "sp2"
? next.ratio !== 2 || !Number.isFinite(next.vout) || !Number.isFinite(next.iout) ||
Math.abs(next.vout-fixture.target_vout) > 1e-7 ||
!loadPoint(next.iout)
: next.ratio !== 4 || !Number.isFinite(next.vout) ||
next.vout < 0.3 || next.vout > 1.1 || !Number.isFinite(next.iout) ||
next.iout < 0.1 || next.iout > 40)
)
return;
pendingReference = next;
if (select.disabled)
parent.postMessage({ type: "pe:simulator-busy" }, location.origin);
applyReference();
});
new MutationObserver(applyReference).observe(select, {
attributes: true,
attributeFilter: ["disabled"],
});
updateTopology();
parent.postMessage({ type: "pe:simulator-ready" }, location.origin);
});