File size: 2,112 Bytes
94a1e47
e0d7f28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94a1e47
 
 
 
 
 
 
 
e0d7f28
 
 
94a1e47
 
 
e0d7f28
94a1e47
 
 
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
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