Spaces:
Running
Running
Download simulator_bridge.js from minjiechen/OpenPELS: direct link, hf CLI and curl.
- Browser
- Download file 29.3 kB
-
https://huggingface.co/spaces/minjiechen/OpenPELS/resolve/main/simulator_bridge.js
- Command line
-
hf download hf://spaces/minjiechen/OpenPELS/simulator_bridge.js
-
curl -L -o simulator_bridge.js https://huggingface.co/spaces/minjiechen/OpenPELS/resolve/main/simulator_bridge.js
29.3 kB
| /* Same-origin asynchronous jobs, while retaining the original XFLY controls. */ | |
| async function openpelsSimulationFetch(path, options, onProgress = () => {}) { | |
| 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.progress) onProgress(job.progress); | |
| 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, rsc2: 2, si2: 2, buck_stacked: 2 }; | |
| topologyLabels.sp2 = "2:1 series-parallel SC"; | |
| topologyLabels.rsc2 = "2:1 resonant SC"; | |
| topologyLabels.si2 = "2:1 switched inductor"; | |
| topologyLabels.buck_stacked = "2:1 Buck_Stacked"; | |
| const metricsTable = document.getElementById("metricsTable"); | |
| const originalHeader = metricsTable.tHead.rows[0].cloneNode(true); | |
| const summary = document.getElementById("summaryMetrics"); | |
| const originalSummary = summary.innerHTML; | |
| const presets = JSON.parse(document.getElementById("sp2-contract").textContent); | |
| const conditions=OpenPELSOperatingPoint.configure(JSON.parse(document.getElementById("operating-conditions").textContent)); | |
| const registered=Object.fromEntries(Object.entries(conditions.topologies) | |
| .filter(([,entry])=>entry.simulator).map(([id,entry])=>[entry.simulator.id,{id,...entry}])); | |
| let spec, parameters, capabilities; | |
| const form = document.getElementById("controls"); | |
| const parameter = document.getElementById("sp2-parameter"); | |
| const sweepBox = document.getElementById("sp2-sweep-controls"); | |
| const sweepStart = document.getElementById("sp2-sweep-start"); | |
| const sweepStop = document.getElementById("sp2-sweep-stop"); | |
| const sweepCount = document.getElementById("sp2-sweep-count"); | |
| 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 validationStatus = document.createElement("p"); | |
| validationStatus.id = "sp2-validation"; | |
| validationStatus.setAttribute("role", "status"); | |
| validationStatus.hidden = true; | |
| const sp2Sweep = document.createElement("section"); | |
| sp2Sweep.id = "sp2-sweep-results"; | |
| sp2Sweep.hidden = true; | |
| document.getElementById("plotWrap").after(validationStatus, sp2Result); | |
| const inputHost = document.getElementById("sp2-controls"); | |
| const inputs = new Map(); | |
| let modeSelect; | |
| const savedControls = new Map(); | |
| const note = document.getElementById('fixed-model-note'); | |
| const originalNote = note.textContent; | |
| const within = (axis, value, topology = select.value) => { | |
| const range = presets[topology]?.parameters[axis]; | |
| return range && (value === null ? range.optional : Number.isFinite(value) && value >= range.minimum && value <= range.maximum); | |
| }; | |
| function renderFixedControls(next) { | |
| if (spec?.id === next) return; | |
| if (spec) savedControls.set(spec.id, { | |
| fields: Object.fromEntries([...inputs].map(([id,input]) => [id,input.value])), | |
| mode: modeSelect?.value, axis: parameter.value, start: sweepStart.value, stop: sweepStop.value, | |
| count: sweepCount.value, include: sweepControl.checked, | |
| }); | |
| spec = presets[next]; | |
| parameters = spec.parameters; | |
| capabilities=registered[next]; | |
| const prior = savedControls.get(next); | |
| inputs.clear(); | |
| parameter.replaceChildren(); | |
| inputHost.replaceChildren(); | |
| modeSelect = null; | |
| if (capabilities.simulator.axes) { | |
| modeSelect = document.createElement("select"); | |
| modeSelect.id = "sp2-voltage-mode"; | |
| for (const mode of capabilities.modes) | |
| modeSelect.add(new Option(conditions.modes[mode].label,mode)); | |
| modeSelect.value = prior?.mode ?? capabilities.default_mode; | |
| const label = document.createElement("label"); | |
| label.htmlFor = modeSelect.id; | |
| label.textContent = "Voltage operating mode"; | |
| const field = document.createElement("div"); | |
| field.className = "control"; | |
| field.append(label,modeSelect); | |
| inputHost.append(field); | |
| modeSelect.addEventListener("change", () => { | |
| showOperatingMode(); | |
| refreshPoint(); | |
| settingsChanged(); | |
| reportPoint(); | |
| }); | |
| } | |
| for (const [id, entry] of Object.entries(parameters)) { | |
| const field = document.createElement("div"); | |
| field.className = "control"; | |
| const label = document.createElement("label"); | |
| label.htmlFor = "sp2-" + id; | |
| label.textContent = entry.unit ? entry.label + " (" + entry.unit + ")" : entry.label; | |
| const input = document.createElement("input"); | |
| Object.assign(input, {id: label.htmlFor, type: "number", step: "any", | |
| min: entry.minimum, max: entry.maximum, required: !entry.optional, | |
| value: prior?.fields[id] ?? entry.default ?? ""}); | |
| if (entry.optional) input.placeholder = entry.placeholder ?? "Automatic"; | |
| field.append(label, input); | |
| inputHost.append(field); | |
| inputs.set(id, input); | |
| parameter.add(new Option(label.textContent, id)); | |
| input.addEventListener("input", () => { | |
| refreshPoint(); | |
| settingsChanged(); | |
| if (modeSelect || id === "vin" || id === "load") reportPoint(); | |
| }); | |
| } | |
| note.textContent = spec.model_note | |
| ? [spec.model_note,spec.gate_note,spec.switch_note,spec.domain_note].filter(Boolean).join(' ') | |
| : originalNote; | |
| Object.assign(sweepCount, {min:spec.sweep_points.minimum,max:spec.sweep_points.maximum, | |
| value:prior?.count ?? spec.sweep_points.default,required:true}); | |
| showOperatingMode(prior?.axis ?? "fs"); | |
| if (prior) { | |
| sweepStart.value = prior.start; | |
| sweepStop.value = prior.stop; | |
| } | |
| sweepControl.checked = prior?.include ?? false; | |
| sweepBox.hidden = !sweepControl.checked; | |
| } | |
| function inactiveAxis() { | |
| const axes=capabilities.simulator.axes; | |
| return axes && Object.values(axes).find(axis=>axis!==axes[modeSelect.value]); | |
| } | |
| function showOperatingMode(axis=parameter.value) { | |
| const inactive=inactiveAxis(); | |
| if (modeSelect) { | |
| for (const id of Object.values(capabilities.simulator.axes)) | |
| inputs.get(id).parentElement.hidden=id===inactive; | |
| parameter.replaceChildren(...[...inputs].filter(([id])=>id!==inactive) | |
| .map(([id,input])=>new Option(input.labels[0].textContent,id))); | |
| } | |
| parameter.value=axis===inactive?capabilities.simulator.axes[modeSelect.value]:axis; | |
| if (!parameter.value) parameter.value="fs"; | |
| sweepLimits(); | |
| } | |
| function windingAdapter(number,inputs,channels) { | |
| const high=channels*number("rs")/1000; | |
| return OpenPELSSwitchedInductor.operatingAdapter({ | |
| vin:inputs.input_voltage_v,load:inputs.load.value,fs:inputs.switching_frequency_hz, | |
| winding:number("lt")*1e-9,coupling:number("coupling"),dcr:number("dcr")/1000,high, | |
| low:Number.isFinite(number("rslow"))?channels*number("rslow")/1000:high, | |
| }); | |
| } | |
| const modelAdapters = { | |
| si2:(number,inputs)=>windingAdapter(number,inputs,1), | |
| buck_stacked:(number,inputs)=>windingAdapter(number,inputs,2), | |
| }; | |
| function operation() { | |
| const number=id=>inputs.get(id).valueAsNumber; | |
| const vin=number("vin"), load=number("load"); | |
| const mode=modeSelect?.value??capabilities.default_mode,axes=capabilities.simulator.axes; | |
| const command={mode,input_voltage_v:vin,load:{kind:"current",value:load},switching_frequency_hz:number("fs")*1e6}; | |
| if (axes) command[mode==="output_voltage"?"target_output_v":"duty"]=number(axes[mode]); | |
| const point=OpenPELSOperatingPoint.resolve(capabilities.id,command,modelAdapters[capabilities.id]?.(number,command)); | |
| return {...point,load,vout:point.idealVoltage}; | |
| } | |
| function refreshPoint() { | |
| const output=document.getElementById("sp2-nominal-output"); | |
| try { | |
| const point=operation(); | |
| if (!within("vin",point.vin)) throw Error("Enter an input voltage within the preset bounds."); | |
| output.textContent = modeSelect | |
| ? `${Number(point.idealVoltage.toPrecision(10))} V ideal · Vout = duty × Vin` | |
| : `${Number(point.vout.toPrecision(10))} V at no load · Vout = Vin/${1/point.idealGain}`; | |
| sp2Settings.textContent = point.solver.status==="infeasible" ? point.solver.diagnostics.join(" ") : modeSelect | |
| ? `Command duty ${point.duty.toFixed(6)} · Analytical loaded output ${point.analyticalVoltage.toFixed(5)} V${point.target==null?"":` · Target ${point.target} V`}` | |
| : "The delivered output voltage is measured with the entered load."; | |
| } catch (error) { | |
| output.textContent="—"; | |
| sp2Settings.textContent=modeSelect?error.message:"The delivered output voltage is measured with the entered load."; | |
| } | |
| } | |
| function settingsChanged() { | |
| const status = document.getElementById("status"); | |
| if (status.textContent.startsWith("Run ")) | |
| status.textContent = "Settings changed. Run the simulation to update the displayed results."; | |
| } | |
| function sweepLimits() { | |
| const entry = parameters[parameter.value]; | |
| for (const input of [sweepStart,sweepStop]) | |
| Object.assign(input, {min:entry.minimum,max:entry.maximum,required:true}); | |
| const center = inputs.get(parameter.value).valueAsNumber; | |
| const span = (entry.maximum-entry.minimum)/10; | |
| const defaultSpan = spec.id === "rsc2" && ["fs","cf","lt","esr","dcr","rs"].includes(parameter.value) | |
| ? Math.min(span, Number.isFinite(center) ? center*.08 : span) : span; | |
| const mid = Number.isFinite(center) ? center : (entry.minimum+entry.maximum)/2; | |
| sweepStart.value = Number(Math.max(entry.minimum,mid-defaultSpan/2).toPrecision(10)); | |
| sweepStop.value = Number(Math.min(entry.maximum,mid+defaultSpan/2).toPrecision(10)); | |
| } | |
| parameter.addEventListener("change", () => { | |
| sweepLimits(); | |
| settingsChanged(); | |
| }); | |
| sweepControl.addEventListener("change", () => { | |
| sweepBox.hidden = !sweepControl.checked; | |
| settingsChanged(); | |
| }); | |
| for (const input of [sweepStart,sweepStop,sweepCount]) | |
| input.addEventListener("input", settingsChanged); | |
| const sweepInputs = [parameter,sweepStart,sweepStop,sweepCount]; | |
| 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(run) { | |
| const m = run.metrics[0]; | |
| const incomplete = m.efficiency_includes_coss === false; | |
| const cossNote = incomplete ? " (excl. unknown Coss)" : ""; | |
| const pct = value => `${(100*value).toFixed(3)} %`; | |
| const values = [ | |
| [modeSelect ? "Ideal Vout" : "Nominal Vout", m.nominal_vout_v.toFixed(3) + " V"], | |
| ["Target Iout", run.settings.output_current_a.toFixed(3) + " A"], | |
| ["Modeled efficiency" + cossNote, pct(m.efficiency_with_gate)], | |
| ["Run Time", run.elapsed_s.toFixed(2) + " s"], | |
| ]; | |
| summary.replaceChildren(...values.map(([label,value]) => { | |
| const metric = document.createElement("div"); | |
| metric.className = "metric"; | |
| const name = document.createElement("b"), result = document.createElement("span"); | |
| name.textContent = label; | |
| result.textContent = value; | |
| metric.append(name,result); | |
| return metric; | |
| })); | |
| const header = metricsTable.tHead.rows[0]; | |
| const row = metricsTable.tBodies[0].insertRow(); | |
| header.replaceChildren(); | |
| for (const [label,value] of [ | |
| ["Topology", spec.short ?? "SP-SC"], | |
| ["Command duty", m.duty?.toFixed(3) ?? "0.5 nominal"], | |
| ["Stage efficiency" + cossNote, pct(m.stage_efficiency)], | |
| ["Efficiency incl. gate" + cossNote, pct(m.efficiency_with_gate)], | |
| ["Gate loss (mW)", (1000*m.supplemental_gate_w).toFixed(3)], | |
| ["Vout avg (V)", m.vout_v.toFixed(5)], | |
| ["Iout avg (A)", m.iout_a.toFixed(4)], | |
| ["Iin avg (A)", m.iin_a.toFixed(4)], | |
| ...(["si2","buck_stacked"].includes(spec.id) ? [ | |
| ["Winding RMS (A)", m.winding_rms_a.map(v => v.toFixed(3)).join(" / ")], | |
| ["Winding ripple (A pp)", m.winding_ripple_a.map(v => v.toFixed(3)).join(" / ")], | |
| ["Output capacitor RMS (A)", m.output_cap_rms_a.toFixed(3)], | |
| ] : [ | |
| ["Flying RMS (A)", m.flying_rms_a.map(v => v.toFixed(3)).join(" / ")], | |
| ["Flying avg (V)", m.mean_flying_voltage_v.map(v => v.toFixed(4)).join(" / ")], | |
| ["Flying ripple (mV)", m.flying_ripple_vpp.map(v => (1000*v).toFixed(3)).join(" / ")], | |
| ]), | |
| ]) { | |
| const th = document.createElement("th"); | |
| th.scope = "col"; | |
| th.textContent = label; | |
| header.append(th); | |
| row.insertCell().textContent = value; | |
| } | |
| metricsTable.hidden = false; | |
| sp2Result.replaceChildren(); | |
| for (const [label, value] of [ | |
| [modeSelect ? "Simulated steady-state output" : "Delivered output", `${m.vout_v.toFixed(5)} V at ${m.iout_a.toFixed(5)} A`], | |
| ...(modeSelect ? [ | |
| ...(m.target_vout_v==null ? [] : [ | |
| ["Output target", `${m.target_vout_v.toFixed(5)} V`], | |
| ["Target error", `${(m.target_error_v*1000).toFixed(4)} mV`], | |
| ]), | |
| ["Analytical loaded output", `${m.analytical_vout_v.toFixed(5)} V`], | |
| ["Ideal / analytical / simulated gain", [m.ideal_gain,m.analytical_gain,m.simulated_gain].map(v=>v.toFixed(6)).join(" / ")], | |
| ] : []), | |
| ["Output ripple", `${(1000*m.ripple_vpp).toFixed(3)} mV peak-to-peak`], | |
| ["Input / delivered power" + cossNote, `${m.input_w.toFixed(5)} / ${m.delivered_w.toFixed(5)} W`], | |
| ...(spec.id==="buck_stacked"?[["Effective gate swing / nominal VDS",""+m.gate_drive_v.toFixed(3)+" V"], | |
| ["Measured Coss event loss",incomplete ? "Unknown · excluded" : (1000*m.coss_w).toFixed(3)+" mW"]]:[]), | |
| ["Stage loss" + cossNote, `${(1000*m.stage_w).toFixed(3)} mW`], | |
| [["si2","buck_stacked"].includes(spec.id) ? "MOS terminal / output ESR loss" : "MOS terminal / flying ESR loss", `${(1000*m.switch_w.reduce((a,b) => a+b,0)).toFixed(3)} / ${(1000*m.esr_w.reduce((a,b) => a+b,0)).toFixed(3)} mW`], | |
| ...(m.dcr_w ? [ | |
| ["Inductor DCR loss", `${(1000*m.dcr_w.reduce((a,b) => a+b,0)).toFixed(3)} mW`], | |
| ...(["si2","buck_stacked"].includes(spec.id) ? [ | |
| ["Winding sum / difference ripple", `${m.winding_sum_ripple_a.toFixed(4)} / ${m.winding_delta_ripple_a.toFixed(4)} A peak-to-peak`], | |
| ["Winding current valleys", m.winding_min_a.map(v=>v.toFixed(3)).join(" / ")+" A"], | |
| ["Peak winding voltage", m.winding_voltage_peak_v.map(v=>v.toFixed(3)).join(" / ")+" V"], | |
| ["Peak switch VDS", m.switch_peak_v.map(v=>v.toFixed(3)).join(" / ")+" V"], | |
| ] : [ | |
| ["Commutation current magnitude", `${m.commutation_current_a.toFixed(4)} A`], | |
| ["Tank output sum / difference ripple", `${m.tank_sum_ripple_a.toFixed(4)} / ${m.tank_delta_ripple_a.toFixed(4)} A peak-to-peak`], | |
| ]), | |
| ] : []), | |
| ["Energy balance residual", `${(1e6*m.balance_w).toFixed(2)} µW`], | |
| ["Executed duration / maximum step", `${m.stop_us.toFixed(3)} µs / ${m.max_step_ps.toFixed(3)} ps`], | |
| ["Measurement window", `${Number(m.window_start_cycles.toFixed(3))}–${Number(m.window_stop_cycles.toFixed(3))} cycles`], | |
| ["Supplemental gate estimate", `${(1000*m.supplemental_gate_w).toFixed(3)} mW`], | |
| ["Efficiency with gate estimate" + cossNote, `${(100*m.efficiency_with_gate).toFixed(3)} %`], | |
| ["R from stage loss / voltage droop" + cossNote, | |
| `${(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"); | |
| const stacked = spec.id === "buck_stacked"; | |
| const incomplete = run.sweep.some(row => row.efficiency_includes_coss === false); | |
| title.textContent = `${run.parameter.label} sweep${incomplete ? " · totals exclude unknown Coss where indicated" : ""}`; | |
| const table = document.createElement("table"); | |
| const header = table.createTHead().insertRow(); | |
| for (const label of [`Value (${run.parameter.unit})`, "Delivered Vout (V)", | |
| ...(modeSelect ? ["Duty","Analytical Vout (V)"] : []), | |
| ...(stacked ? ["Coss loss (mW)"] : []), "Stage loss (mW)", "Efficiency incl. modeled gate (%)", "Validation"]) { | |
| 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(); | |
| const metrics = m.status === "failed" ? Array((modeSelect?5:3)+(stacked?1:0)).fill("—") : | |
| [m.vout_v.toFixed(5), ...(modeSelect?[m.duty.toFixed(6),m.analytical_vout_v.toFixed(5)]:[]), ...(stacked?[m.coss_w===null?"Unknown":(1000*m.coss_w).toFixed(3)]:[]), (1000*m.stage_w).toFixed(3), (100*m.efficiency_with_gate).toFixed(3)]; | |
| for (const value of [Number(m.value.toPrecision(10)), ...metrics, | |
| m.message ? m.status + ": " + m.message : m.status]) | |
| row.insertCell().textContent = value; | |
| } | |
| const chart = document.createElement("div"); | |
| chart.className = "sweep-chart"; | |
| chart.append(title, artifactImage(run.sweep_plot_url, title.textContent + " efficiency plot")); | |
| sp2Sweep.replaceChildren(chart, table); | |
| document.getElementById("sweepCharts").replaceChildren(sp2Sweep); | |
| sp2Sweep.hidden = false; | |
| } | |
| form.addEventListener("submit", async (event) => { | |
| if (!presets[select.value]) 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 activeEntries = [...inputs].filter(([id])=>id!==inactiveAxis()); | |
| const activeInputs = [...activeEntries.map(([,input])=>input), ...(sweepControl.checked ? sweepInputs : [])]; | |
| if (activeInputs.some(input => !input.reportValidity())) return; | |
| const request = {topologies: [spec.id]}; | |
| const name = spec.short ?? "SP-SC"; | |
| if (modeSelect) request.voltage_mode=modeSelect.value; | |
| for (const [id,input] of activeEntries) | |
| request[parameters[id].field] = input.value === "" ? null : input.valueAsNumber; | |
| if (sweepControl.checked) { | |
| request.sweep = {axis:parameter.value, start:sweepStart.valueAsNumber, | |
| stop:sweepStop.valueAsNumber, points:sweepCount.valueAsNumber}; | |
| } | |
| const controls = [select,button,sweepControl,...activeInputs,...(modeSelect?[modeSelect]:[])]; | |
| controls.forEach((control) => { control.disabled = true; }); | |
| sp2Result.hidden = sp2Sweep.hidden = validationStatus.hidden = true; | |
| plot.replaceChildren(); | |
| metricsTable.hidden = true; | |
| metricsTable.tBodies[0].replaceChildren(); | |
| summary.querySelectorAll(".metric span").forEach(span => span.textContent = "-"); | |
| resetSweep(); | |
| document.getElementById("sweepStatus").textContent = request.sweep | |
| ? `Waiting for ${name} convergence runs…` : "Sweep disabled for this run."; | |
| openpelsRenderArtifacts({ artifacts: [] }); | |
| status.textContent = request.sweep ? `Running the ${name} operating point and sweep…` : `Running ${name}…`; | |
| const stopProgress = showProgress([spec.id]); | |
| try { | |
| const response = await openpelsSimulationFetch("/api/run", {body: JSON.stringify(request)}, ({complete,total}) => { | |
| if (request.sweep) { | |
| document.getElementById("sweepStatus").textContent = `Sweep running: ${complete} / ${total}`; | |
| document.getElementById("sweepProgressFill").style.width = `${100*complete/total}%`; | |
| } | |
| }); | |
| const run = await response.json(); | |
| if (!response.ok) throw new Error(run.error); | |
| if (run.metrics.length) { | |
| plot.replaceChildren(artifactImage(run.plot_url, `${name} commands, branch currents and output waveforms`)); | |
| showMeasurements(run); | |
| } else { | |
| plot.textContent = "The operating point did not pass validation."; | |
| } | |
| validationStatus.textContent = run.validation_message || "The operating point passed steady-state, energy-balance and convergence checks."; | |
| validationStatus.hidden = false; | |
| if (run.sweep.length) { | |
| showSweep(run); | |
| const passed = run.sweep.filter(row => row.status !== "failed").length; | |
| document.getElementById("sweepStatus").textContent = | |
| "Sweep complete: " + passed + " / " + run.sweep.length + " points passed checks"; | |
| document.getElementById("sweepProgressFill").style.width = "100%"; | |
| } | |
| status.textContent = `Run ${run.run_id}${run.sweep.length ? " · sweep complete" : ""}`; | |
| openpelsRenderArtifacts(run); | |
| } catch (error) { | |
| plot.textContent = "Run a simulation to show waveforms."; | |
| status.textContent = error.message; | |
| if (request.sweep) document.getElementById("sweepStatus").textContent = "Sweep failed. Check the run status."; | |
| } finally { | |
| stopProgress(); | |
| controls.forEach((control) => { control.disabled = false; }); | |
| } | |
| }, true); | |
| let previous = select.value; | |
| function updateTopology() { | |
| frequencies[previous] = frequency.value; | |
| previous = select.value; | |
| frequency.value = frequencies[previous]; | |
| const sp2Active = Object.hasOwn(presets,previous); | |
| if (sp2Active) renderFixedControls(previous); | |
| form.classList.toggle("sp2-fixed", sp2Active); | |
| form.noValidate = sp2Active; | |
| for (const input of [...inputs.values(),...sweepInputs,sweepControl]) | |
| input.disabled = !sp2Active; | |
| if (sp2Active) refreshPoint(); | |
| document.getElementById("sp2-fixture-info").hidden = !sp2Active; | |
| metricsTable.tHead.rows[0].replaceWith(originalHeader.cloneNode(true)); | |
| summary.innerHTML = originalSummary; | |
| sp2Result.hidden = sp2Sweep.hidden = validationStatus.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; | |
| let point; | |
| if (presets[select.value]) { | |
| try { point=operation(); } catch { return; } | |
| if (!within("vin",point.vin) || !within("load",point.load)) return; | |
| } | |
| parent.postMessage( | |
| { | |
| type: "pe:simulation-point", | |
| topology: select.value, | |
| vout: point ? point.vout : Number(document.getElementById("targetVout").value), | |
| iout: point ? point.load : Number(document.getElementById("iout").value), | |
| ...(modeSelect ? {vin:point.vin,voltage_mode:point.mode,duty:point.duty, | |
| target_vout:point.target,analytical_vout:point.analyticalVoltage, | |
| plant:Object.fromEntries(Object.keys(capabilities.simulator.handoff??{}).map(id=>[id,inputs.get(id).valueAsNumber]))} : {}), | |
| ...(point?{operating_point:point}:{}), | |
| ratio:registered[select.value]?.nominal_ratio, | |
| }, | |
| 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 (presets[next.topology]) { | |
| const command=next.operating_point?.inputs; | |
| inputs.get("vin").value = command?.input_voltage_v ?? next.vin ?? | |
| Number((next.vout*capabilities.nominal_ratio).toPrecision(15)); | |
| inputs.get("load").value = command?.load.value ?? next.iout; | |
| if (modeSelect) { | |
| const mode=command?.mode??next.voltage_mode??capabilities.default_mode; | |
| const changed=modeSelect.value!==mode; | |
| modeSelect.value=mode; | |
| const axes=capabilities.simulator.axes; | |
| const duty=command?.duty??next.duty,target=command?.target_output_v??next.target_vout; | |
| if (Number.isFinite(duty)) inputs.get(axes.duty_cycle).value = duty; | |
| if (Number.isFinite(target)) inputs.get(axes.output_voltage).value = target; | |
| for (const [axis,value] of Object.entries(next.plant??{})) | |
| if (within(axis,value)) inputs.get(axis).value=value ?? ""; | |
| if (changed) showOperatingMode(); | |
| } | |
| refreshPoint(); | |
| } 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, | |
| vin: next.vin, | |
| duty: next.duty, | |
| voltage_mode: next.voltage_mode, | |
| target_vout: next.target_vout, | |
| analytical_vout: next.analytical_vout, | |
| plant: next.plant, | |
| operating_point:next.operating_point, | |
| }, | |
| 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) || | |
| (presets[next.topology] | |
| ? next.ratio !== registered[next.topology].nominal_ratio || !Number.isFinite(next.vout) || !Number.isFinite(next.iout) || | |
| !within("vin", next.vin ?? next.vout*registered[next.topology].nominal_ratio, next.topology) || | |
| !within("load", next.iout, next.topology) || | |
| (next.duty != null && !within("duty", next.duty, next.topology)) || | |
| (next.voltage_mode==="output_voltage" && !within("target",next.target_vout,next.topology)) | |
| : 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); | |
| }); | |