Spaces:
Sleeping
Sleeping
File size: 11,886 Bytes
90bf6ec 4ee621f 90bf6ec 22b441d 90bf6ec 4ee621f 90bf6ec 4ee621f 90bf6ec 4ee621f 90bf6ec 50e62eb 90bf6ec 4ee621f 90bf6ec 4ee621f 90bf6ec 4ee621f 90bf6ec | 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 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | /**
* Generate a runnable Python script from the current canvas pipeline.
*
* The script imports Qiskit + qlib modules and reproduces the same
* operations the backend would run, so a researcher can copy the file
* into their own project, tweak it, and run batch experiments without
* the web UI.
*
* We deliberately keep the generated code flat and readable (no
* classes, no abstractions) so someone unfamiliar with the codebase
* can follow it line by line.
*
* Architecture: one ``Emitter`` per node kind. Each emitter is a pure
* function from (params, stepNum, ctx) to a list of source lines. The
* main loop walks the topo-sorted nodes, dispatches to the emitter,
* and concatenates. To support a new node kind, add one entry to
* ``EMITTERS``.
*/
import type { Node, Edge } from "@xyflow/react";
import type { QNodeData } from "../components/QNode";
import type { NodeKind } from "./nodeCatalog";
interface PipelineNode {
kind: NodeKind;
params: Record<string, unknown>;
}
interface EmitContext {
/** Filename suggestion for an Option A QPY load. */
sampleKey: string | null;
}
type Emitter = (b: PipelineNode, stepNum: number, ctx: EmitContext) => string[];
// ---- topology helper -----------------------------------------------------
/**
* Topological sort of canvas nodes using the edge list.
* Falls back to catalog order if the graph is disconnected.
*/
function topoSort(nodes: Node[], edges: Edge[]): Node[] {
const adj = new Map<string, string[]>();
const indeg = new Map<string, number>();
for (const n of nodes) {
adj.set(n.id, []);
indeg.set(n.id, 0);
}
for (const e of edges) {
adj.get(e.source)?.push(e.target);
indeg.set(e.target, (indeg.get(e.target) ?? 0) + 1);
}
const queue = nodes.filter((n) => (indeg.get(n.id) ?? 0) === 0).map((n) => n.id);
const order: string[] = [];
while (queue.length > 0) {
const id = queue.shift()!;
order.push(id);
for (const next of adj.get(id) ?? []) {
const d = (indeg.get(next) ?? 1) - 1;
indeg.set(next, d);
if (d === 0) queue.push(next);
}
}
const byId = new Map(nodes.map((n) => [n.id, n]));
// Append any disconnected nodes at the end.
for (const n of nodes) {
if (!order.includes(n.id)) order.push(n.id);
}
return order.map((id) => byId.get(id)!).filter(Boolean);
}
// ---- emitters: one per node kind -----------------------------------------
//
// Each emitter returns ONLY the body lines for its step — the main
// loop handles the leading "# Step N: <title>" header and a trailing
// blank line. Keep each emitter self-contained so adding a new node
// kind is a strictly additive change.
function asStr(v: unknown, dflt: string): string {
return typeof v === "string" && v.length > 0 ? v : dflt;
}
function asNum(v: unknown, dflt: number): number {
return typeof v === "number" && Number.isFinite(v) ? v : dflt;
}
const emitInputCircuit: Emitter = (_b, _step, { sampleKey }) => {
const lines: string[] = [];
if (sampleKey) {
lines.push(`# Sample: ${sampleKey}`);
lines.push(`# Option A: Load from a .qpy file`);
lines.push(`# from qiskit import qpy`);
lines.push(`# with open("${sampleKey}.qpy", "rb") as f:`);
lines.push(`# qc = qpy.load(f)[0]`);
lines.push(``);
lines.push(`# Option B: Build programmatically (replace with your circuit)`);
} else {
lines.push(`# Replace with your circuit`);
}
lines.push(`qc = QuantumCircuit(4, name="my_circuit")`);
lines.push(`# qc.ry(0.5, 0)`);
lines.push(`# qc.cx(0, 1)`);
lines.push(`# ... add your gates here`);
return lines;
};
const emitFakeBackend: Emitter = (b) => {
const name = asStr(b.params.backend_name, "FakeFez");
const shots = asNum(b.params.shots, 1024);
return [
`from qiskit.providers.fake_provider import ${name}V2`,
`backend = ${name}V2()`,
`noise_model = NoiseModel.from_backend(backend)`,
`shots = ${shots} # user-set measurement count`,
];
};
const emitIbmBackend: Emitter = (b) => {
const name = asStr(b.params.backend_name, "ibm_fez");
const shots = asNum(b.params.shots, 1024);
return [
`# Requires: pip install qiskit-ibm-runtime`,
`# from qiskit_ibm_runtime import QiskitRuntimeService`,
`# service = QiskitRuntimeService(channel="ibm_quantum", token="YOUR_TOKEN")`,
`# backend = service.backend("${name}")`,
`# noise_model = NoiseModel.from_backend(backend)`,
`#`,
`# For now, falling back to fake backend:`,
`from qiskit.providers.fake_provider import FakeFezV2`,
`backend = FakeFezV2()`,
`noise_model = NoiseModel.from_backend(backend)`,
`shots = ${shots}`,
];
};
const emitQucad: Emitter = (b) => {
const iters = asNum(b.params.iterations, 3);
const lam = asNum(b.params.lam, 0.005);
const rho = asNum(b.params.rho, 500.0);
return [
`from qlib.qucad import run_qucad_training_noisy`,
``,
`# Bind free parameters to zero if circuit is parameterized`,
`if qc.num_parameters > 0:`,
` qc_bound = qc.assign_parameters([0.0] * qc.num_parameters)`,
`else:`,
` qc_bound = qc`,
``,
`theta, mask, history = run_qucad_training_noisy(`,
` qc, noise_model, backend,`,
` iterations=${iters}, lam=${lam}, rho=${rho},`,
`)`,
`qc = qc.assign_parameters(theta * (mask != 0))`,
`print(f"QuCAD: kept {int((mask != 0).sum())}/{len(mask)} parameters")`,
];
};
const emitQubound: Emitter = (b) => {
const cacheBackend = asStr(b.params.cache_backend, "ibm_fez");
const threshRaw = asNum(b.params.threshold, 0);
// 0 / negative disables pass/fail, matching the backend's
// _build_summary contract.
const threshold = threshRaw > 0 ? threshRaw : null;
const lines = [
`from qlib.qbound import call_QuBound_from_cache`,
`from pathlib import Path`,
``,
`cache_path = Path("cache/ibm_history/${cacheBackend}.pkl")`,
`if qc.num_parameters > 0:`,
` qc_eval = qc.assign_parameters([0.0] * qc.num_parameters)`,
`else:`,
` qc_eval = qc`,
``,
`bound, model, meta = call_QuBound_from_cache(`,
` qc_eval, cache_path, reference_backend=backend if 'backend' in dir() else None,`,
`)`,
`print(f"QuBound predicted error bound: {bound:.6f}")`,
];
if (threshold !== null) {
lines.push(
`threshold = ${threshold}`,
`passes = bound <= threshold`,
`margin = threshold - bound`,
`print(f" threshold {threshold}: {'PASS' if passes else 'FAIL'} (margin {margin:+.4f})")`,
);
}
return lines;
};
const emitCompvqc: Emitter = () => [
`from qlib.compvqc import get_LUT, quadraticProgram_luttoqp, admmOptimizedCompVQC, resultsCompressVQC`,
``,
`if qc.num_parameters > 0:`,
` comp_backend = backend if 'backend' in dir() else None`,
` if comp_backend is None:`,
` from qiskit.providers.fake_provider import FakeFezV2`,
` comp_backend = FakeFezV2()`,
` lut = get_LUT(qc, comp_backend)`,
` if lut:`,
` qp = quadraticProgram_luttoqp(qc, lut)`,
` result = admmOptimizedCompVQC(qp)`,
` qc = resultsCompressVQC(result, qc)`,
` print(f"CompressVQC: compressed circuit depth {qc.depth()}")`,
` else:`,
` print("CompressVQC: no compressible pairs found")`,
`else:`,
` print("CompressVQC: skipped (no parameterized gates)")`,
];
const emitQshot: Emitter = (b) => {
const snapshot = asStr(b.params.noise_snapshot, "pittsburgh_1");
const alpha = asNum(b.params.alpha, 0.95);
return [
`from qlib.qshot import get_recommender, resolve_noise_snapshot`,
``,
`if qc.num_parameters > 0:`,
` qc_shot = qc.assign_parameters([0.0] * qc.num_parameters)`,
`else:`,
` qc_shot = qc`,
``,
`noise_path = resolve_noise_snapshot("${snapshot}")`,
`recommender = get_recommender()`,
`result = recommender.predict(qc_shot, noise_path, alpha=${alpha})`,
`if result:`,
` print(f"Qshot: recommended {result['recommended_shots']} shots")`,
` print(f" predicted fidelity: {result['predicted_fidelity']:.4f}")`,
`else:`,
` print("Qshot: could not produce recommendation")`,
];
};
const emitFidelity: Emitter = (b) => {
const method = asStr(b.params.method, "statevector");
const policy = asStr(b.params.unbound_param_policy, "bind_zero");
if (method === "sampled") {
return [
`from qlib.qiskit_utils import sampledFidelityEstimator`,
``,
`fidelity, meta = sampledFidelityEstimator(`,
` qc,`,
` backend if 'backend' in dir() else None,`,
` shots=shots if 'shots' in dir() else 1024,`,
` unbound_param_policy="${policy}",`,
`)`,
`print(f"Fidelity (sampled, shots={meta['shots']}): {fidelity:.6f}")`,
];
}
return [
`from qlib.qiskit_utils import simpleFidelityEstimator`,
``,
`fidelity, meta = simpleFidelityEstimator(`,
` qc, unbound_param_policy="${policy}",`,
`)`,
`print(f"Fidelity (noiseless statevector): {fidelity:.6f}")`,
];
};
const emitOutput: Emitter = () => [
`print("\\n" + "=" * 60)`,
`print(f"Final circuit: {qc.num_qubits}q, depth {qc.depth()}, {qc.size()} gates")`,
`print(f"Gate counts: {dict(qc.count_ops())}")`,
`print(qc.draw(output='text', fold=120))`,
];
const STEP_TITLES: Record<NodeKind, string> = {
input_circuit: "Load circuit",
fake_backend: "Noisy simulator",
ibm_backend: "IBM live backend",
qucad: "QuCAD — noise-aware VQC sparsification",
qubound: "QuBound — LSTM error-bound prediction",
compvqc: "CompressVQC — fold redundant gates",
qshot: "Qshot — noise-aware shot-count recommendation",
fidelity: "Fidelity estimate",
output: "Output summary",
};
const EMITTERS: Record<NodeKind, Emitter> = {
input_circuit: emitInputCircuit,
fake_backend: emitFakeBackend,
ibm_backend: emitIbmBackend,
qucad: emitQucad,
qubound: emitQubound,
compvqc: emitCompvqc,
qshot: emitQshot,
fidelity: emitFidelity,
output: emitOutput,
};
// ---- main entry ----------------------------------------------------------
export function generatePythonScript(
nodes: Node[],
edges: Edge[],
sampleKey: string | null,
): string {
const sorted = topoSort(nodes, edges);
const blocks: PipelineNode[] = sorted.map((n) => ({
kind: (n.data as QNodeData).kind,
params: ((n.data as QNodeData).params as Record<string, unknown>) ?? {},
}));
const lines: string[] = [];
// Header
lines.push(`"""`);
lines.push(`Pipeline exported from QuDA Studio`);
lines.push(`https://jqub21-quaim.hf.space/`);
lines.push(`"""`);
lines.push(``);
// Imports. QuantumCircuit is always needed; AerSimulator + NoiseModel
// come along for any backend block. Detailed qlib imports are emitted
// inline in each step's body so unused steps don't leave dead imports.
const imports = new Set<string>(["from qiskit import QuantumCircuit"]);
const hasBackend = blocks.some(
(b) => b.kind === "fake_backend" || b.kind === "ibm_backend",
);
if (hasBackend) {
imports.add("from qiskit_aer import AerSimulator");
imports.add("from qiskit_aer.noise import NoiseModel");
}
lines.push([...imports].sort().join("\n"));
lines.push(``);
const sep = `# ${"─".repeat(60)}`;
const ctx: EmitContext = { sampleKey };
blocks.forEach((b, i) => {
const stepNum = i + 1;
const emitter = EMITTERS[b.kind];
if (!emitter) return; // Plugin / unknown — skip silently.
lines.push(sep);
lines.push(`# Step ${stepNum}: ${STEP_TITLES[b.kind] ?? b.kind}`);
lines.push(...emitter(b, stepNum, ctx));
lines.push(``);
});
// Footer
lines.push(`# ${"─".repeat(60)}`);
lines.push(`# End of exported pipeline`);
lines.push(`# To run: python pipeline.py`);
lines.push(`# Make sure qlib/ is on your PYTHONPATH (or run from the backend/ dir)`);
return lines.join("\n");
}
|