示例#1
0
def get_hhl_2x2(A, b, r, qubits):
    '''Generate a circuit that implements the full HHL algorithm for the case
    of 2x2 matrices.

    :param A: (numpy.ndarray) A Hermitian 2x2 matrix.
    :param b: (numpy.ndarray) A vector.
    :param r: (float) Parameter to be tuned in the algorithm.
    :param verbose: (bool) Optional information about the wavefunction.

    :return: A Quil program to perform HHL.
    '''
    p = pq.Program()
    p.inst(create_arbitrary_state(b, [qubits[3]]))
    p.inst(H(qubits[1]))
    p.inst(H(qubits[2]))
    p.defgate('CONTROLLED-U0', controlled(scipy.linalg.expm(2j*π*A/4)))
    p.inst(('CONTROLLED-U0', qubits[2], qubits[3]))
    p.defgate('CONTROLLED-U1', controlled(scipy.linalg.expm(2j*π*A/2)))
    p.inst(('CONTROLLED-U1', qubits[1], qubits[3]))
    p.inst(SWAP(qubits[1], qubits[2]))
    p.inst(H(qubits[2]))
    p.defgate('CSdag', controlled(np.array([[1, 0], [0, -1j]])))
    p.inst(('CSdag', qubits[1], qubits[2]))
    p.inst(H(qubits[1]))
    p.inst(SWAP(qubits[1], qubits[2]))
    uncomputation = p.dagger()
    p.defgate('CRy0', controlled(rY(2*π/2**r)))
    p.inst(('CRy0', qubits[1], qubits[0]))
    p.defgate('CRy1', controlled(rY(π/2**r)))
    p.inst(('CRy1', qubits[2], qubits[0]))
    p += uncomputation
    return p
示例#2
0
    def get_program_inversion(self, program):
        # =============================================
        # Inversion
        # =============================================
        # add hadamards
        program += H(self.first)
        program += H(self.second)

        # add the exponent gates
        expF = expm(np.pi * 1j * self.F)
        expF = self.controlMake(expF)
        program = program.defgate("expF", expF)
        program.inst(("expF", self.first, self.y))

        expFhalf = expm(np.pi / 2. * 1j * self.F)
        expFhalf = self.controlMake(expFhalf)
        program = program.defgate("expFhalf", expFhalf)
        program.inst(("expFhalf", self.second, self.y))

        program += SWAP(self.first, self.second)
        program += H(self.second)

        #S inverse
        program += CPHASE(-np.pi / 2, self.second,
                          self.first)  # right order of qubits?

        program += H(self.first)

        CRYpi4 = self.CRY(np.pi / 4.)
        program = program.defgate("CRYpi4", CRYpi4)
        program.inst(("CRYpi4", self.second, self.anc))

        CRYpi8 = self.CRY(np.pi / 8.)
        program = program.defgate("CRYpi8", CRYpi8)
        program.inst(("CRYpi8", self.first, self.anc))

        program += H(self.first)

        program += CPHASE(np.pi / 2, self.second,
                          self.first)  # right order of qubits?

        program += H(self.second)

        program += SWAP(self.first, self.second)

        minusExpFhalf = expm(-np.pi / 2. * 1j * self.F)
        minusExpFhalf = self.controlMake(minusExpFhalf)
        program = program.defgate("minusExpFhalf", minusExpFhalf)
        program.inst(("minusExpFhalf", self.second, self.y))

        minusExpF = expm(-np.pi * 1j * self.F)
        minusExpF = self.controlMake(minusExpF)
        program = program.defgate("minusExpF", minusExpF)
        program.inst(("minusExpF", self.second, self.y))

        program += H(self.first)
        program += H(self.second)

        return program
示例#3
0
def test_SWAP():
    u1 = program_unitary(Program(SWAP(0, 1)), n_qubits=2)
    u2 = program_unitary(_SWAP(0, 1), n_qubits=2)
    assert equal_up_to_global_phase(u1, u2, atol=1e-12)

    u1 = program_unitary(Program(SWAP(1, 0)), n_qubits=2)
    u2 = program_unitary(_SWAP(1, 0), n_qubits=2)
    assert equal_up_to_global_phase(u1, u2, atol=1e-12)
示例#4
0
def test_gradient_program():
    f_h = 0.25
    precision = 2

    trial_prog = gradient_program(f_h, precision)

    result_prog = pq.Program([H(0), H(1)])

    phase_factor = np.exp(-1.0j * 2 * np.pi * abs(f_h))
    U = np.array([[phase_factor, 0], [0, phase_factor]])
    q_out = range(precision, precision + 1)
    for i in range(precision):
        if i > 0:
            U = np.dot(U, U)
        cU = controlled(U)
        name = "CONTROLLED-U{0}".format(2**i)
        result_prog.defgate(name, cU)
        result_prog.inst((name, i) + tuple(q_out))

    result_prog.inst([
        H(1),
        CPHASE(1.5707963267948966, 0, 1),
        H(0),
        SWAP(0, 1),
        MEASURE(0, [0]),
        MEASURE(1, [1])
    ])

    assert (trial_prog == result_prog)
示例#5
0
 def qft3(q0, q1, q2):
     p = Program()
     p.inst(H(q2),
            CPHASE(pi / 2.0)(q1, q2), H(1),
            CPHASE(pi / 4.0)(q0, q2),
            CPHASE(pi / 2.0)(q0, q1), H(q0), SWAP(q0, q2))
     return p
示例#6
0
def test_to_latex():
    """A test to give full coverage of latex_generation."""
    p = Program()
    p.inst(
        X(0),
        RX(1.0, 5),
        Y(0),
        CZ(0, 2),
        SWAP(0, 1),
        MEASURE(0, None),
        CNOT(2, 0),
        X(0).controlled(1),
        Y(0).dagger(),
    )
    _ = to_latex(p)

    # Modify settings to access non-standard control paths.
    settings = DiagramSettings(impute_missing_qubits=True)
    _ = to_latex(p, settings)

    settings = DiagramSettings(abbreviate_controlled_rotations=True)
    _ = to_latex(p, settings)

    settings = DiagramSettings(label_qubit_lines=False)
    _ = to_latex(p, settings)
示例#7
0
def _core_sycamore_circuit(reg: List[int], depth: int) -> Program:
    """
    Generates the core program to perform an approximation of the Sycamore chip benchmark
    
    :param qubits: A list of qubit indexes.
    :param depth: Benchmark circuit depth
    :return: A Quil program to perform an approximation of the Sycamore chip benchmark
    """

    num_qubits = len(reg)
    gateSequence = [0, 3, 2, 1, 2, 1, 0, 3]
    single_bit_gates = sqrtx, sqrty, H  # H should actually be sqrth
    circ = []

    lastSingleBitGates = []

    colLen = math.floor(math.sqrt(num_qubits))
    while (((num_qubits / colLen) * colLen) != num_qubits):
        colLen = colLen - 1
    rowLen = num_qubits // colLen

    for i in range(depth):
        # Single bit gates
        singleBitGates = []
        for j in range(num_qubits):
            gate = random.choice(single_bit_gates)
            if len(lastSingleBitGates) > 0:
                while gate == lastSingleBitGates[j]:
                    gate = random.choice(single_bit_gates)
            circ.append(gate(reg[j]))
            singleBitGates.append(gate)

        lastSingleBitGates = singleBitGates

        gate = gateSequence[0]
        gateSequence.pop(0)
        gateSequence.append(gate)

        for row in range(1, rowLen, 2):
            for col in range(0, colLen):
                tempRow = row
                tempCol = col

                tempRow = tempRow + (1 if (gate & 2) else -1)
                if colLen != 1:
                    tempCol = tempCol + (1 if (gate & 1) else 0)

                if (tempRow < 0) or (tempCol < 0) or (tempRow >= rowLen) or (
                        tempCol >= colLen):
                    continue

                b1 = row * colLen + col
                b2 = tempRow * colLen + tempCol

                # Two bit gates
                circ.append(CPHASE(math.pi / 6, reg[b1], reg[b2]))
                circ.append(SWAP(reg[b1], reg[b2]))

    return circ
示例#8
0
def test_dagger():
    # these gates are their own inverses
    p = Program().inst(I(0), X(0), Y(0), Z(0),
                       H(0), CNOT(0, 1), CCNOT(0, 1, 2),
                       SWAP(0, 1), CSWAP(0, 1, 2))
    assert p.dagger().out() == 'CSWAP 0 1 2\nSWAP 0 1\n' \
                               'CCNOT 0 1 2\nCNOT 0 1\nH 0\n' \
                               'Z 0\nY 0\nX 0\nI 0\n'

    # these gates require negating a parameter
    p = Program().inst(PHASE(pi, 0), RX(pi, 0), RY(pi, 0),
                       RZ(pi, 0), CPHASE(pi, 0, 1),
                       CPHASE00(pi, 0, 1), CPHASE01(pi, 0, 1),
                       CPHASE10(pi, 0, 1), PSWAP(pi, 0, 1))
    assert p.dagger().out() == 'PSWAP(-pi) 0 1\n' \
                               'CPHASE10(-pi) 0 1\n' \
                               'CPHASE01(-pi) 0 1\n' \
                               'CPHASE00(-pi) 0 1\n' \
                               'CPHASE(-pi) 0 1\n' \
                               'RZ(-pi) 0\n' \
                               'RY(-pi) 0\n' \
                               'RX(-pi) 0\n' \
                               'PHASE(-pi) 0\n'

    # these gates are special cases
    p = Program().inst(S(0), T(0), ISWAP(0, 1))
    assert p.dagger().out() == 'PSWAP(pi/2) 0 1\n' \
                               'RZ(pi/4) 0\n' \
                               'PHASE(-pi/2) 0\n'

    # must invert defined gates
    G = np.array([[0, 1], [0 + 1j, 0]])
    p = Program().defgate("G", G).inst(("G", 0))
    assert p.dagger().out() == 'DEFGATE G-INV:\n' \
                               '    0.0, -i\n' \
                               '    1.0, 0.0\n\n' \
                               'G-INV 0\n'

    # can also pass in a list of inverses
    inv_dict = {"G": "J"}
    p = Program().defgate("G", G).inst(("G", 0))
    assert p.dagger(inv_dict=inv_dict).out() == 'J 0\n'

    # defined parameterized gates cannot auto generate daggered version https://github.com/rigetticomputing/pyquil/issues/304
    theta = Parameter('theta')
    gparam_matrix = np.array([[quil_cos(theta / 2), -1j * quil_sin(theta / 2)],
                             [-1j * quil_sin(theta / 2), quil_cos(theta / 2)]])
    g_param_def = DefGate('GPARAM', gparam_matrix, [theta])
    p = Program(g_param_def)
    with pytest.raises(TypeError):
        p.dagger()

    # defined parameterized gates should passback parameters https://github.com/rigetticomputing/pyquil/issues/304
    GPARAM = g_param_def.get_constructor()
    p = Program(GPARAM(pi)(1, 2))
    assert p.dagger().out() == 'GPARAM-INV(pi) 1 2\n'
示例#9
0
def get_hhl_2x2_corrected(A, b, r, qubits):
    """ HHL program with bit code corrections on first two H gates """
    p = pq.Program()
    p.inst(create_arbitrary_state(b, [qubits[3]]))
    
    # PHASE ESTIMATION
    bit_code_H(p, qubits[1], qubits)  
    bit_code_H(p, qubits[2], qubits)    
    p.defgate('CONTROLLED-U0', controlled(scipy.linalg.expm(2j*π*A/4)))
    p.inst(('CONTROLLED-U0', qubits[2], qubits[3]))
    p.defgate('CONTROLLED-U1', controlled(scipy.linalg.expm(2j*π*A/2)))
    p.inst(('CONTROLLED-U1', qubits[1], qubits[3]))
    p.inst(SWAP(qubits[1], qubits[2]))
    p.inst(H(qubits[2]))
    p.defgate('CSdag', controlled(np.array([[1, 0], [0, -1j]])))
    p.inst(('CSdag', qubits[1], qubits[2]))
    p.inst(H(qubits[1]))
    p.inst(SWAP(qubits[1], qubits[2]))

    p.defgate('CRy0', controlled(rY(2*π/2**r)))
    p.inst(('CRy0', qubits[1], qubits[0]))
    p.defgate('CRy1', controlled(rY(π/2**r)))
    p.inst(('CRy1', qubits[2], qubits[0]))
    
    # HARD CODE THE INVERSE PHASE ESTIMATION :'(
    p.inst(SWAP(qubits[1], qubits[2]))
    p.inst(H(qubits[1]))
    p.defgate('CSdag-INV', controlled(np.array([[1, 0], [0, 1j]])))
    p.inst(('CSdag-INV', qubits[1], qubits[2]))
    p.inst(H(qubits[2]))
    p.inst(SWAP(qubits[1], qubits[2]))
    p.defgate('CONTROLLED-U1-INV', controlled(scipy.linalg.expm(-2j*π*A/2)))
    p.inst(('CONTROLLED-U1-INV', qubits[1], qubits[3]))
    p.defgate('CONTROLLED-U0-INV', controlled(scipy.linalg.expm(-2j*π*A/4)))
    p.inst(('CONTROLLED-U0-INV', qubits[2], qubits[3]))    
    p.inst(H(qubits[2]))
    p.inst(H(qubits[1]))

    # undoes create_arbitrary_state
    p.inst(RY(π/2, qubits[3]))
    p.inst(H(qubits[3]))
    return p
示例#10
0
文件: fourier.py 项目: dklink/quantum
def bit_reversal(qubits):
    """
    Generate a circuit to do bit reversal.
    :param qubits: Qubits to do bit reversal with.
    :return: A program to do bit reversal.
    """
    p = pq.Program()
    n = len(qubits)
    for i in range(int(n / 2)):
        p.inst(SWAP(qubits[i], qubits[-i - 1]))
    return p
示例#11
0
def test_simple():
    qc = get_qc("3q-qvm")

    # |0, 0, 0>  -->  |+, 0, 1>
    pq = Program(H(0), X(1), SWAP(1, 2))
    true_amplitudes = np.array([0, 1, 0, 0, 0, 1, 0, 0]) / np.sqrt(2)

    rho_est = qdb.Qdb(qc, pq).do_tomography("0 1 2")

    amplitudes = np.array([wf[i] for i in range(2 ** len(wf))])
    assert np.allclose(true_amplitudes, amplitudes)
示例#12
0
def inverse_qft_2q(qubits):

    prog = Program()

    prog += SWAP(0, 1)
    # QFT is unitary, thus the inverse QFT contains reversed order of gates
    # with complex conjugate in CPHASE
    prog += H(0)
    prog += CPHASE(-math.pi / 2, 0, 1)
    prog += H(1)

    return prog
示例#13
0
def test_multi_qubit_qft():
    trial_prog = Program()
    trial_prog.inst(X(0), X(1), X(2))
    trial_prog = trial_prog + inverse_qft([0, 1, 2])
    
    result_prog = Program().inst([X(0), X(1), X(2),
                                     SWAP(0, 2), H(0),
                                     CPHASE(-1.5707963267948966, 0, 1),
                                     CPHASE(-0.7853981633974483, 0, 2),
                                     H(1), CPHASE(-1.5707963267948966, 1, 2),
                                     H(2)])
    
    assert trial_prog == result_prog
示例#14
0
def reverse_qubits(qubits, order=1):
    """
    Generates a quil programm to reverse given qubits.
    
    :param qubits: List of qubits indexes to do reversal with.
    :param order: Specifies the ordering of instractions. 
                Set dir=1 for normal ordering and -1 for reverse.
    
    :returns: A quil program to do a bit reversal of given qubits.
    """
    p = Program()
    l = len(qubits)
    for i in range(l / 2)[::order]:
        p.inst(SWAP(qubits[i], qubits[-i - 1]))

    return p
示例#15
0
def test_to_latex():
    """A test to give full coverage of latex_generation and latex_config."""
    qubits = range(3)
    p = Program()
    p.inst(X(qubits[0]), Y(qubits[0]), CZ(qubits[0], qubits[2]),
           SWAP(qubits[0], qubits[1]), MEASURE(qubits[0], None),
           CNOT(qubits[2], qubits[0]))
    _ = to_latex(p)

    # Modify settings to access non-standard control paths.
    settings = get_default_settings()
    settings['gates']['AllocateQubitGate']['draw_id'] = True
    settings['gate_shadow'] = None
    _ = to_latex(p, settings)

    settings['control']['shadow'] = True
    _ = to_latex(p, settings)
示例#16
0
def QFT3():  # pylint: disable=invalid-name
    """ Returns the Quantum Fourier Transform of 3 qubits
        pyquil circuit"""
    prog = Program()
    ro = prog.declare("ro", memory_size=3)
    prog += [
        SWAP(0, 2),
        H(0),
        CPHASE(-pi / 2.0, 0, 1),
        H(1),
        CPHASE(-pi / 4.0, 0, 2),
        CPHASE(-pi / 2.0, 1, 2),
        H(2),
    ]

    prog.measure(0, ro[0])
    prog.measure(1, ro[1])
    prog.measure(2, ro[2])
    return prog
示例#17
0
    def run_quantum(self, vec_query, mes_anc=True, mes_rep=True):
        """
        @brief Run the quantum SVM to classify a given query
        @param vec_query: query vector. 
        @return wavefunction after run
        """

        self.theta0 = calc_theta(vec_query)

        self.program = self.get_program_inversion(self.program)
        self.program = self.get_program_oracle(self.program)
        self.program = self.get_program_u(self.program)

        # =============================================
        # MEASUREMENT
        # =============================================

        self.program += SWAP(self.first, self.anc)
        if mes_anc:
            self.program += MEASURE(self.anc, 0)

        if self.verb_print_program:
            print("Pyquil program: \n", self.program)

        # only return, if ancilla measured 1 (a little hacky by amplitues)
        while True:
            wavefunction = (self.qvm.wavefunction(self.program))

            if mes_rep:
                # repetitive, conditional readout like on hackathon
                if np.real(wavefunction.amplitudes[0]) == 0 and np.imag(
                        wavefunction.amplitudes[0]) == 0:
                    if self.verb_print_wavefunction:
                        print("Final Wavefunction: " + str(wavefunction))
                        print("Ampl[9] (|1001>): " +
                              str(wavefunction.amplitudes[9]))
                    return wavefunction

            else:
                if self.verb_print_wavefunction:
                    print(wavefunction)
                return wavefunction
示例#18
0
def test_dagger():
    # these gates are their own inverses
    p = Program().inst(I(0), X(0), Y(0), Z(0),
                       H(0), CNOT(0,1), CCNOT(0,1,2),
                       SWAP(0,1), CSWAP(0,1,2))
    assert p.dagger().out() == 'CSWAP 0 1 2\nSWAP 0 1\n' \
                      'CCNOT 0 1 2\nCNOT 0 1\nH 0\n' \
                      'Z 0\nY 0\nX 0\nI 0\n'

    # these gates require negating a parameter
    p = Program().inst(PHASE(pi, 0), RX(pi, 0), RY(pi, 0),
                       RZ(pi, 0), CPHASE(pi, 0, 1),
                       CPHASE00(pi, 0, 1), CPHASE01(pi, 0, 1),
                       CPHASE10(pi, 0, 1), PSWAP(pi, 0, 1))
    assert p.dagger().out() == 'PSWAP(-3.141592653589793) 0 1\n' \
                               'CPHASE10(-3.141592653589793) 0 1\n' \
                               'CPHASE01(-3.141592653589793) 0 1\n' \
                               'CPHASE00(-3.141592653589793) 0 1\n' \
                               'CPHASE(-3.141592653589793) 0 1\n' \
                               'RZ(-3.141592653589793) 0\n' \
                               'RY(-3.141592653589793) 0\n' \
                               'RX(-3.141592653589793) 0\n' \
                               'PHASE(-3.141592653589793) 0\n'

    # these gates are special cases
    p = Program().inst(S(0), T(0), ISWAP(0, 1))
    assert p.dagger().out() == 'PSWAP(1.5707963267948966) 0 1\n' \
                               'RZ(0.7853981633974483) 0\n' \
                               'PHASE(-1.5707963267948966) 0\n'

    # must invert defined gates
    G = np.array([[0, 1], [0+1j, 0]])
    p = Program().defgate("G", G).inst(("G", 0))
    assert p.dagger().out() == 'DEFGATE G-INV:\n' \
                               '    0.0+-0.0i, 0.0-1.0i\n' \
                               '    1.0+-0.0i, 0.0+-0.0i\n\n' \
                               'G-INV 0\n'

    # can also pass in a list of inverses
    inv_dict = {"G":"J"}
    p = Program().defgate("G", G).inst(("G", 0))
    assert p.dagger(inv_dict=inv_dict).out() == 'J 0\n'
示例#19
0
def get_test_program(measure: bool = False) -> Program:
    PI = float(pi.evalf())
    p = Program()
    p += X(0)
    p += Y(1)
    p += Z(2)
    p += H(3)
    p += S(0)
    p += T(1)
    p += RX(PI / 2, 2)
    p += RY(PI / 2, 3)
    p += RZ(PI / 2, 0)
    p += CZ(0, 1)
    p += CNOT(2, 3)
    p += CCNOT(0, 1, 2)
    p += CPHASE(PI / 4, 2, 1)
    p += SWAP(0, 3)
    if measure:
        ro = p.declare("ro", "BIT", 4)
        p += MEASURE(0, ro[0])
        p += MEASURE(3, ro[1])
        p += MEASURE(2, ro[2])
        p += MEASURE(1, ro[3])
    return p
示例#20
0
hhl = Program()

# Quantum phase estimation through superposition
hhl += H(1)
hhl += H(2)

# Controlled-U0
hhl.defgate("CONTROLLED-U0", controlled(scipy.linalg.expm(2j*π*A/4)))
hhl += ("CONTROLLED-U0", 2, 3)

# Controlled-U1
hhl.defgate("CONTROLLED-U1", controlled(scipy.linalg.expm(2j*π*A/2)))
hhl += ("CONTROLLED-U1", 1, 3)

# Inverse quantum inverse Fourier transformation
hhl += SWAP(1, 2)
hhl += H(2)
hhl.defgate("CSdag", controlled(np.array([[1, 0], [0, -1j]])))
hhl += ("CSdag", 1, 2)
hhl += H(1)
hhl += SWAP(1, 2)
uncomputation = hhl.dagger()

def rY(angle):
    """
    Generate a rotation matrix over the Y axis in the Bloch sphere.
    angle is the angle of rotation. 
    """
    return np.array([[np.cos(angle/2), -np.sin(angle/2)],
                     [np.sin(angle/2), np.cos(angle/2)]])
示例#21
0
def test_swaps():
    p = Program(SWAP(0, 1), CSWAP(0, 1, 2), ISWAP(0, 1), PSWAP(np.pi, 0, 1))
    assert p.out() == "SWAP 0 1\nCSWAP 0 1 2\nISWAP 0 1\nPSWAP(pi) 0 1\n"
示例#22
0
x = np.fft.ifft(y, norm='ortho')
print(x)

#==============================================================================
# QFT
#==============================================================================
import math
from pyquil import Program
from pyquil.gates import SWAP, H, CPHASE
from pyquil.api import WavefunctionSimulator

# Initilize program
prog = Program()

# Prepare state
prog = prog.inst(H(0),H(1))
print('Amplitudes a of input state psi: {}'.format(WavefunctionSimulator().wavefunction(prog).amplitudes))

# Perfrom QFT
prog += SWAP(0, 1)
prog += H(1)
prog += CPHASE(math.pi / 2, 0, 1)
prog += H(0)

print('Amplitudes b of output state phi: {}'.format(WavefunctionSimulator().wavefunction(prog).amplitudes))





示例#23
0
    CPHASE(0.04908738521234052, 1, 7),
    CPHASE(0.09817477042468103, 1, 6),
    CPHASE(0.19634954084936207, 1, 5),
    CPHASE(0.39269908169872414, 1, 4),
    CPHASE(0.7853981633974483, 1, 3),
    CPHASE(1.5707963267948966, 1, 2),
    H(1),
    CPHASE(0.02454369260617026, 0, 7),
    CPHASE(0.04908738521234052, 0, 6),
    CPHASE(0.09817477042468103, 0, 5),
    CPHASE(0.19634954084936207, 0, 4),
    CPHASE(0.39269908169872414, 0, 3),
    CPHASE(0.7853981633974483, 0, 2),
    CPHASE(1.5707963267948966, 0, 1),
    H(0),
    SWAP(0, 7),
    SWAP(1, 6),
    SWAP(2, 5),
    SWAP(3, 4),
]

QFT_8_WF_PROBS = [
    0.0625 + 0.0j,
    0.0625 + 0.0j,
    0.0625 + 0.0j,
    0.0625 + 0.0j,
    0.0625 + 0.0j,
    0.0625 + 0.0j,
    0.0625 + 0.0j,
    0.0625 + 0.0j,
    0.0625 + 0.0j,
示例#24
0
    def execute_sabre_algorithm(self, front_layer_gates: list,
                                qubit_mapping: dict,
                                circuit_dag: DiGraph) -> Union[Program, dict]:
        """Applies SABRE algorithm proposed in "Tackling the Qubit Mapping Problem for NISQ-Era Quantum Devices"
            by Gushu Li, Yufei Ding, and Yuan Xie (https://arxiv.org/pdf/1809.02573.pdf). This function returns 
            final program with SWAPs inserted and a mapping with qubit dependencies resolved

        Args:
            front_layer_gates (list): list of gates that have no unexecuted predecessors in the DAG
            qubit_mapping (dict): a dictionary containing logical to physical qubit mapping
            circuit_dag (DiGraph): a directed acyclic graph where each vertex represents a gate in the 
                                    input circuit and the edges represent the qubit dependencies of a gate on the other

        Returns:
            Union[Program, dict]: final program with SWAPs inserted and a mapping with qubit dependencies resolved
        """
        decay_parameter = self.initialize_decay_parameter(qubit_mapping)
        final_circuit = Program()

        while len(front_layer_gates) > 0:
            execute_gate_list = list()
            for gate_details in front_layer_gates:
                if self.is_gate_executable(gate_details[0], qubit_mapping):
                    execute_gate_list.append(gate_details)
                    decay_parameter = self.initialize_decay_parameter(
                        qubit_mapping)

            if len(execute_gate_list) > 0:
                for gate_details in execute_gate_list:
                    front_layer_gates.remove(gate_details)
                    final_circuit.inst(gate_details[0])
                    for successor_details in circuit_dag.successors(
                            gate_details):
                        dependency_found = self.is_dependent_on_successors(
                            successor_details, front_layer_gates)
                        if not dependency_found:
                            front_layer_gates.append(successor_details)
            else:
                for gate_details in front_layer_gates:
                    heuristic_score = dict()
                    swap_candidate_list = list()
                    f_gate = gate_details[0]
                    f_qubits = list(f_gate.get_qubits())
                    control_logical_qubit, target_logical_qubit = f_qubits[
                        0], f_qubits[1]
                    control_logical_qubit_neighbours, target_logical_qubit_neighbours = self.get_qubit_neighbours(
                        control_logical_qubit, target_logical_qubit,
                        qubit_mapping)
                    for control_logical_qubit_neighbour in control_logical_qubit_neighbours:
                        swap_candidate_list.append(
                            SWAP(control_logical_qubit,
                                 control_logical_qubit_neighbour))
                    for target_logical_qubit_neighbour in target_logical_qubit_neighbours:
                        swap_candidate_list.append(
                            SWAP(target_logical_qubit,
                                 target_logical_qubit_neighbour))
                    for swap_gate in swap_candidate_list:
                        temp_mapping = self.update_initial_mapping(
                            swap_gate, qubit_mapping)
                        swap_gate_score = heuristic_function(
                            front_layer_gates, circuit_dag, temp_mapping,
                            self.distance_matrix, swap_gate, decay_parameter)
                        heuristic_score.update({swap_gate: swap_gate_score})
                    min_score_swap_gate = self.find_min_score_swap_gate(
                        heuristic_score, swap_candidate_list)
                    final_circuit.inst(min_score_swap_gate)
                    qubit_mapping = self.update_initial_mapping(
                        min_score_swap_gate, qubit_mapping)
                    decay_parameter = self.update_decay_parameter(
                        min_score_swap_gate, decay_parameter)
        return final_circuit, qubit_mapping
示例#25
0
def test_swaps():
    p = Program(SWAP(0, 1), CSWAP(0, 1, 2), ISWAP(0, 1), PSWAP(np.pi)(0, 1))
    assert p.out(
    ) == 'SWAP 0 1\nCSWAP 0 1 2\nISWAP 0 1\nPSWAP(3.141592653589793) 0 1\n'
print("Probability that after measurement the system is in state 10 {}".format(abs(state.amplitudes[2])**2))
print("Probability that after measurement the system is in state 11 {}".format(abs(state.amplitudes[3])**2))

#==============================================================================
# Quantum gates
#==============================================================================
from pyquil.gates import X
prog.inst(X(0))

# Print current quantum state of the system
state = WavefunctionSimulator().wavefunction(prog)
print("The system is in state: {}".format(state))

# Swap gate
from pyquil.gates import SWAP
prog.inst(SWAP(1, 0))

# Print current quantum state of the system
state = WavefunctionSimulator().wavefunction(prog)
print("The system is in state: {}".format(state))

# Hadamard gate
from pyquil.gates import H
prog.inst(H(1))

# Print current quantum state of the system
state = WavefunctionSimulator().wavefunction(prog)
print("The system is in state: {}".format(state))

#==============================================================================
# Measurment
示例#27
0
文件: MUSIQu.py 项目: kangruix/MUSIQu
def QFT(q0, q1, q2):
    for i in range(0, len(states)):
        states[i] = states[i] + Program().inst(
            H(q2), CPHASE(pi / 2.0, q1, q2), H(q1), CPHASE(pi / 4.0, q0, q2),
            CPHASE(pi / 2.0, q0, q1), H(q0), SWAP(q0, q2))
示例#28
0
def test_standard_gates():
    parse_equals("H 0", H(0))
    parse_equals("CNOT 0 1", CNOT(0, 1))
    parse_equals("SWAP 0 1", SWAP(0, 1))