ErrorMitigation / src /utils /qasm_utils.py
Dvirmor100's picture
style: using black and ruff to format the project
e0d7f28
Raw History Blame Contribute Delete
2.11 kB
import re
from qiskit.qasm2 import loads
def get_qasm_circuit_depth(qasm_str: str) -> int:
"""
Given a QASM circuit string from PennyLane, return the depth of the circuit.
:param qasm_str: The QASM string representation of the circuit.
:return: Depth of the quantum circuit.
"""
try:
qiskit_circuit = loads(fix_qasm(qasm_str))
return qiskit_circuit.depth()
except Exception as e:
print(e)
return -1
def fix_qasm(qasm_code: str) -> str:
fixed_lines = []
for line in qasm_code.splitlines():
# Fix expressions like rx([value]) to rx(value)
fixed_line = re.sub(r"([a-z]+)\(\[(.*?)\]\)", r"\1(\2)", line)
fixed_lines.append(fixed_line)
return remove_measurements(replace_swap_gates("\n".join(fixed_lines)))
def replace_swap_gates(qasm_code: str) -> str:
"""
Replaces all occurrences of `swap` gates in QASM 2.0 with their
equivalent decomposition using CNOT gates.
"""
# Regular expression to match 'swap q[x],q[y];'
swap_pattern = re.compile(r"swap\s+q\[(\d+)\],\s*q\[(\d+)\];")
def swap_replacement(match):
q1, q2 = match.groups()
return f"""
cx q[{q1}], q[{q2}];
cx q[{q2}], q[{q1}];
cx q[{q1}], q[{q2}];
""".strip()
# Replace all swap occurrences in the QASM code
return swap_pattern.sub(swap_replacement, qasm_code)
def remove_measurements(qasm_code: str) -> str:
"""
Removes all lines that start with 'measure' from a given QASM string.
:param qasm_code: The input QASM code as a string.
:return: The QASM code without measurement lines.
"""
cleaned_code = re.sub(r"^measure .*$", "", qasm_code, flags=re.MULTILINE)
return re.sub(r"\n+", "\n", cleaned_code).strip()
def extract_qasm_from_llm_output(text):
# Compile a regex pattern to match content between the markers.
pattern = re.compile(r"<QASM START>(.*?)<QASM END>", re.DOTALL)
matches = pattern.findall(text)
# Return the last match if available, otherwise None.
return matches[-1].strip() if matches else None