Spaces:
Running

File size: 9,107 Bytes
1e8420e
e3a78d8
f9845e9
1e8420e
e3a78d8
 
1e8420e
 
 
 
9a4ea8c
 
f9845e9
 
 
 
 
 
e3a78d8
f9845e9
e3a78d8
 
 
 
 
 
 
 
 
 
f9845e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3a78d8
 
 
 
 
f9845e9
 
 
 
 
 
 
 
 
 
 
 
 
1e8420e
 
 
 
 
 
 
 
 
 
f9845e9
 
1e8420e
264fc61
1e8420e
9a4ea8c
 
f9845e9
1e8420e
 
 
f9845e9
 
 
 
1e8420e
 
 
f9845e9
e3a78d8
 
 
 
 
1e8420e
 
 
 
e3a78d8
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
"""Host adaptation for the pinned simulator UI; numerical source stays unchanged."""
import json
import re

from sp2.sp2_preset import contract

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>
          </select>
        </div>
        <section id="sp2-fixture-info" hidden aria-label="SP-SC parameters">
          <p>3 V input · 1.5 V nominal output. The stage delivers a lower voltage under load.</p>
          <label for="sp2-parameter">Simulation parameter</label>
          <select id="sp2-parameter"></select>
          <label for="sp2-point">Parameter value</label>
          <select id="sp2-point"></select>
          <label class="check"><input id="sp2-include-sweep" type="checkbox"> Sweep the selected parameter</label>
          <p id="sp2-settings"></p>
        </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>
        <img src="/compare/assets/sp2-candidate.svg" alt="Eight-switch 2:1 series-parallel SC">
      </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)
    html = html.replace('<script>\n    const form', '<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 .control:not(:has(#topologySelect)),
      #controls.sp2-fixed .optional-sweep{display:none}
      #sp2-fixture-info{display:grid;gap:8px}
      #sp2-fixture-info p{margin:0;font-size:12px}
      #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')
    sp2 = json.dumps(contract(), ensure_ascii=False).replace('<', '\\u003c')
    return html.replace('</body>', f'<script type="application/json" id="sp2-contract">{sp2}</script></body>')