import './compare/operating-point.js?v=operating-conditions'; import { createSimulator } from "./simulator.js?v=operating-conditions"; import { createGallery } from "./gallery.js?v=buck-stacked-coss"; import { createAnalysis } from "./analysis.js"; const $ = (s) => document.querySelector(s), $$ = (s) => [...document.querySelectorAll(s)]; const editor = $("#editor"); const STORAGE = "openpels-current-v1"; const PREVIOUS_STORAGE = ["pe", "canvas", "current", "v1"].join("-"); const sentLoads = new Map(); let starters = [], active = null, current = null, baseline = null, ratio = 4, ready = false, selection = 0, acceptedRequestId = 0, pendingLoad = null, migratingStorage = false; function notify(message) { $("#message").textContent = message; $("#message").classList.toggle("visible", !!message); } let selectedTopology = null, selectedRatio = 4, currentView = "gallery"; const conditions=await OpenPELSOperatingPoint.load('./compare/operating-conditions.json'); const fixedPresets = new Map(); const fixedPoints = new Map(Object.entries(conditions.topologies).filter(([,entry])=>entry.defaults) .map(([id,{defaults,law,default_mode}])=>{ const vin=defaults.input_voltage_v,duty=defaults.duty??0; const vout=vin*(law.ideal_gain.constant+law.ideal_gain.duty*duty); return [id,{vout,iout:defaults.load.value,...(default_mode==="fixed_ratio"?{}:{vin,duty,voltage_mode:default_mode})}]; })); const fixedInBounds = (id, axis, value) => { const range = fixedPresets.get(id)?.parameters[axis]; return range && (value === null ? range.optional : Number.isFinite(value) && value >= range.minimum && value <= range.maximum); }; let legacyPoint = { vout: 0.8, iout: 2 }; let operatingPoint = legacyPoint; function selectReference(entry, family) { const prior = selectedTopology?.id; if (prior !== entry.id) { if (fixedPoints.has(prior)) fixedPoints.set(prior,operatingPoint); else legacyPoint = operatingPoint; operatingPoint = fixedPoints.get(entry.id) ?? legacyPoint; } selectedTopology = entry; selectedRatio = family; } const gallery = createGallery({ report: notify, onSelect: (entry, family) => chooseTopology(entry, family), }); const analysis = createAnalysis(notify, (point) => { if ( currentView !== "compare" || point.id !== selectedTopology?.id || point.ratio !== selectedRatio || !Number.isFinite(point.vout) || !Number.isFinite(point.iout) ) return; operatingPoint = { vout: point.vout, iout: point.iout, operating_point:point.operating_point, ...(Number.isFinite(point.vin) ? { vin:point.vin,duty:point.duty,voltage_mode:point.voltage_mode,target_vout:point.target_vout, analytical_vout:point.analytical_vout,plant:point.plant } : {}) }; renderSelection(); }); const simulator = createSimulator(notify, (topology, point) => { if (currentView !== "simulator") return; const entry = gallery.forSimulator(topology); if (entry) { selectReference(entry, point.ratio); if ( Number.isFinite(point.vout) && Number.isFinite(point.iout) && point.vout > 0 && point.iout > 0 ) operatingPoint = { vout: point.vout, iout: point.iout, operating_point:point.operating_point, ...(Number.isFinite(point.vin) ? { vin:point.vin,duty:point.duty,voltage_mode:point.voltage_mode,target_vout:point.target_vout, analytical_vout:point.analytical_vout,plant:point.plant } : {}) }; gallery.highlight(entry.id); renderSelection(); } }); function simulationAvailable() { const id = selectedTopology?.simulator; if (fixedPoints.has(id)) return selectedRatio === conditions.topologies[id].nominal_ratio && fixedInBounds(id,"vin",operatingPoint.vin??operatingPoint.vout*selectedRatio) && fixedInBounds(id,"load",operatingPoint.iout) && (conditions.topologies[id].default_mode==="fixed_ratio" || (fixedInBounds(id,"duty",operatingPoint.duty) && (operatingPoint.voltage_mode!=="output_voltage" || fixedInBounds(id,"target",operatingPoint.target_vout)) && Object.entries(operatingPoint.plant??{}).every(([axis,value])=>fixedInBounds(id,axis,value)))); return ( !!selectedTopology?.simulator && selectedRatio === 4 && operatingPoint.vout >= 0.3 && operatingPoint.vout <= 1.1 && operatingPoint.iout >= 0.1 && operatingPoint.iout <= 40 ); } function renderSelection() { const entry = selectedTopology; document.querySelector('[data-view="compare"]').disabled = !entry; document.querySelector('[data-view="simulator"]').disabled = !simulationAvailable(); if (!entry) return; $("#selected-name").textContent = entry.name; $("#selected-ratio").textContent = `${selectedRatio}:1 reference · ${conditions.topologies[entry.id]?.simulator?.axes?`Vin ${operatingPoint.vin} V · ${operatingPoint.voltage_mode==="output_voltage" ? `target ${operatingPoint.target_vout} V` : `duty ${operatingPoint.duty??.5}`}`:`Vout ${operatingPoint.vout} V`} · Iout ${operatingPoint.iout} A`; $("#selected-image").src = "./compare/assets/" + entry.image; $("#selected-image").alt = entry.name + " circuit schematic"; $("#selected-simulate").disabled = !simulationAvailable(); $("#selected-simulate").textContent = entry.simulationRelation === "related" ? "Related simulation →" : "Simulate →"; $("#selected-edit").disabled = !entry.starter; $("#selected-edit").textContent = entry.simulationRelation === "related" ? "Edit related schematic" : "Edit schematic"; $("#selected-availability").textContent = !entry.simulator ? "Analytical model available. A validated NGSpice preset is not yet available for this topology." : fixedPoints.has(entry.simulator) ? simulationAvailable() ? "Continuous inputs and configurable sweeps. Each run checks result reliability." : conditions.topologies[entry.id]?.simulator?.axes ? "Use a reachable voltage or duty command and component values within the Simulator preset bounds." : entry.simulator === "sp2" ? "Set nominal output to 0.9–2 V and output current to 0.05–4 A to open the SP-SC Simulator." : "Set nominal output to 0.9–2 V and output current to 0.15–2 A to open the resonant SC Simulator." : selectedRatio !== 4 ? "This preset currently supports simulation in the 4:1 family; the selected ratio has an analytical model." : !simulationAvailable() ? "This simulation preset supports 0.30–1.10 V output and 0.1–40 A. Adjust the analysis operating point to use it." : (entry.simulationNote ?? ""); } function chooseTopology(entry, family, view = "compare") { if (!entry || !entry.ratios.includes(family)) { notify("This topology has no qualified model for the selected ratio."); return; } selectReference(entry, family); gallery.highlight(entry.id); renderSelection(); showView(view); } function referenceSelection() { return { id: selectedTopology.id, ratio: selectedRatio, ...operatingPoint }; } $("#back-gallery").onclick = () => showView("gallery"); $("#selected-analysis").onclick = () => showView("compare"); $("#selected-simulate").onclick = () => showView("simulator"); $("#selected-edit").onclick = () => { const starter = starters.find( (item) => item.id === selectedTopology?.starter, ); if (starter) { openStarter(starter); showView("design"); } }; function saveLocal() { if (!current) return; try { localStorage.setItem( STORAGE, JSON.stringify({ project: current, starter: active?.id ?? null, baseline, }), ); // Retire the old key only after the canonical project was accepted and saved. if (migratingStorage) { try { localStorage.removeItem(PREVIOUS_STORAGE); } catch {} migratingStorage = false; } $("#save-status").textContent = "Saved in this browser"; } catch { $("#save-status").textContent = "Browser storage unavailable · download to keep"; } } function postProject(project, requestId = acceptedRequestId) { if (ready) editor.contentWindow.postMessage( { type: "pe:load", project, requestId }, location.origin, ); } function renderLibrary() { const list = $("#starter-list"); list.replaceChildren(); const matches = starters.filter((s) => s.ratio === ratio); for (const s of matches) { const button = document.createElement("button"); button.className = "starter" + (active?.id === s.id ? " active" : ""); const title = document.createElement("strong"); title.textContent = s.name; const sub = document.createElement("small"); sub.textContent = `${s.switches} switches · ${s.magneticsLabel ?? "inverse-coupled output"}`; const chip = document.createElement("span"); chip.className = "chip"; chip.textContent = `${s.ratio}:1 reference`; button.append(title, sub, chip); button.onclick = () => openStarter(s); list.append(button); } if (!matches.length) { const p = document.createElement("p"); p.className = "empty-family"; p.textContent = `${ratio}:1 starter and analytical model are not yet validated. Open a project to explore a custom circuit; the scoreboard lists supported reference families.`; list.append(p); } $$("[data-ratio]").forEach((b) => b.classList.toggle("active", +b.dataset.ratio === ratio), ); } async function openStarter(s) { const ticket = ++selection; try { const res = await fetch("./" + s.project); if (!res.ok) throw Error("Could not load starter"); const text = await res.text(); if (ticket !== selection) return; pendingLoad = { requestId: ticket, starter: s, project: text }; sentLoads.set(ticket, pendingLoad); notify(""); postProject(text, ticket); } catch (e) { notify(e.message); } } function showView(view) { if ((view === "compare" || view === "simulator") && !selectedTopology) return; if (view === "simulator" && !simulationAvailable()) return; currentView = view; $("#gallery-view").hidden = view !== "gallery"; $("#design-view").hidden = view !== "design"; $("#compare-view").hidden = view !== "compare"; $("#simulator-view").hidden = view !== "simulator"; $("#selection-bar").hidden = !selectedTopology || view === "gallery" || view === "design"; $(".file-actions").hidden = view !== "design"; if (view === "compare") { $("#compare-context").textContent = `${selectedTopology.name} · ${selectedRatio}:1 · selected reference model`; analysis.show(referenceSelection()); } if (view === "simulator") simulator.show({ topology: selectedTopology.simulator, ratio: selectedRatio, ...operatingPoint, }); $$("[data-view]").forEach((button) => button.classList.toggle("active", button.dataset.view === view), ); } $$("[data-view]").forEach((b) => (b.onclick = () => showView(b.dataset.view))); $("#back-design").onclick = () => showView("gallery"); $$("[data-ratio]").forEach( (b) => (b.onclick = () => { ratio = +b.dataset.ratio; renderLibrary(); }), ); $("#compare-reference").onclick = () => { const entry = gallery.get(active?.model); if (entry) chooseTopology(entry, active.ratio); }; window.addEventListener("message", (event) => { if (event.origin !== location.origin || event.source !== editor.contentWindow) return; const data = event.data; if (data?.type === "pe:ready") { if (ready) return; ready = true; if (pendingLoad) postProject(pendingLoad.project, pendingLoad.requestId); else if (current) postProject(current); else if (starters.length && selection === 0) openStarter(starters.find((s) => s.id === "xfly6s") ?? starters[0]); return; } if (data?.type === "pe:error") { if (!sentLoads.has(data.requestId)) return; sentLoads.delete(data.requestId); if (data.requestId === pendingLoad?.requestId) pendingLoad = null; notify(data.message); return; } if ( data?.type !== "pe:snapshot" || (data.requestId !== acceptedRequestId && (!sentLoads.has(data.requestId) || data.requestId < acceptedRequestId)) || typeof data.project !== "string" || data.project.length > 10_000_000 || typeof data.signature !== "string" ) return; if (data.requestId !== acceptedRequestId && sentLoads.has(data.requestId)) { const acceptedLoad = sentLoads.get(data.requestId); acceptedRequestId = data.requestId; active = acceptedLoad.starter; baseline = null; if (pendingLoad?.requestId === data.requestId) pendingLoad = null; for (const id of sentLoads.keys()) if (id <= acceptedRequestId) sentLoads.delete(id); if (active) { ratio = active.ratio; $("#context-name").textContent = active.name; $("#context-description").textContent = active.description; } else { $("#context-name").textContent = "Imported circuit"; $("#context-description").textContent = "Custom project. Connectivity and parameters remain editable; no reference loss model is assigned."; } renderLibrary(); } current = data.project; if (active && baseline === null) baseline = data.signature; const matched = !!active && baseline === data.signature; $("#model-status").textContent = matched ? "Reference structure retained. Compare this family using the curated analytical model." : "Custom electrical structure or values. Reference results do not describe this edited circuit."; $("#model-status").classList.toggle("edited", !matched); $("#compare-reference").disabled = !matched; try { const p = JSON.parse(current); $("#project-name").textContent = p.name ?? "Power converter"; const docs = p.documents ?? []; // The state drawings in these starters repeat the top-cell devices. const counted = ["rsc2","si2"].includes(active?.id) ? docs.filter(d => d.id === p.topDocumentId) : docs; const instances = counted.flatMap(d => d.instances ?? []); const types = instances.map((i) => String(i.type ?? i.symbolId ?? "")); $("#device-count").textContent = types.filter((t) => /^(nmos|pmos|mosfet|switch)/i.test(t), ).length; $("#winding-count").textContent = types.filter((t) => /inductor/i.test(t), ).length; $("#cap-count").textContent = types.filter((t) => /^capacitor/i.test(t), ).length; } catch {} $("#save-project").disabled = false; saveLocal(); }); $("#save-project").onclick = () => { if (!current) return; const url = URL.createObjectURL( new Blob([current], { type: "application/json" }), ); const a = document.createElement("a"); a.href = url; a.download = "openpels.icproj.json"; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); notify( "Project downloaded. Open project restores its editable circuit and component definitions.", ); }; $("#open-project").onclick = () => $("#project-file").click(); $("#project-file").onchange = async (event) => { const f = event.target.files[0]; event.target.value = ""; if (!f) return; showView("design"); if (f.size > 10_000_000) { notify("This project exceeds the 10 MB browser import limit."); return; } try { const text = await f.text(); JSON.parse(text); const requestId = ++selection; pendingLoad = { requestId, starter: null, project: text }; sentLoads.set(requestId, pendingLoad); postProject(text, requestId); notify(""); } catch { notify("Could not read the project JSON. Your circuit was kept."); } }; try { const currentCopy = localStorage.getItem(STORAGE); const previousCopy = currentCopy === null ? localStorage.getItem(PREVIOUS_STORAGE) : null; const stored = JSON.parse(currentCopy ?? previousCopy ?? "null"); if (stored && typeof stored.project === "string") { migratingStorage = currentCopy === null && previousCopy !== null; current = stored.project; baseline = stored.baseline; active = { id: stored.starter }; } } catch {} try { const res = await fetch("./starters/index.json", { cache: "no-store" }); if (!res.ok) throw Error("Starter library unavailable"); starters = await res.json(); active = starters.find((s) => s.id === active?.id) ?? null; if (active) { ratio = active.ratio; $("#context-name").textContent = active.name; $("#context-description").textContent = active.description; } renderLibrary(); if (ready) { if (pendingLoad) postProject(pendingLoad.project, pendingLoad.requestId); else if (current) postProject(current); else if (selection === 0) openStarter(starters.find((s) => s.id === "xfly6s") ?? starters[0]); } } catch (e) { notify(e.message); } // Recover an early child-ready event even when its bundle loads first. const greet = () => editor.contentWindow.postMessage({ type: "pe:hello" }, location.origin); editor.addEventListener("load", greet); greet(); await Promise.all([...fixedPoints.keys()].map(async id => { try { const response = await fetch(`./testbenches/${id}-preset.json`, { cache: "no-store" }); if (response.ok) fixedPresets.set(id,await response.json()); } catch { // Other presets remain available when one contract cannot load. } })); await gallery.load(); if (["#simulator", "#testbenches"].includes(location.hash)) { history.replaceState(null, "", "#simulator"); chooseTopology(gallery.get("xfly2p"), 4, "simulator"); } else if (location.hash === "#schematic") showView("design"); else showView(currentView);