dense-evolution 8.3.0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. dashboard_core/__init__.py +115 -0
  2. dashboard_core/_gate_tables.py +30 -0
  3. dashboard_core/band_structure.py +71 -0
  4. dashboard_core/circuit_builder_component.py +232 -0
  5. dashboard_core/circuit_diagram.py +216 -0
  6. dashboard_core/crypto_protocols.py +77 -0
  7. dashboard_core/engine.py +326 -0
  8. dashboard_core/graphical_builder.py +114 -0
  9. dashboard_core/hamiltonians.py +593 -0
  10. dashboard_core/mass_decomposition_tool.py +47 -0
  11. dashboard_core/mitigation.py +343 -0
  12. dashboard_core/native_hf_diagnostics.py +62 -0
  13. dashboard_core/noise_tools.py +125 -0
  14. dashboard_core/qasm_library.py +233 -0
  15. dashboard_core/qmmm.py +16 -0
  16. dashboard_core/rag_tool.py +45 -0
  17. dashboard_core/state_visuals.py +288 -0
  18. dashboard_core/system_limits.py +60 -0
  19. dashboard_core/vector_healing.py +102 -0
  20. dashboard_core/visuals.py +158 -0
  21. dashboard_core/vqe.py +533 -0
  22. dashboard_core/wormhole.py +580 -0
  23. dense_evolution/__init__.py +114 -0
  24. dense_evolution/autodiff.py +10 -0
  25. dense_evolution/backends/__init__.py +5 -0
  26. dense_evolution/backends/chunk/__init__.py +37 -0
  27. dense_evolution/backends/chunk/_engine_imports.py +57 -0
  28. dense_evolution/backends/chunk/circuit_chunker.py +55 -0
  29. dense_evolution/backends/chunk/core.py +432 -0
  30. dense_evolution/backends/chunk/disk_overflow.py +232 -0
  31. dense_evolution/backends/chunk/geometry.py +95 -0
  32. dense_evolution/backends/chunk/guard.py +190 -0
  33. dense_evolution/backends/chunk/kernels.py +531 -0
  34. dense_evolution/backends/mps.py +1569 -0
  35. dense_evolution/backends/statevector.py +616 -0
  36. dense_evolution/chunk.py +25 -0
  37. dense_evolution/circuits/__init__.py +20 -0
  38. dense_evolution/circuits/compiler.py +488 -0
  39. dense_evolution/circuits/diagram.py +94 -0
  40. dense_evolution/circuits/gates.py +91 -0
  41. dense_evolution/circuits/parser.py +632 -0
  42. dense_evolution/circuits/qft.py +66 -0
  43. dense_evolution/circuits/random_circuit.py +85 -0
  44. dense_evolution/circuits/registry.py +74 -0
  45. dense_evolution/circuits/topology.py +79 -0
  46. dense_evolution/circuits/trotter.py +265 -0
  47. dense_evolution/circuits/uccsd.py +275 -0
  48. dense_evolution/cli.py +199 -0
  49. dense_evolution/compiler.py +9 -0
  50. dense_evolution/config.py +49 -0
  51. dense_evolution/drawing.py +10 -0
  52. dense_evolution/entropy.py +9 -0
  53. dense_evolution/fermions.py +9 -0
  54. dense_evolution/gates.py +9 -0
  55. dense_evolution/harrison_tb.py +16 -0
  56. dense_evolution/healing.py +18 -0
  57. dense_evolution/interop/__init__.py +18 -0
  58. dense_evolution/interop/qiskit_pennylane.py +406 -0
  59. dense_evolution/measurement.py +10 -0
  60. dense_evolution/mitigation/__init__.py +54 -0
  61. dense_evolution/mitigation/healing.py +215 -0
  62. dense_evolution/mitigation/kl_divergence.py +93 -0
  63. dense_evolution/mitigation/magic_entropy.py +163 -0
  64. dense_evolution/mitigation/magic_entropy_shadows.py +262 -0
  65. dense_evolution/mitigation/renyi.py +168 -0
  66. dense_evolution/mitigation/stabilizer_renyi_entropy.py +103 -0
  67. dense_evolution/mitigation/zne.py +990 -0
  68. dense_evolution/mps.py +9 -0
  69. dense_evolution/native_hf/__init__.py +26 -0
  70. dense_evolution/native_hf/_libcint/LICENSE-libcint +10 -0
  71. dense_evolution/native_hf/_libcint/libdecint.dll +0 -0
  72. dense_evolution/native_hf/assembly.py +304 -0
  73. dense_evolution/native_hf/basis.py +117 -0
  74. dense_evolution/native_hf/boys.py +35 -0
  75. dense_evolution/native_hf/bridge.py +112 -0
  76. dense_evolution/native_hf/cartesian.py +64 -0
  77. dense_evolution/native_hf/coulomb.py +196 -0
  78. dense_evolution/native_hf/differentiable.py +53 -0
  79. dense_evolution/native_hf/gaussians.py +79 -0
  80. dense_evolution/native_hf/kinetic.py +52 -0
  81. dense_evolution/native_hf/libcint_bridge.py +167 -0
  82. dense_evolution/native_hf/overlap.py +91 -0
  83. dense_evolution/native_hf/scf.py +404 -0
  84. dense_evolution/noise/__init__.py +79 -0
  85. dense_evolution/noise/coherent_attack.py +264 -0
  86. dense_evolution/noise/cosmic_ray.py +61 -0
  87. dense_evolution/noise/density_matrix_channels.py +78 -0
  88. dense_evolution/noise/differentiable.py +66 -0
  89. dense_evolution/noise/kraus/__init__.py +6 -0
  90. dense_evolution/noise/kraus/amplitude_damping.py +47 -0
  91. dense_evolution/noise/kraus/bitflip.py +22 -0
  92. dense_evolution/noise/kraus/combined.py +16 -0
  93. dense_evolution/noise/kraus/depolarizing.py +47 -0
  94. dense_evolution/noise/kraus/ideal.py +10 -0
  95. dense_evolution/noise/kraus/phaseflip.py +21 -0
  96. dense_evolution/noise/kraus_channels.py +285 -0
  97. dense_evolution/noise/oscillating.py +32 -0
  98. dense_evolution/noise/pink.py +80 -0
  99. dense_evolution/observables.py +11 -0
  100. dense_evolution/parser.py +9 -0
  101. dense_evolution/physics/__init__.py +27 -0
  102. dense_evolution/physics/entropy.py +161 -0
  103. dense_evolution/physics/fermions.py +322 -0
  104. dense_evolution/physics/observables.py +523 -0
  105. dense_evolution/physics/qec.py +1113 -0
  106. dense_evolution/physics/spectral.py +143 -0
  107. dense_evolution/physics/states.py +43 -0
  108. dense_evolution/protocols/__init__.py +27 -0
  109. dense_evolution/protocols/bb84.py +133 -0
  110. dense_evolution/protocols/di_qkd_ghz.py +199 -0
  111. dense_evolution/protocols/dicka_protocol2.py +124 -0
  112. dense_evolution/qec.py +20 -0
  113. dense_evolution/qft.py +9 -0
  114. dense_evolution/qmmm/__init__.py +13 -0
  115. dense_evolution/qmmm/ase_bridge.py +97 -0
  116. dense_evolution/qmmm/forces.py +388 -0
  117. dense_evolution/qmmm/propagation.py +80 -0
  118. dense_evolution/qmmm/region.py +137 -0
  119. dense_evolution/random_circuit.py +15 -0
  120. dense_evolution/registry.py +9 -0
  121. dense_evolution/simulator.py +10 -0
  122. dense_evolution/solvers/__init__.py +19 -0
  123. dense_evolution/solvers/autodiff.py +169 -0
  124. dense_evolution/solvers/harrison_tb.py +189 -0
  125. dense_evolution/solvers/vhd_tb.py +187 -0
  126. dense_evolution/states.py +9 -0
  127. dense_evolution/topology.py +9 -0
  128. dense_evolution/trotter.py +9 -0
  129. dense_evolution/utils/__init__.py +13 -0
  130. dense_evolution/utils/drawing.py +101 -0
  131. dense_evolution/utils/mass_decomposition.py +246 -0
  132. dense_evolution/utils/measurement.py +94 -0
  133. dense_evolution/vhd_tb.py +16 -0
  134. dense_evolution-8.3.0.dist-info/METADATA +366 -0
  135. dense_evolution-8.3.0.dist-info/RECORD +165 -0
  136. dense_evolution-8.3.0.dist-info/WHEEL +5 -0
  137. dense_evolution-8.3.0.dist-info/entry_points.txt +2 -0
  138. dense_evolution-8.3.0.dist-info/licenses/license.md +58 -0
  139. dense_evolution-8.3.0.dist-info/top_level.txt +5 -0
  140. ia_utils/__init__.py +0 -0
  141. ia_utils/adversarial_vector_attack.py +196 -0
  142. ia_utils/rag.py +288 -0
  143. ia_utils/vector_healing.py +399 -0
  144. local_site/__init__.py +0 -0
  145. local_site/app/__init__.py +0 -0
  146. local_site/app/server.py +1009 -0
  147. mcp_server/__init__.py +0 -0
  148. mcp_server/client.py +324 -0
  149. mcp_server/config.py +32 -0
  150. mcp_server/models.py +347 -0
  151. mcp_server/molecules.py +71 -0
  152. mcp_server/server.py +119 -0
  153. mcp_server/tools/__init__.py +0 -0
  154. mcp_server/tools/chemistry_tools.py +225 -0
  155. mcp_server/tools/circuit_tools.py +83 -0
  156. mcp_server/tools/crypto_tools.py +66 -0
  157. mcp_server/tools/mitigation_tools.py +81 -0
  158. mcp_server/tools/noise_tools.py +60 -0
  159. mcp_server/tools/retrieval_tools.py +44 -0
  160. mcp_server/tools/system_tools.py +149 -0
  161. mcp_server/tools/wormhole_tools.py +142 -0
  162. mcp_server/utils/__init__.py +0 -0
  163. mcp_server/utils/cache.py +55 -0
  164. mcp_server/utils/images.py +67 -0
  165. mcp_server/utils/truncation.py +38 -0
@@ -0,0 +1,632 @@
1
+ import ast
2
+ import operator
3
+ import re
4
+ from typing import List, Dict, Optional, Tuple
5
+ from dataclasses import dataclass, field
6
+ import numpy as np
7
+
8
+
9
+ # ─────────────────────────────────────────────────────────────────────────────
10
+ # Data model
11
+ # ─────────────────────────────────────────────────────────────────────────────
12
+
13
+ @dataclass
14
+ class QASMCircuit:
15
+ """
16
+ Parsed representation of an OpenQASM 2.0 / 3.0 circuit.
17
+
18
+ Attributes
19
+ ----------
20
+ n_qubits : total qubit count declared in qreg / qubit statements
21
+ n_cbits : total classical bit count declared in creg / bit statements
22
+ ops : list of gate dicts — each dict has keys:
23
+ 'type' : 'gate'
24
+ 'name' : lowercase gate name (aliases resolved)
25
+ 'qubits' : list[int] — absolute qubit indices
26
+ 'params' : list[float] — evaluated rotation angles
27
+ """
28
+ n_qubits: int = 0
29
+ n_cbits: int = 0
30
+ ops: List[Dict] = field(default_factory=list)
31
+
32
+ def to_tuples(self) -> List[Tuple]:
33
+ """
34
+ Convert ops to the tuple format expected by DenseSVSimulator.run_circuit:
35
+ `(name, qubit0, [qubit1, ...], [param0, ...])`
36
+
37
+ BUG FIX (original): the original returned
38
+ (name,) + tuple(qubits) + tuple(params)
39
+ which placed params *after* qubits, but run_circuit expects
40
+ params interleaved or trailing depending on gate type.
41
+ For the standard (name, qubit, param) convention used throughout
42
+ the simulator, this ordering is correct — preserved here but
43
+ documented explicitly so callers know what to expect.
44
+ """
45
+ out = []
46
+ for op in self.ops:
47
+ row = (op['name'],) + tuple(op['qubits']) + tuple(op['params'])
48
+ out.append(row)
49
+ return out
50
+
51
+ def __iter__(self):
52
+ """Duck-type as an iterable of the same tuples to_tuples() returns,
53
+ so a QASMCircuit works anywhere a plain circuit list is expected
54
+ (QuantumTranspiler.transpile, Chunk.run_chunk, ...) without the
55
+ caller having to remember to call .to_tuples() first. Verified this
56
+ was a real gap, not a hypothetical one: `for cmd in circuit` inside
57
+ QuantumTranspiler.transpile — reached via Chunk.run_chunk(circuit)
58
+ — raised `TypeError: 'QASMCircuit' object is not iterable` when
59
+ handed a QASMCircuit straight from QASMParser().parse(), instead of
60
+ circuit.to_tuples()."""
61
+ return iter(self.to_tuples())
62
+
63
+
64
+ # ─────────────────────────────────────────────────────────────────────────────
65
+ # Parser
66
+ # ─────────────────────────────────────────────────────────────────────────────
67
+
68
+ class QASMParser:
69
+ """
70
+ Robust OpenQASM 2.0 / 3.0 parser.
71
+
72
+ Supported features
73
+ ------------------
74
+ - qreg / creg (QASM 2.0)
75
+ - qubit / bit (QASM 3.0)
76
+ - Parametric gates: rx, ry, rz, p, u1, u2, u3, cp, crz, ...
77
+ - Compound parameter expressions: pi/2, sqrt(2), cos(0.3), ...
78
+ - Block comments /* ... */ and line comments // ...
79
+ - Gate aliases: cu1→cp, u1→p, toffoli→ccx, cnot→cx, ...
80
+ - Range syntax q[0:3] expanded to individual qubits
81
+ - Bare register name (no index) resolved to qubit 0 of that register
82
+ - Silent fallback (0.0) for unparseable parameter expressions
83
+ """
84
+
85
+ # ── compiled regexes ────────────────────────────────────────────
86
+ _RE_BLOCK_CMT = re.compile(r'/\*.*?\*/', re.DOTALL)
87
+ _RE_LINE_CMT = re.compile(r'//[^\n]*')
88
+ _RE_INDEX = re.compile(r'\[(\d+)\]')
89
+ _RE_RANGE = re.compile(r'^([a-zA-Z_]\w*)\[(\d+):(\d+)\]$') # q[0:3]
90
+ _RE_QREG2 = re.compile(r'^qreg\s+([a-zA-Z_]\w*)\s*\[(\d+)\]')
91
+ _RE_CREG2 = re.compile(r'^creg\s+([a-zA-Z_]\w*)\s*\[(\d+)\]')
92
+ _RE_QREG3 = re.compile(r'^qubit(?:\s*\[(\d+)\])?\s+([a-zA-Z_]\w*)')
93
+ _RE_CREG3 = re.compile(r'^bit(?:\s*\[(\d+)\])?\s+([a-zA-Z_]\w*)')
94
+ _RE_GATE_HEAD = re.compile(r'^([a-zA-Z_]\w*)(?:\((.*)\))?$')
95
+
96
+ # QASM 3.0 `for <type> <var> in [start:end] {` — range is INCLUSIVE
97
+ # of `end` per the OpenQASM 3 spec (unlike this parser's own q[a:b]
98
+ # qubit-range syntax, which is exclusive — a separate feature).
99
+ _RE_FOR_HEAD = re.compile(
100
+ r'for\s+(?:\w+\s+)?(\w+)\s+in\s*\[\s*([^\]]+?)\s*:\s*([^\]]+?)\s*\]\s*\{')
101
+ _RE_BLOCK_HEAD = re.compile(r'\b(for|if|while|def|gate)\b[^{]*\{')
102
+ _RE_INT_DECL = re.compile(
103
+ r'(?:const\s+)?int(?:\s*\[\d+\])?\s+(\w+)\s*=\s*(-?\d+)\s*;')
104
+
105
+ # ── gate name aliases ────────────────────────────────────────────
106
+ _ALIAS: Dict[str, str] = {
107
+ 'cu1': 'cp',
108
+ 'u1': 'p',
109
+ 'toffoli': 'ccx',
110
+ 'fredkin': 'cswap',
111
+ 'cnot': 'cx',
112
+ 'not': 'x',
113
+ 'id': 'i',
114
+ 'cx': 'cx', # explicit identity mappings for safety
115
+ 'cz': 'cz',
116
+ 'ccx': 'ccx',
117
+ }
118
+
119
+ # ── gate names that only ever take one qubit ─────────────────────
120
+ # Used to expand range syntax (q[0:3]) into one op per qubit instead
121
+ # of a single op with multiple qubits attached — see BUG FIX 3 note
122
+ # on parse(): the original fix resolved q[0:3] to the qubit list
123
+ # [0,1,2], but nothing expanded that list into separate applications
124
+ # for gates that are only ever single-qubit, so e.g. `h q[0:3]` ended
125
+ # up applying H to qubit 0 only, silently dropping qubits 1 and 2.
126
+ _SINGLE_QUBIT_GATES = frozenset((
127
+ 'h', 'x', 'y', 'z', 's', 'sdg', 't', 'tdg', 'sx', 'id',
128
+ 'rx', 'ry', 'rz', 'p', 'u1', 'u2', 'u3',
129
+ ))
130
+
131
+ # ── statements to skip entirely ──────────────────────────────────
132
+ # BUG FIX (original): 'gate ' had a trailing space making it miss
133
+ # 'gate foo(...)' where the token is 'gate' followed by space.
134
+ # Using startswith on lowercased tokens is correct but the original
135
+ # also skipped 'def ' and 'for ' which are QASM 3.0 keywords —
136
+ # kept here for forward compatibility.
137
+ _SKIP = frozenset((
138
+ 'openqasm', 'include', 'barrier', 'measure',
139
+ 'reset', 'gate', 'def', 'if', 'for', 'while',
140
+ ))
141
+
142
+ # ── safe math environment for the AST-based expression evaluator ────
143
+ # No '__builtins__' entry and no raw 'np' module reference (either one
144
+ # would still be reachable via attribute access in a naive eval() —
145
+ # see _eval_ast_node's docstring for why this environment alone was
146
+ # never actually what made the old eval() call safe).
147
+ _MATH_ENV: Dict = {
148
+ 'pi': np.pi,
149
+ 'tau': 2.0 * np.pi,
150
+ 'euler': np.e,
151
+ 'sin': np.sin, 'cos': np.cos, 'tan': np.tan,
152
+ 'sqrt': np.sqrt, 'exp': np.exp, 'log': np.log,
153
+ 'asin': np.arcsin,'acos': np.arccos,'atan': np.arctan,
154
+ 'arcsin': np.arcsin,'arccos': np.arccos,'arctan': np.arctan,
155
+ 'abs': abs, 'round': round,
156
+ }
157
+
158
+ # ── operators allowed in the AST expression evaluator ────────────
159
+ _BINOPS = {
160
+ ast.Add: operator.add, ast.Sub: operator.sub,
161
+ ast.Mult: operator.mul, ast.Div: operator.truediv,
162
+ ast.Pow: operator.pow, ast.Mod: operator.mod,
163
+ }
164
+ _UNARYOPS = {ast.UAdd: operator.pos, ast.USub: operator.neg}
165
+
166
+ # ────────────────────────────────────────────────────────────────
167
+ # Public interface
168
+ # ────────────────────────────────────────────────────────────────
169
+
170
+ def _find_matching_brace(self, s: str, open_idx: int) -> Optional[int]:
171
+ """Return the index of the '}' matching s[open_idx] == '{', or None
172
+ if unbalanced. Counter-based — no regex, handles nesting correctly."""
173
+ depth = 0
174
+ for i in range(open_idx, len(s)):
175
+ if s[i] == '{':
176
+ depth += 1
177
+ elif s[i] == '}':
178
+ depth -= 1
179
+ if depth == 0:
180
+ return i
181
+ return None
182
+
183
+ def _collect_int_declarations(self, s: str) -> Dict[str, int]:
184
+ """Map QASM3 `int n = 3;` / `const int n = 3;` declarations to their
185
+ literal value, so `for` bounds like `n-1` can be resolved."""
186
+ return {name: int(val) for name, val in self._RE_INT_DECL.findall(s)}
187
+
188
+ def _eval_ast_node(self, node, env: Dict):
189
+ """
190
+ Evaluate a Python expression AST node against an explicit node-type
191
+ whitelist — never eval()/exec(). Only literals, +-*/%** arithmetic,
192
+ unary +/-, and Name/Call lookups restricted to `env` are handled;
193
+ anything else (Attribute, Subscript, comprehensions, lambda, ...)
194
+ falls through to the final `raise` and is rejected.
195
+
196
+ This exists because `eval(tok, {'__builtins__': {}})` — the
197
+ previous implementation — does NOT stop attribute/dunder traversal
198
+ of the live object graph: `().__class__.__bases__[0].__subclasses__()`
199
+ needs no builtin name at all, and from there any class loaded in
200
+ the process (including ones whose __globals__ reference `os`) is
201
+ reachable. Verified directly: that exact expression, passed as a
202
+ gate parameter through the public QASMParser.parse() entry point,
203
+ executed successfully and returned a real value before this fix.
204
+ An AST whitelist makes that structurally impossible — an
205
+ `ast.Attribute` node is never one of the cases handled below, so
206
+ `.` in an expression always ends in the rejection branch.
207
+ """
208
+ if isinstance(node, ast.Expression):
209
+ return self._eval_ast_node(node.body, env)
210
+ if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
211
+ return node.value
212
+ if isinstance(node, ast.BinOp) and type(node.op) in self._BINOPS:
213
+ return self._BINOPS[type(node.op)](
214
+ self._eval_ast_node(node.left, env),
215
+ self._eval_ast_node(node.right, env))
216
+ if isinstance(node, ast.UnaryOp) and type(node.op) in self._UNARYOPS:
217
+ return self._UNARYOPS[type(node.op)](self._eval_ast_node(node.operand, env))
218
+ if isinstance(node, ast.Name) and node.id in env and not callable(env[node.id]):
219
+ return env[node.id]
220
+ if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
221
+ and node.func.id in env and callable(env[node.func.id])
222
+ and not node.keywords):
223
+ args = [self._eval_ast_node(a, env) for a in node.args]
224
+ return env[node.func.id](*args)
225
+ raise ValueError(f"disallowed expression node: {type(node).__name__}")
226
+
227
+ def _resolve_int_expr(self, expr: str, decls: Dict[str, int]) -> Optional[int]:
228
+ """Resolve a `for`-bound expression (literal int, or a declared int
229
+ variable combined with +/-/*// arithmetic) to a concrete int.
230
+ Returns None if the expression isn't a safe, resolvable integer
231
+ expression — callers then treat the loop as unrollable-unresolved."""
232
+ expr = expr.strip()
233
+ for name, val in decls.items():
234
+ expr = re.sub(r'\b' + re.escape(name) + r'\b', str(val), expr)
235
+ try:
236
+ tree = ast.parse(expr, mode='eval')
237
+ return int(self._eval_ast_node(tree, {}))
238
+ except Exception:
239
+ return None
240
+
241
+ def _process_block_constructs(self, s: str) -> str:
242
+ """
243
+ Pre-process `for` / `if` / `while` / `def` / `gate` blocks BEFORE the
244
+ statement-level `split(';')` in parse() ever sees them.
245
+
246
+ These are brace-delimited, not `;`-terminated, so leaving them for
247
+ the naive splitter corrupts whatever statement follows the block on
248
+ the same line (the closing '}' merges into the next real statement).
249
+ `gate` matters beyond QASM3: OpenQASM 2.0 exporters (e.g. Qiskit's
250
+ `qiskit.qasm2.dumps` for composite gates like `mcx`) emit a `gate
251
+ NAME params { ... }` definition on a single line, so this hits real
252
+ QASM2 circuits too, not just QASM3 control-flow syntax.
253
+
254
+ - `for <type> <var> in [start:end] { body }` with resolvable
255
+ integer bounds (literals, or `int`/`const int` variables declared
256
+ earlier in the source) is unrolled: `var` is substituted into
257
+ `body` for each value in range(start, end+1) — QASM3 `for`-ranges
258
+ are INCLUSIVE of the end bound (unlike this parser's own
259
+ exclusive `q[a:b]` qubit-range syntax).
260
+ - `for` loops with unresolvable bounds, and all `if`/`while`/`def`
261
+ blocks (no static execution — would need runtime classical bit
262
+ state), are simply removed, leaving the rest of the source intact.
263
+ - `gate` definitions are removed too — their body uses the gate's
264
+ own formal parameter names, not real qubit indices, so it can't
265
+ be executed directly; a later call site referencing that gate
266
+ name still falls through as an unrecognized gate (silent no-op,
267
+ same as any other unknown gate name elsewhere in this codebase),
268
+ but no longer corrupts the qubit/statement that follows it.
269
+
270
+ Runs as a search/replace loop rather than recursion: after an outer
271
+ block is unrolled, any inner (nested) blocks are duplicated as raw
272
+ text into the result and get picked up on a later iteration of the
273
+ same loop, so nesting is handled without extra bookkeeping.
274
+ """
275
+ decls = self._collect_int_declarations(s)
276
+ while True:
277
+ m = self._RE_BLOCK_HEAD.search(s)
278
+ if not m:
279
+ break
280
+ keyword = m.group(1).lower()
281
+ open_brace = m.end() - 1
282
+ close_brace = self._find_matching_brace(s, open_brace)
283
+ if close_brace is None:
284
+ # Unbalanced braces — bail out rather than loop forever;
285
+ # leftover text falls through to the existing _SKIP path.
286
+ break
287
+ header = s[m.start():open_brace]
288
+ body = s[open_brace + 1:close_brace]
289
+ replacement = ''
290
+ if keyword == 'for':
291
+ fm = self._RE_FOR_HEAD.search(header + '{')
292
+ if fm:
293
+ var, start_e, end_e = fm.group(1), fm.group(2), fm.group(3)
294
+ start_v = self._resolve_int_expr(start_e, decls)
295
+ end_v = self._resolve_int_expr(end_e, decls)
296
+ if start_v is not None and end_v is not None:
297
+ var_re = re.compile(r'\b' + re.escape(var) + r'\b')
298
+ parts = [var_re.sub(str(i), body)
299
+ for i in range(start_v, end_v + 1)]
300
+ replacement = ' '.join(parts)
301
+ # unresolved `for`, and all `if`/`while`/`def` blocks, collapse
302
+ # to '' (replacement stays empty) — stripped, not corrupting.
303
+ s = s[:m.start()] + replacement + s[close_brace + 1:]
304
+ return s
305
+
306
+ def parse(self, qasm_str: str) -> QASMCircuit:
307
+ """
308
+ Parse an OpenQASM 2.0 or 3.0 string into a QASMCircuit.
309
+
310
+ BUG FIX 1 (original): the original joined all lines with a single
311
+ space then split on ';'. Multi-line gate definitions (gate foo ...)
312
+ were not stripped before joining, causing 'gate foo ...' to appear
313
+ as a runnable instruction. Fixed by stripping comments *before*
314
+ joining and by using the frozenset _SKIP check on the first token.
315
+
316
+ BUG FIX 2 (original): bare register names (e.g. 'h q' instead of
317
+ 'h q[0]') were silently dropped if the register had more than one
318
+ qubit, because qubit_map only stored 'name[0]' → 0 for size-1
319
+ registers. Fixed: bare names always map to qubit 0 of that register
320
+ regardless of register size.
321
+
322
+ BUG FIX 3 (original): range syntax q[0:3] was never handled —
323
+ such tokens fell through to the digit-extraction fallback which
324
+ returned only the last digit. Fixed in _resolve_qubits.
325
+ """
326
+ qubit_map: Dict[str, int] = {}
327
+ cbit_map: Dict[str, int] = {}
328
+ n_qubits = 0
329
+ n_cbits = 0
330
+ ops: List[Dict] = []
331
+
332
+ # ── strip comments ───────────────────────────────────────────
333
+ cleaned = self._RE_BLOCK_CMT.sub(' ', qasm_str)
334
+ cleaned = self._RE_LINE_CMT.sub(' ', cleaned)
335
+
336
+ # ── unroll for-loops / strip if-while-def blocks ────────────────
337
+ # Must run before the ';'-split below: brace-delimited blocks are
338
+ # not single ';'-terminated statements, and left alone they corrupt
339
+ # whatever real statement follows them on the same line.
340
+ cleaned = self._process_block_constructs(cleaned)
341
+
342
+ # ── split into statements ─────────────────────────────────────
343
+ statements = [s.strip() for s in cleaned.split(';') if s.strip()]
344
+
345
+ for instr in statements:
346
+ # collapse internal whitespace runs to a single space
347
+ instr = re.sub(r'\s+', ' ', instr).strip()
348
+ if not instr:
349
+ continue
350
+
351
+ # first token (before any space or '(') for keyword detection
352
+ first_token = re.split(r'[\s(]', instr)[0].lower()
353
+ if first_token in self._SKIP:
354
+ continue
355
+
356
+ # ── qreg (QASM 2.0) ─────────────────────────────────────
357
+ m = self._RE_QREG2.match(instr)
358
+ if m:
359
+ reg_name, sz = m.group(1), int(m.group(2))
360
+ for i in range(sz):
361
+ qubit_map[f'{reg_name}[{i}]'] = n_qubits + i
362
+ qubit_map[reg_name] = n_qubits # bare name → first qubit
363
+ n_qubits += sz
364
+ continue
365
+
366
+ # ── creg (QASM 2.0) ─────────────────────────────────────
367
+ m = self._RE_CREG2.match(instr)
368
+ if m:
369
+ reg_name, sz = m.group(1), int(m.group(2))
370
+ for i in range(sz):
371
+ cbit_map[f'{reg_name}[{i}]'] = n_cbits + i
372
+ cbit_map[reg_name] = n_cbits
373
+ n_cbits += sz
374
+ continue
375
+
376
+ # ── qubit (QASM 3.0) ─────────────────────────────────────
377
+ m = self._RE_QREG3.match(instr)
378
+ if m:
379
+ sz_s, reg_name = m.group(1), m.group(2)
380
+ sz = int(sz_s) if sz_s else 1
381
+ for i in range(sz):
382
+ qubit_map[f'{reg_name}[{i}]'] = n_qubits + i
383
+ qubit_map[reg_name] = n_qubits
384
+ n_qubits += sz
385
+ continue
386
+
387
+ # ── bit (QASM 3.0) ───────────────────────────────────────
388
+ m = self._RE_CREG3.match(instr)
389
+ if m:
390
+ sz_s, reg_name = m.group(1), m.group(2)
391
+ sz = int(sz_s) if sz_s else 1
392
+ for i in range(sz):
393
+ cbit_map[f'{reg_name}[{i}]'] = n_cbits + i
394
+ cbit_map[reg_name] = n_cbits
395
+ n_cbits += sz
396
+ continue
397
+
398
+ # ── gate application ─────────────────────────────────────
399
+ op = self._parse_gate(instr, qubit_map)
400
+ if op is not None:
401
+ if op['name'] in self._SINGLE_QUBIT_GATES and len(op['qubits']) > 1:
402
+ # range syntax on an inherently single-qubit gate
403
+ # (e.g. `h q[0:3]`) — expand into one op per qubit.
404
+ for q in op['qubits']:
405
+ ops.append({
406
+ 'type': op['type'], 'name': op['name'],
407
+ 'qubits': [q], 'params': list(op['params']),
408
+ })
409
+ n_qubits = max(n_qubits, q + 1)
410
+ else:
411
+ ops.append(op)
412
+ # update n_qubits from seen qubit indices
413
+ # (handles circuits without explicit qreg declarations)
414
+ if op['qubits']:
415
+ n_qubits = max(n_qubits, max(op['qubits']) + 1)
416
+
417
+ return QASMCircuit(n_qubits, n_cbits, ops)
418
+
419
+ def validate(self, circ: QASMCircuit) -> Tuple[bool, str]:
420
+ """Light structural validation — does not verify gate semantics."""
421
+ if circ.n_qubits <= 0:
422
+ return False, 'n_qubits must be > 0.'
423
+ if not circ.ops:
424
+ return False, 'No gate operations found in circuit.'
425
+ # check for out-of-range qubit references
426
+ for i, op in enumerate(circ.ops):
427
+ for q in op.get('qubits', []):
428
+ if not (0 <= q < circ.n_qubits):
429
+ return False, (
430
+ f"Gate '{op['name']}' at op[{i}] references "
431
+ f"qubit {q} but n_qubits={circ.n_qubits}.")
432
+ return True, 'OK'
433
+
434
+ # ────────────────────────────────────────────────────────────────
435
+ # Private helpers
436
+ # ────────────────────────────────────────────────────────────────
437
+
438
+ def _parse_gate(self,
439
+ instr: str,
440
+ qubit_map: Dict[str, int]) -> Optional[Dict]:
441
+ """
442
+ Parse a single gate instruction into an op dict.
443
+
444
+ BUG FIX 4 (original): the original code had two independent
445
+ code paths for extracting param_str — one using _RE_GATE_HEAD
446
+ and one rescanning for '(' — that could disagree, leaving
447
+ param_str as the group(2) of an earlier (shorter) match while
448
+ paren_start/paren_end referred to a different range. Unified
449
+ into a single pass that:
450
+ 1. finds the parameter parentheses (balanced),
451
+ 2. extracts everything before '(' as the gate name,
452
+ 3. extracts everything after the closing ')' as the qubit list.
453
+
454
+ BUG FIX 5 (original): split_at was found by scanning for the
455
+ first space at depth==0 *in the whole instruction*, so for
456
+ rx(pi/2) q[0]
457
+ split_at was -1 (no space outside parens in 'rx(pi/2)') and
458
+ rest was '' — dropping the qubit entirely. Fixed by splitting
459
+ on the space after the closing ')'.
460
+ """
461
+ instr = instr.strip()
462
+
463
+ # ── locate parameter block '(...)' ───────────────────────────
464
+ paren_open = instr.find('(')
465
+ paren_close = -1
466
+ param_str = ''
467
+
468
+ if paren_open != -1:
469
+ depth = 0
470
+ for idx in range(paren_open, len(instr)):
471
+ if instr[idx] == '(':
472
+ depth += 1
473
+ elif instr[idx] == ')':
474
+ depth -= 1
475
+ if depth == 0:
476
+ paren_close = idx
477
+ break
478
+ if paren_close == -1:
479
+ # Unbalanced parentheses — skip this instruction
480
+ return None
481
+ param_str = instr[paren_open + 1 : paren_close].strip()
482
+ # gate_head = everything before '(', qubit_part = everything after ')'
483
+ gate_head = instr[:paren_open].strip()
484
+ qubit_part = instr[paren_close + 1:].strip()
485
+ else:
486
+ # No parameters: split on first whitespace
487
+ parts = instr.split(None, 1)
488
+ gate_head = parts[0]
489
+ qubit_part = parts[1] if len(parts) > 1 else ''
490
+
491
+ gate_name_raw = gate_head.strip().lower()
492
+ if not gate_name_raw:
493
+ return None
494
+
495
+ gate_name = self._ALIAS.get(gate_name_raw, gate_name_raw)
496
+
497
+ # ── parse parameters ─────────────────────────────────────────
498
+ params: List[float] = []
499
+ if param_str:
500
+ for tok in self._split_params(param_str):
501
+ tok = tok.strip()
502
+ if not tok:
503
+ continue
504
+ params.append(self._eval_param(tok))
505
+
506
+ # ── resolve qubits ───────────────────────────────────────────
507
+ qubits = self._resolve_qubits(
508
+ qubit_part.replace(' ', ''), qubit_map)
509
+
510
+ if not qubits:
511
+ return None
512
+
513
+ return {
514
+ 'type': 'gate',
515
+ 'name': gate_name,
516
+ 'qubits': qubits,
517
+ 'params': params,
518
+ }
519
+
520
+ def _eval_param(self, tok: str) -> float:
521
+ """
522
+ Evaluate a parameter token to float via the AST whitelist evaluator
523
+ (_eval_ast_node) — never eval()/exec(). See _eval_ast_node's
524
+ docstring for why a raw eval() here was a real code-execution
525
+ vulnerability (attribute/dunder traversal bypasses
526
+ `{'__builtins__': {}}` entirely), fixed in this version.
527
+
528
+ Handles: numeric literals, pi, pi/2, sqrt(2), cos(0.3), etc.
529
+ Raises ValueError on anything else — malformed expressions (e.g.
530
+ 'pi * / 2') and disallowed/malicious expressions alike. Used to
531
+ silently return 0.0 on any evaluation error instead; that hid a
532
+ typo as a *different, valid* circuit (rx(0) instead of an error)
533
+ with no signal anything was wrong — the same class of
534
+ silent-wrong-behavior issue already fixed for unknown gate names
535
+ and mismatched parameter batches (issues #4/#6).
536
+ """
537
+ try:
538
+ tree = ast.parse(tok, mode='eval')
539
+ return float(self._eval_ast_node(tree, self._MATH_ENV))
540
+ except Exception as e:
541
+ raise ValueError(f"Invalid gate parameter expression '{tok}': {e}") from e
542
+
543
+ @staticmethod
544
+ def _split_params(s: str) -> List[str]:
545
+ """
546
+ Split a comma-separated parameter string respecting nested
547
+ parentheses. e.g. 'pi/2, atan(1,0)' → ['pi/2', 'atan(1,0)']
548
+ """
549
+ tokens: List[str] = []
550
+ cur: List[str] = []
551
+ depth = 0
552
+ for ch in s:
553
+ if ch == '(':
554
+ depth += 1
555
+ cur.append(ch)
556
+ elif ch == ')':
557
+ depth -= 1
558
+ cur.append(ch)
559
+ elif ch == ',' and depth == 0:
560
+ tokens.append(''.join(cur).strip())
561
+ cur = []
562
+ else:
563
+ cur.append(ch)
564
+ if cur:
565
+ tokens.append(''.join(cur).strip())
566
+ return [t for t in tokens if t]
567
+
568
+ def _resolve_qubits(self,
569
+ s: str,
570
+ qmap: Dict[str, int]) -> List[int]:
571
+ r"""
572
+ Resolve a comma-separated qubit argument string to absolute indices.
573
+
574
+ Handles
575
+ -------
576
+ - Indexed: q[0], q[1]
577
+ - Bare: q → qmap['q'] (first qubit of that register)
578
+ - Range: q[0:3] → [qmap['q[0]'], qmap['q[1]'], qmap['q[2]']]
579
+
580
+ BUG FIX 6 (original): range syntax q[0:3] was not handled and
581
+ fell through to the digit-extraction fallback, returning only
582
+ the last number found (e.g., 3 instead of [0,1,2]).
583
+
584
+ BUG FIX 7 (original): the fallback `digits = re.findall(r'\d+', tok)`
585
+ was used as a last resort — this could silently map unknown tokens
586
+ to arbitrary integers. Now the fallback is gated on the absence of
587
+ any letter character to avoid mapping named registers that are simply
588
+ not yet in qmap to wrong indices.
589
+ """
590
+ out: List[int] = []
591
+ for tok in s.split(','):
592
+ tok = tok.strip()
593
+ if not tok:
594
+ continue
595
+
596
+ # ── range syntax: q[start:end] ───────────────────────────
597
+ m = self._RE_RANGE.match(tok)
598
+ if m:
599
+ base = m.group(1)
600
+ start = int(m.group(2))
601
+ end = int(m.group(3)) # exclusive upper bound
602
+ for i in range(start, end):
603
+ key = f'{base}[{i}]'
604
+ if key in qmap:
605
+ out.append(qmap[key])
606
+ continue
607
+
608
+ # ── direct map lookup ─────────────────────────────────────
609
+ if tok in qmap:
610
+ out.append(qmap[tok])
611
+ continue
612
+
613
+ # ── indexed: base[n] ─────────────────────────────────────
614
+ bracket = self._RE_INDEX.search(tok)
615
+ if bracket:
616
+ base = tok[:tok.index('[')]
617
+ key = f'{base}[{bracket.group(1)}]'
618
+ if key in qmap:
619
+ out.append(qmap[key])
620
+ continue
621
+ # index not in map — try numeric fallback
622
+ out.append(int(bracket.group(1)))
623
+ continue
624
+
625
+ # ── bare name not in map: try stripping to digits ─────────
626
+ # Only do this when the token contains no letters (pure numeric)
627
+ # to avoid misidentifying unknown register names.
628
+ digits = re.findall(r'\d+', tok)
629
+ if digits and not re.search(r'[a-zA-Z_]', tok):
630
+ out.append(int(digits[-1]))
631
+
632
+ return out