Spaces:
Running
Running
Download simulator_frame.py from minjiechen/OpenPELS: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/spaces/minjiechen/OpenPELS/resolve/main/simulator_frame.py
- Command line
-
hf download hf://spaces/minjiechen/OpenPELS/simulator_frame.py
-
curl -L -o simulator_frame.py https://huggingface.co/spaces/minjiechen/OpenPELS/resolve/main/simulator_frame.py
12.2 kB
| """Host adaptation for the pinned simulator UI; numerical source stays unchanged.""" | |
| import json | |
| import re | |
| from operating_conditions import registry | |
| from simulator_service import FIXED_PRESETS | |
| def simulator_html(original): | |
| html = original.replace('<title>Xfly / C3L Comparison GUI - Chen / Kudva</title>', '<title>OpenPELS · NGSpice simulator</title>') | |
| html = html.replace('Xfly6S / Xfly8S / C3L NGSpice Comparison - Chen / Kudva', 'NGSpice simulator') | |
| html = html.replace('src="/assets/', 'src="/simulator/assets/') | |
| html = html.replace('max="1.10" step="0.01"', 'max="1.10" step="any"') | |
| html = html.replace('Number(targetVout.value).toFixed(2)', 'Number(targetVout.value).toFixed(3)') | |
| selector = '''<div class="control"> | |
| <label for="topologySelect">Topology</label> | |
| <select id="topologySelect" name="topology"> | |
| <option value="xfly6s">XFLY6S</option> | |
| <option value="xfly8s">XFLY8S</option> | |
| <option value="c3l">C3L</option> | |
| <option value="sp2">2:1 series-parallel SC</option> | |
| <option value="rsc2">2:1 resonant SC</option> | |
| <option value="si2">2:1 switched inductor</option> | |
| <option value="buck_stacked">2:1 Buck_Stacked</option> | |
| </select> | |
| </div> | |
| <section id="sp2-fixture-info" hidden aria-label="Topology simulation parameters"> | |
| <div class="metric"><b>Nominal output voltage</b><span id="sp2-nominal-output"></span></div> | |
| <div id="sp2-controls"></div> | |
| <p id="sp2-settings"></p> | |
| <details class="sp2-model-note"> | |
| <summary>Model and run limits</summary> | |
| <p id="fixed-model-note">Fixed two-phase 2:1 gain. The output current is a constant-current load. | |
| Leave gate capacitance, duration or maximum step blank for automatic settings. Every run checks periodic steady state, energy balance and convergence. | |
| Q3/Q7 use a −2 V off bias. Effective gate capacitance supplies the auxiliary loss estimate.</p> | |
| </details> | |
| <label class="check"><input id="sp2-include-sweep" type="checkbox"> Include parameter sweep</label> | |
| <div id="sp2-sweep-controls" hidden> | |
| <label for="sp2-parameter">Parameter to sweep</label> | |
| <select id="sp2-parameter"></select> | |
| <div class="two"> | |
| <div class="control"><label for="sp2-sweep-start">Start</label><input id="sp2-sweep-start" type="number" step="any"></div> | |
| <div class="control"><label for="sp2-sweep-stop">Stop</label><input id="sp2-sweep-stop" type="number" step="any"></div> | |
| </div> | |
| <label for="sp2-sweep-count">Points</label> | |
| <input id="sp2-sweep-count" type="number" step="1"> | |
| <p>The main waveform uses the entered operating point. The sweep varies the selected input and keeps the other settings.</p> | |
| </div> | |
| </section>''' | |
| html = html.replace('<form id="controls" class="panel controls">', '<form id="controls" class="panel controls">' + selector, 1) | |
| start = html.index(' <div class="control">\n <label>Topologies</label>') | |
| end = html.index(' <div class="actions">', start) | |
| html = html[:start] + html[end:] | |
| start = html.index(' <div class="control">\n <label>Switching Frequency (MHz)</label>') | |
| end = html.index(' <div class="control">\n <label for="cfly">', start) | |
| html = html[:start] + '''<div class="control"> | |
| <label for="frequency">Switching Frequency (MHz)</label> | |
| <input id="frequency" name="frequency" type="number" min="1" max="500" step="1" value="100"> | |
| </div> | |
| ''' + html[end:] | |
| html = html.replace('const topologies = [...form.querySelectorAll(\'input[name="topology"]:checked\')].map(x => x.value);', "const topologies = [document.getElementById('topologySelect').value];") | |
| html, count = re.subn(r"frequency_mhz_by_topology: \{.*?\n \},", "frequency_mhz_by_topology: {[topologies[0]]: Number(document.getElementById('frequency').value)},", html, count=1, flags=re.S) | |
| if count != 1: | |
| raise ValueError('Pinned simulator frequency contract changed') | |
| def mark_drawing(match): | |
| key = re.search(r'/(xfly6s|xfly8s|c3l)\.png', match[0])[1] | |
| hidden = ' hidden' if key != 'xfly6s' else '' | |
| return match[0].replace('<figure class="topology-card">', f'<figure class="topology-card" data-topology="{key}"{hidden}>') | |
| html, count = re.subn(r'<figure class="topology-card">.*?</figure>', mark_drawing, html, flags=re.S) | |
| if count != 3: | |
| raise ValueError('Pinned simulator drawing contract changed') | |
| card_end = html.index('</figure>', html.index('data-topology="c3l"')) + len('</figure>') | |
| html = html[:card_end] + ''' | |
| <figure class="topology-card" data-topology="sp2" hidden> | |
| <b>2:1 series-parallel SC</b> | |
| <div class="topology-image-frame"> | |
| <img src="/compare/assets/sp2-candidate.svg" alt="Eight-switch 2:1 series-parallel SC"> | |
| </div> | |
| </figure> | |
| <figure class="topology-card" data-topology="buck_stacked" hidden> | |
| <h3>2:1 Buck_Stacked</h3> | |
| <img src="/compare/assets/buck-stacked-candidate.svg" alt="Eight numbered switches in two inverse-coupled stacked buck phases"> | |
| </figure> | |
| <figure class="topology-card" data-topology="si2" hidden> | |
| <b>2:1 switched inductor</b> | |
| <div class="topology-image-frame"> | |
| <img src="/compare/assets/si2-candidate.svg" alt="Two inverse-coupled synchronous buck phases"> | |
| </div> | |
| </figure> | |
| <figure class="topology-card" data-topology="rsc2" hidden> | |
| <b>2:1 resonant SC</b> | |
| <div class="topology-image-frame"> | |
| <img src="/compare/assets/rsc2-candidate.svg" alt="Two interleaved resonant switched-capacitor legs"> | |
| </div> | |
| </figure>''' + html[card_end:] | |
| html = html.replace(" const sweepTopologies = ['xfly6s', 'xfly8s', 'c3l'];\n", '') | |
| html = html.replace('sweepTopologies.map(topology => chartForTopology(', '[...new Set(items.map(item => item.key))].map(topology => chartForTopology(') | |
| html = html.replace('const jobs = sweepTopologies.flatMap(', 'const jobs = basePayload.topologies.flatMap(') | |
| # Drain in-flight sweep jobs before the form unlocks topology selection. | |
| html = html.replace(' let nextJob = 0;', ' let nextJob = 0;\n let failed = false;') | |
| html = html.replace('while (nextJob < jobs.length)', 'while (!failed && nextJob < jobs.length)') | |
| html = html.replace(' } finally {\n active -= 1;', ' } catch (error) {\n failed = true;\n throw error;\n } finally {\n active -= 1;') | |
| html = html.replace(' await Promise.all(Array.from({length: workerCount}, () => runWorker()));', ''' const settled = await Promise.allSettled(Array.from({length: workerCount}, () => runWorker())); | |
| const failure = settled.find(item => item.status === 'rejected'); | |
| if (failure) throw failure.reason;''') | |
| html = html.replace('Select at least one topology.', 'Select one topology.') | |
| html = html.replace('comparison plot', 'waveform plot').replace('Comparison plot', 'Waveform plot').replace('comparison run', 'simulation run') | |
| for endpoint in ('run', 'sweep-case'): | |
| old = f"fetch('/api/{endpoint}'," | |
| if html.count(old) != 1: | |
| raise ValueError('Pinned simulator request contract changed: ' + endpoint) | |
| html = html.replace(old, f"openpelsSimulationFetch('/api/{endpoint}',") | |
| html = html.replace(' await runEfficiencySweep(payload);\n statusEl.textContent = `Run ${data.run_id} + sweep complete`;', ''' openpelsRenderArtifacts(data); | |
| if (document.getElementById('includeSweep').checked) { | |
| await runEfficiencySweep(payload); | |
| statusEl.textContent = `Run ${data.run_id} + sweep complete`; | |
| }''') | |
| html = html.replace('<div class="actions">\n <button id="runButton"', '<label class="check optional-sweep"><input type="checkbox" id="includeSweep"> Include optional 15-point efficiency sweep</label>\n <div class="actions">\n <button id="runButton"') | |
| html = html.replace('Runs after the waveform plot.', 'Optional · enable in the controls before running.') | |
| html = html.replace('<table id="metricsTable" hidden>', '<div class="metrics-scroll"><table id="metricsTable" hidden>').replace('</table>', '</table></div>', 1) | |
| html = html.replace('<main>', '<div id="runArtifacts" class="run-artifacts"></div>\n<main>', 1) | |
| models = ('<script src="/compare/operating-point.js?v=operating-conditions"></script>\n' | |
| '<script src="/compare/switched-inductor.js?v=operating-conditions"></script>\n') | |
| html = html.replace('<script>\n const form', models+'<script src="/simulator/bridge.js"></script>\n <script>\n const form', 1) | |
| html = html.replace(' runButton.disabled = true;', " runButton.disabled = true;\n document.getElementById('topologySelect').disabled = true;\n document.getElementById('targetVout').disabled = true;\n document.getElementById('iout').disabled = true;\n openpelsRenderArtifacts({artifacts:[]});") | |
| html = html.replace(' runButton.disabled = false;', " runButton.disabled = false;\n document.getElementById('topologySelect').disabled = false;\n document.getElementById('targetVout').disabled = false;\n document.getElementById('iout').disabled = false;") | |
| html = html.replace('Efficiency (%)', 'Modeled efficiency (%)').replace('Best Efficiency', 'Modeled efficiency') | |
| html = html.replace('</head>', '''<style> | |
| body{background:#f5f6f8}header{position:static;padding:14px 22px}h1{font-size:17px} | |
| :root{--blue:#e15c34;--line:#e3e7eb;--shadow:none}button{background:#e15c34} | |
| [hidden]{display:none!important} | |
| #topologySelect{width:100%;padding:10px;border:1px solid #dce0e5;border-radius:6px;background:white;font:inherit;color:inherit} | |
| .topology-strip,.sweep-grid{grid-template-columns:minmax(0,1fr)} | |
| .topology-image-frame{height:250px}.plot-wrap img{width:auto;max-width:100%;max-height:900px} | |
| .run-artifacts{display:none;padding:12px 22px;background:#fff7f1;border-bottom:1px solid #eddfd7;font-size:11px;gap:8px;flex-wrap:wrap} | |
| .run-artifacts a{color:#af502e;border:1px solid #e4cabb;border-radius:4px;padding:6px 8px;text-decoration:none;background:#fff} | |
| section.results{min-width:0}.metrics-scroll{max-width:100%;overflow-x:auto} | |
| @media(max-width:600px){main{display:flex;flex-direction:column}.topology-strip{grid-template-columns:minmax(0,1fr)}.status{white-space:normal}} | |
| #controls.sp2-fixed > :is(.control:not(:has(#topologySelect)),.two,.optional-sweep){display:none} | |
| #sp2-fixture-info{display:grid;gap:8px} | |
| #sp2-fixture-info p{margin:0;font-size:12px;line-height:1.45} | |
| #sp2-fixture-info select{width:100%;padding:8px;border:1px solid var(--line);border-radius:6px;font:inherit;color:inherit;background:white} | |
| #sp2-controls{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px} | |
| #sp2-sweep-controls{display:grid;gap:8px} | |
| .sp2-model-note{font-size:12px} | |
| #sp2-sweep-results{overflow-x:auto} | |
| #sp2-sweep-results .sweep-chart img{width:100%;max-width:650px} | |
| #sp2-result{display:grid;grid-template-columns:max-content 1fr;gap:4px 12px} | |
| .optional-sweep{font-size:11px;color:#74818e;margin:10px 0} .optional-sweep input{width:auto} | |
| </style></head>''') | |
| if 'includeSweep' not in html or '/simulator/bridge.js' not in html: | |
| raise ValueError('Pinned simulator layout contract changed') | |
| presets = json.dumps({name:preset.contract() for name,preset in FIXED_PRESETS.items()}, ensure_ascii=False).replace('<', '\\u003c') | |
| operational = json.dumps(registry(),ensure_ascii=False).replace('<','\\u003c') | |
| return html.replace('</body>', f'<script type="application/json" id="sp2-contract">{presets}</script>' | |
| f'<script type="application/json" id="operating-conditions">{operational}</script></body>') | |