Example #1
0
 def _define(self):
     """Calculate a subcircuit that implements this unitary."""
     if self.num_qubits == 1:
         q = QuantumRegister(1, "q")
         angles = euler_angles_1q(self.to_matrix())
         self.definition = [(U3Gate(*angles), [q[0]], [])]
     elif self.num_qubits == 2:
         self.definition = two_qubit_cnot_decompose(self.to_matrix())
     else:
         raise NotImplementedError("Not able to generate a subcircuit for "
                                   "a {}-qubit unitary".format(self.num_qubits))
    def build_model_circuit_kak(width, depth, seed=None):
        """Create quantum volume model circuit on quantum register qreg of given
        depth (default depth is equal to width) and random seed.
        The model circuits consist of layers of Haar random
        elements of U(4) applied between corresponding pairs
        of qubits in a random bipartition.
        """
        qreg = QuantumRegister(width)
        depth = depth or width

        np.random.seed(seed)
        circuit = QuantumCircuit(qreg,
                                 name="Qvolume: %s by %s, seed: %s" %
                                 (width, depth, seed))

        for _ in range(depth):
            # Generate uniformly random permutation Pj of [0...n-1]
            perm = np.random.permutation(width)

            # For each pair p in Pj, generate Haar random U(4)
            # Decompose each U(4) into CNOT + SU(2)
            for k in range(width // 2):
                U = random_unitary(4, seed).data
                for gate in two_qubit_cnot_decompose(U):
                    qs = [qreg[int(perm[2 * k + i.index])] for i in gate[1]]
                    pars = gate[0].params
                    name = gate[0].name
                    if name == "cx":
                        circuit.cx(qs[0], qs[1])
                    elif name == "u1":
                        circuit.u1(pars[0], qs[0])
                    elif name == "u2":
                        circuit.u2(*pars[:2], qs[0])
                    elif name == "u3":
                        circuit.u3(*pars[:3], qs[0])
                    elif name == "id":
                        pass  # do nothing
                    else:
                        raise Exception("Unexpected gate name: %s" % name)
        return circuit
Example #3
0
}  # dictionary to hold counts for quantum simulation
yse = {
    '00': [],
    '01': [],
    '10': [],
    '11': []
}  # dictionary to hold classically calculated values for comparison

start = time.time()
for i, t in enumerate(ts):

    M = sp.linalg.expm(-1j * H * t)  # create time evolution operator
    st = M.dot(np.array([1, 0, 0, 0]))  # apply operator to vacuum state
    cr = ClassicalRegister(2,
                           'c' + str(i))  # create and name classical register
    qc = two_qubit_cnot_decompose(
        M)  # decompose time evolution operator into quantum gates
    qc.add_register(cr)  # add classical register to circuit
    qc.measure([0, 1], [0, 1])  # add measurement gate
    result = execute(qc, backend, shots=shots).result()  # simulate
    counts = result.get_counts(qc)  # get results
    for i, state in enumerate(ys.keys()):  # populate dictionaries
        yse[state].append(np.linalg.norm(st[i])**2)
        try:
            ys[state].append(counts[state] / shots)
        except KeyError:
            ys[state].append(0)

print("Quantum walk finished in {0} seconds.".format(time.time() - start))

qc.draw(output='latex', plot_barriers=False,
        filename='2q_walk_circuit.png')  # draw circuit
Example #4
0
def Vk(k, q0, q1):
    print("Executing Vk")
    e = exp(1j * (math.pi / k))
    e2 = exp(1j * (math.pi / (2 * k)))
    f = 1 / math.sqrt(e.real + 1)
    u11 = 1 / math.sqrt(2)
    u13 = math.sqrt(e.real)
    u14 = e / math.sqrt(2)
    u21 = 1 / math.sqrt(2)
    u23 = -math.sqrt(e.real) * exp(-1j * (math.pi / k))
    u24 = exp(-1j * (math.pi / k)) / math.sqrt(2)
    u31 = math.sqrt(e.real)
    u33 = (exp(-1j * (math.pi /
                      (2 * k))) * e.imag) / (1j * math.sqrt(2) * e2.real)
    u34 = -math.sqrt(e.real)
    u42 = math.sqrt(e.real + 1)
    matrix_to_decompose = np.array(
        [[u11 * f, 0, u13 * f, u14 * f], [u21 * f, 0, u23 * f, u24 * f],
         [u31 * f, 0, u33 * f, u34 * f], [0, u42 * f, 0, 0]],
        dtype=complex)
    circuit = two_qubit_cnot_decompose(matrix_to_decompose)
    i = 0
    while i < len(circuit):
        if circuit[i]['name'] == 'u1':
            lambd = float(circuit[i]['params'][2])
            q_num = int(circuit[i]['args'][0])
            step = int(lambd * 256 / (2 * math.pi))
            if step > 255:
                step -= 255
            if q_num == 0:
                q0.rot_Z(step)
            else:
                q1.rot_Z(step)
        elif circuit[i]['name'] == 'u3':
            theta = float(circuit[i]['params'][0])
            phi = float(circuit[i]['params'][1])
            lambd = float(circuit[i]['params'][2])
            q_num = int(circuit[i]['args'][0])
            #to_print = "theta = {}, phi = {}, lambd = {}".format(theta, phi, lambd)
            #print(to_print)
            step1 = int((phi + (3 * math.pi)) * 256 / (2 * math.pi))
            step2 = int((math.pi / 2) * 256 / (2 * math.pi))
            step3 = int((theta + math.pi) * 256 / (2 * math.pi))
            step4 = int((math.pi / 2) * 256 / (2 * math.pi))
            step5 = int(lambd * 256 / (2 * math.pi))
            if step1 > 255:
                step1 -= 255
            if step2 > 255:
                step2 -= 255
            if step3 > 255:
                step3 -= 255
            if step4 > 255:
                step4 -= 255
            if step5 > 255:
                step5 -= 255
            if q_num == 0:
                q0.rot_Z(step1)
                q0.rot_X(step2)
                q0.rot_Z(step3)
                q0.rot_X(step4)
                q0.rot_Z(step5)
            else:
                q1.rot_Z(step1)
                q1.rot_X(step2)
                q1.rot_Z(step3)
                q1.rot_X(step4)
                q1.rot_Z(step5)
        elif circuit[i]['name'] == 'cx':
            control_qubit = int(circuit[i]['args'][0])
            target_qubit = int(circuit[i]['args'][1])
            if control_qubit == 0:
                q0.cnot(q1)
            else:
                q1.cnot(q0)
        i += 1
    return