Spaces:
Running
Running
Download simulator_service.py from minjiechen/OpenPELS: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/spaces/minjiechen/OpenPELS/resolve/main/simulator_service.py
- Command line
-
hf download hf://spaces/minjiechen/OpenPELS/simulator_service.py
-
curl -L -o simulator_service.py https://huggingface.co/spaces/minjiechen/OpenPELS/resolve/main/simulator_service.py
13.1 kB
| """Bounded local NGSpice jobs using the pinned, original XFLY simulation engine.""" | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| import hashlib | |
| import importlib.util | |
| import json | |
| import math | |
| import sys | |
| import os | |
| import re | |
| import shutil | |
| import threading | |
| import time | |
| import uuid | |
| from sp2 import sp2_preset | |
| from rsc2 import preset as rsc2_preset | |
| from si2 import preset as si2_preset | |
| from buck_stacked import preset as buck_stacked_preset | |
| FIXED_PRESETS = {"sp2": sp2_preset, "rsc2": rsc2_preset, "si2": si2_preset, "buck_stacked": buck_stacked_preset} | |
| STUDY = 'library/ngspice/studies/xfly6s_xfly8s_c3l_scaled_comparison' | |
| TOPOLOGIES = ('xfly6s', 'xfly8s', 'c3l') | |
| FIELDS = {'input_voltage_v', 'target_vout', 'output_current_a', 'lout_nh', 'cfly_nf', | |
| 'frequency_mhz_by_topology', 'switching_frequency_mhz', 'coupling', | |
| 'dcr1_mohm', 'dcr2_mohm', 'switch_ron_mohm', 'switch_coff_pf', | |
| 'gate_drive_v', 'gate_cap_pf', 'stop_us', 'max_step_ps', 'topologies', | |
| 'topology', 'load_pct', 'case_id'} | |
| def finite_tree(value, depth=0): | |
| if depth > 8: | |
| raise ValueError("Simulation input is too deeply nested") | |
| if isinstance(value, bool): | |
| raise ValueError('Use numeric values, not booleans') | |
| if isinstance(value, (int, float)) and not -sys.float_info.max <= value <= sys.float_info.max: | |
| raise ValueError('Simulation values must be finite') | |
| if isinstance(value, dict): | |
| for item in value.values(): | |
| finite_tree(item, depth + 1) | |
| elif isinstance(value, list): | |
| for item in value: | |
| finite_tree(item, depth + 1) | |
| def validate_request(kind, payload, cases): | |
| if kind not in {'run', 'sweep-case', 'source'} or not isinstance(payload, dict): | |
| raise ValueError('Choose a supported simulation request') | |
| finite_tree(payload) | |
| if kind == 'run': | |
| for topology, preset in FIXED_PRESETS.items(): | |
| if payload.get('topologies') == [topology]: | |
| preset.validate(payload) | |
| return | |
| if set(payload) - FIELDS: | |
| raise ValueError('Unsupported simulation input') | |
| if kind == 'source': | |
| if set(payload) != {'case_id'} or payload['case_id'] not in cases: | |
| raise ValueError('Choose one original source testbench') | |
| return | |
| selected = payload.get('topologies') if kind == 'run' else [payload.get('topology')] | |
| if not isinstance(selected, list) or len(selected) != 1 or any(item not in TOPOLOGIES for item in selected) or len(set(selected)) != len(selected): | |
| raise ValueError('Choose exactly one topology: XFLY6S, XFLY8S or C3L') | |
| for key, value in payload.items(): | |
| if key in {'topologies', 'topology'}: | |
| continue | |
| if key == 'frequency_mhz_by_topology': | |
| if not isinstance(value, dict) or set(value) - set(TOPOLOGIES): | |
| raise ValueError('Invalid per-topology frequencies') | |
| values = value.values() | |
| else: | |
| values = [value] | |
| if any(isinstance(item, bool) or not isinstance(item, (int, float)) or not math.isfinite(item) for item in values): | |
| raise ValueError('Simulation parameters must be finite numbers') | |
| def scalar(value): | |
| match = re.fullmatch(r'([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)(meg|[tgkmunpf]?)', value.strip(), re.I) | |
| if not match: | |
| raise ValueError('Unsupported source scalar: ' + value) | |
| scales = {'': 1, 't': 1e12, 'g': 1e9, 'meg': 1e6, 'k': 1e3, 'm': 1e-3, 'u': 1e-6, 'n': 1e-9, 'p': 1e-12, 'f': 1e-15} | |
| return float(match[1]) * scales[match[2].lower()] | |
| def instrument_source(text, run_id, topology): | |
| text = re.sub(r'^\s*(?:write|wrdata)\b[^\n]*', '', text, flags=re.M | re.I) | |
| text, count = re.subn(r'^\.control\s*$', '.save i(Vvin) v(cin_int) v(co_int)\n.control', text, count=1, flags=re.M) | |
| if count != 1: | |
| raise ValueError('Source testbench needs one control block') | |
| text, count = re.subn(r'^run\s*$', f'run\nwrite output/xfly_gui/{run_id}/{topology}.raw', text, count=1, flags=re.M) | |
| if count != 1: | |
| raise ValueError('Source testbench needs one transient run') | |
| return text | |
| class Simulator: | |
| def __init__(self, engine_path, site, work): | |
| self.source_metadata = None | |
| self.site, self.work = Path(site).resolve(), Path(work).resolve() | |
| self.work.mkdir(parents=True, exist_ok=True) | |
| os.environ.setdefault("MPLCONFIGDIR", str(self.work / "matplotlib-cache")) | |
| os.environ.setdefault("XDG_CACHE_HOME", str(self.work / "cache")) | |
| manifest = json.loads((self.site / 'testbenches/index.json').read_text()) | |
| self.cases = {case['id']: (group, case) for group in manifest['circuits'] for case in group['cases']} | |
| source_lock = json.loads((Path(__file__).parent / 'simulator-source.json').read_text()) | |
| self.source_metadata = source_lock | |
| if hashlib.sha256(Path(engine_path).read_bytes()).hexdigest() != source_lock['sha256']: | |
| raise ValueError('XFLY simulator engine checksum differs') | |
| spec = importlib.util.spec_from_file_location('openpels_xfly_engine', engine_path) | |
| self.engine = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(self.engine) | |
| self.engine.REPO_ROOT = self.work | |
| self.engine.RUN_ROOT = self.work / 'output/xfly_gui' | |
| self.engine.RUN_ROOT.mkdir(parents=True, exist_ok=True) | |
| self.engine.ASSET_DIR = self.site / 'testbenches/images' | |
| for topology, meta in self.engine.TOPOLOGIES.items(): | |
| meta['template'] = self.site / 'testbenches/netlists' / (topology + '_transient.cir') | |
| # Reuse the original computations while retaining only compact export data. | |
| self._analyze_case = self.engine.analyze_case | |
| self.engine.analyze_case = self.analyze_case | |
| self.jobs, self.lock = {}, threading.RLock() | |
| self.worker = ThreadPoolExecutor(max_workers=1, thread_name_prefix='ngspice') | |
| def analyze_case(self, topology, run_dir, settings, case_id=None): | |
| import numpy as np | |
| case = self._analyze_case(topology, run_dir, settings, case_id) | |
| indices = np.linspace(0, len(case['time']) - 1, min(4000, len(case['time'])), dtype=int) | |
| columns = [case['time'], case['vout'], case['il1'], case['il2'], *[values for _, values in case['caps']]] | |
| np.savetxt(run_dir / f'{case_id or topology}-sampled.csv', | |
| np.column_stack([values[indices] for values in columns]), delimiter=',', | |
| header=','.join(['time_s', 'vout_v', 'il1_a', 'il2_a', *[f'cfly{index + 1}_v' for index in range(len(case['caps']))]]), comments='') | |
| return case | |
| def source_run(self, case_id): | |
| group, case = self.cases[case_id] | |
| topology, p = group['id'], case['parameters'] | |
| text = (self.site / 'testbenches' / case['file']).read_text() | |
| if hashlib.sha256(text.encode()).hexdigest() != case['sha256']: | |
| raise ValueError('Source testbench checksum differs') | |
| tran = re.search(r'^\.tran\s+(\S+)\s+(\S+)\s+\S+\s+(\S+)', text, re.M) | |
| frequency = scalar(p['FSW_XFLY']) / 2 if 'FSW_XFLY' in p else scalar(p['FSW']) | |
| payload = dict(input_voltage_v=scalar(p['VIN']), target_vout=scalar(p['VOUT_TARGET']), | |
| output_current_a=scalar(p['IOUT_NOM']), lout_nh=scalar(p['LOUT']) * 1e9, | |
| cfly_nf=scalar(p['CFLY']) * 1e9, coupling=scalar(p['KCOUP']), | |
| dcr1_mohm=scalar(p.get('LDCR1', p['LDCR'])) * 1e3, | |
| dcr2_mohm=scalar(p.get('LDCR2', p['LDCR'])) * 1e3, | |
| switch_ron_mohm=2, switch_coff_pf=scalar(p['COFF']) * 1e12, | |
| gate_drive_v=scalar(p['VDRV']), gate_cap_pf=0, | |
| stop_us=scalar(tran[2]) * 1e6, max_step_ps=scalar(tran[3]) * 1e12, | |
| frequency_mhz_by_topology={topology: frequency * 1e-6}) | |
| settings = self.engine.settings_from_payload(payload, [topology]) | |
| settings['duty_by_topology'] = {topology: scalar(p['DUTY'])} | |
| settings['unclamped_duty_by_topology'] = dict(settings['duty_by_topology']) | |
| settings['source_case_id'] = case_id | |
| run_id = time.strftime('%Y%m%d-%H%M%S-') + uuid.uuid4().hex[:8] | |
| directory = self.engine.RUN_ROOT / run_id | |
| directory.mkdir() | |
| # Instrumentation-only changes: save input/current/energy probes and | |
| # redirect large exports. Circuit, models, gating, ICs and .tran stay intact. | |
| text = instrument_source(text, run_id, topology) | |
| (directory / 'settings.json').write_text(json.dumps(settings, indent=2)) | |
| deck = directory / (topology + '.cir') | |
| deck.write_text(text) | |
| started = time.perf_counter() | |
| self.engine.run_ngspice(deck) | |
| analyzed = self.analyze_case(topology, directory, settings) | |
| plot = self.engine.make_plot([analyzed], directory, settings) | |
| return dict(run_id=run_id, elapsed_s=time.perf_counter() - started, | |
| settings=settings, metrics=[analyzed['metrics']], | |
| source_case_id=case_id, plot_url=f'/runs/{run_id}/{plot.name}') | |
| def submit(self, kind, payload): | |
| validate_request(kind, payload, self.cases) | |
| with self.lock: | |
| self.prune() | |
| if sum(job['state'] in {'queued', 'running'} for job in self.jobs.values()) >= 3: | |
| raise BlockingIOError('Simulator is busy. Try again after a running job finishes.') | |
| job_id = uuid.uuid4().hex | |
| self.jobs[job_id] = dict(id=job_id, state='queued', created=time.time(), kind=kind) | |
| self.worker.submit(self.execute, job_id, kind, json.loads(json.dumps(payload))) | |
| return dict(self.jobs[job_id]) | |
| def update_progress(self, job_id, complete, total): | |
| with self.lock: | |
| self.jobs[job_id]['progress'] = {'complete': complete, 'total': total} | |
| def execute(self, job_id, kind, payload): | |
| with self.lock: | |
| self.jobs[job_id]['state'] = 'running' | |
| before = None | |
| try: | |
| before = set(self.engine.RUN_ROOT.iterdir()) | |
| if kind == 'source': | |
| result = self.source_run(payload['case_id']) | |
| elif kind == 'run' and payload['topologies'][0] in FIXED_PRESETS: | |
| directory = self.engine.RUN_ROOT / job_id | |
| directory.mkdir() | |
| result = FIXED_PRESETS[payload['topologies'][0]].run(payload, directory, | |
| lambda complete, total: self.update_progress(job_id, complete, total)) | |
| elif kind == 'run': | |
| result = self.engine.run_simulation(payload) | |
| else: | |
| result = self.engine.run_sweep_case(payload) | |
| directory = self.engine.RUN_ROOT / result['run_id'] | |
| artifacts = [] | |
| for path in sorted(directory.iterdir()): | |
| if path.suffix == '.raw' or path.name.endswith('_timeseries.csv'): | |
| path.unlink() | |
| elif path.suffix in {'.cir', '.log', '.csv', '.json', '.png'}: | |
| artifacts.append(dict(name=path.name, url=f'/simulator/runs/{directory.name}/{path.name}')) | |
| result['engine_revision'] = result.get('model_provenance', {}).get( | |
| 'phase_cd_commit', self.source_metadata['revision']) | |
| result['artifacts'] = artifacts | |
| if 'plot_url' in result: | |
| result['plot_url'] = '/simulator' + result['plot_url'] | |
| result['artifacts'].append(dict(name='result.json', url=f'/simulator/runs/{directory.name}/result.json')) | |
| (directory / 'result.json').write_text(json.dumps(result, allow_nan=False, indent=2)) | |
| # Refuse non-finite JSON rather than presenting a successful bad run. | |
| json.dumps(result, allow_nan=False) | |
| with self.lock: | |
| self.jobs[job_id].update(state='succeeded', result=result, finished=time.time()) | |
| except Exception as error: | |
| # Failed runs must not fill the ephemeral disk with raw traces. | |
| if before is not None: | |
| for directory in set(self.engine.RUN_ROOT.iterdir()) - before: | |
| shutil.rmtree(directory, ignore_errors=True) | |
| with self.lock: | |
| self.jobs[job_id].update(state='failed', error=str(error)[:3000], finished=time.time()) | |
| def get(self, job_id): | |
| with self.lock: | |
| job = self.jobs.get(job_id) | |
| return dict(job) if job else None | |
| def prune(self): | |
| completed = sorted((job for job in self.jobs.values() if job['state'] in {'succeeded', 'failed'}), key=lambda job: job['created']) | |
| for job in completed: | |
| if len(self.jobs) < 64 and time.time() - job['created'] < 3600: | |
| continue | |
| result = job.get('result', {}) | |
| if result.get('run_id'): | |
| shutil.rmtree(self.engine.RUN_ROOT / result['run_id'], ignore_errors=True) | |
| del self.jobs[job['id']] | |