def qc_approx_sim(x, t1, t2): theta1 = x - t1; theta2 = x - t2; q = QuantumRegister(2, 'q') c = ClassicalRegister(2, 'c') qc = QuantumCircuit(q, c) qc.h( q[0] ) qc.h( q[1] ) qc.u3(t1, 0.0, 0.0, q[0]); qc.u3(t2, 0.0, 0.0, q[1]); qc.barrier( q ) #qc.measure(q,c) qc.measure( q[0], c[0] ) qc.measure( q[1], c[1] ) job = execute(qc, backend, shots=1024) rslt = job.result() #counts = rslt.get_counts(qc) #print(counts) outputstate = rslt.get_statevector( qc, decimals=13 ) #print(outputstate) qval = outputstate; return qval;
def trial_circuit_computational(n, state, meas_string = None, measurement = True): """Trial function for classical optimization problems. n = number of qubits state = a bit string for the state prepared. meas_string = the pauli to be measured measurement = true/false if measurement is to be done """ q = QuantumRegister("q", n) c = ClassicalRegister("c", n) trial_circuit = QuantumCircuit(q, c) if meas_string is None: meas_string = [None for x in range(n)] if len(state) == n: for j in range(n): if state[n-j-1] == "1": trial_circuit.x(q[j]) trial_circuit.barrier(q) for j in range(n): if meas_string[j] == 'X': trial_circuit.h(q[j]) elif meas_string[j] == 'Y': trial_circuit.s(q[j]).inverse() trial_circuit.h(q[j]) if measurement: for j in range(n): trial_circuit.measure(q[j], c[j]) return trial_circuit
class TestStandard3Q(StandardExtensionTest): """Standard Extension Test. Gates with three Qubits""" def setUp(self): self.q = QuantumRegister(3, "q") self.r = QuantumRegister(3, "r") self.s = QuantumRegister(3, "s") self.c = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.q, self.r, self.s, self.c) self.c_header = 80 # lenght of the header def test_barrier_None(self): self.circuit.barrier() qasm_txt = 'barrier q[0],q[1],q[2],r[0],r[1],r[2],s[0],s[1],s[2];' self.assertResult(Barrier, qasm_txt, qasm_txt) def test_ccx_reg_reg_reg(self): qasm_txt = 'ccx q[0],r[0],s[0];\nccx q[1],r[1],s[1];\nccx q[2],r[2],s[2];' instruction_set = self.circuit.ccx(self.q, self.r, self.s) self.assertStmtsType(instruction_set.instructions, ToffoliGate) self.assertQasm(qasm_txt) def test_ccx_reg_reg_inv(self): qasm_txt = 'ccx q[0],r[0],s[0];\nccx q[1],r[1],s[1];\nccx q[2],r[2],s[2];' instruction_set = self.circuit.ccx(self.q, self.r, self.s).inverse() self.assertStmtsType(instruction_set.instructions, ToffoliGate) self.assertQasm(qasm_txt) def test_cswap_reg_reg_reg(self): qasm_txt = 'cswap q[0],r[0],s[0];\n' \ 'cswap q[1],r[1],s[1];\n' \ 'cswap q[2],r[2],s[2];' instruction_set = self.circuit.cswap(self.q, self.r, self.s) self.assertStmtsType(instruction_set.instructions, FredkinGate) self.assertQasm(qasm_txt) def test_cswap_reg_reg_inv(self): qasm_txt = 'cswap q[0],r[0],s[0];\n' \ 'cswap q[1],r[1],s[1];\n' \ 'cswap q[2],r[2],s[2];' instruction_set = self.circuit.cswap(self.q, self.r, self.s).inverse() self.assertStmtsType(instruction_set.instructions, FredkinGate) self.assertQasm(qasm_txt)
def trial_circuit_ryrz(n, m, theta, entangler_map, meas_string=None, measurement=True): """Creates a QuantumCircuit object ocnsisting in layers of parametrized single-qubit Y and Z rotations and CZ two-qubit gates Args: n (int) : number of qubits m (int) : depth of the circuit theta array[float] : angles that parametrize the Y and Z rotations entangler_map : CZ connectivity, e.g. {0: [1], 1: [2]} meas_string (str) : measure a given Pauli operator at the end of the circuit measurement (bool) : whether to measure the qubit (register "q") on classical bits (register "c") Returns: A QuantumCircuit object """ q = QuantumRegister("q", n) c = ClassicalRegister("c", n) trial_circuit = QuantumCircuit(q, c) trial_circuit.h(q) if meas_string is None: meas_string = [None for x in range(n)] for i in range(m): trial_circuit.barrier(q) for node in entangler_map: for j in entangler_map[node]: trial_circuit.cz(q[node], q[j]) for j in range(n): trial_circuit.ry(theta[n * i * 2 + 2 * j], q[j]) trial_circuit.rz(theta[n * i * 2 + 2 * j + 1], q[j]) trial_circuit.barrier(q) for j in range(n): if meas_string[j] == 'X': trial_circuit.h(q[j]) elif meas_string[j] == 'Y': trial_circuit.s(q[j]).inverse() trial_circuit.h(q[j]) if measurement: for j in range(n): trial_circuit.measure(q[j], c[j]) return trial_circuit
def trial_circuit_ryrz(n, m, theta, entangler_map, meas_string = None, measurement = True): """Trial function for classical optimization problems. n = number of qubits m = depth theta = control vector of size n*m*2 stacked as theta[n*i*2+2*j+p] where j counts the qubits and i the depth and p if y and z. entangler_map = {0: [2, 1], 1: [2], 3: [2], 4: [2]} control is the key and values are the target pauli_string = length of number of qubits string """ q = QuantumRegister("q", n) c = ClassicalRegister("c", n) trial_circuit = QuantumCircuit(q, c) trial_circuit.h(q) if meas_string is None: meas_string = [None for x in range(n)] for i in range(m): trial_circuit.barrier(q) for node in entangler_map: for j in entangler_map[node]: trial_circuit.cz(q[node], q[j]) for j in range(n): trial_circuit.ry(theta[n * i * 2 + 2*j], q[j]) trial_circuit.rz(theta[n * i * 2 + 2*j + 1], q[j]) trial_circuit.barrier(q) for j in range(n): if meas_string[j] == 'X': trial_circuit.h(q[j]) elif meas_string[j] == 'Y': trial_circuit.s(q[j]).inverse() trial_circuit.h(q[j]) if measurement: for j in range(n): trial_circuit.measure(q[j], c[j]) return trial_circuit
class CircuitBackend(UnrollerBackend): """Backend for the unroller that produces a QuantumCircuit. By default, basis gates are the QX gates. """ def __init__(self, basis=None): """Setup this backend. basis is a list of operation name strings. """ super().__init__(basis) self.creg = None self.cval = None if basis: self.basis = basis else: self.basis = ["cx", "u1", "u2", "u3"] self.gates = {} self.listen = True self.in_gate = "" self.circuit = QuantumCircuit() def set_basis(self, basis): """Declare the set of user-defined gates to emit. basis is a list of operation name strings. """ self.basis = basis def version(self, version): """Ignore the version string. v is a version number. """ pass def new_qreg(self, name, size): """Create a new quantum register. name = name of the register sz = size of the register """ assert size >= 0, "invalid qreg size" q_register = QuantumRegister(size, name) self.circuit.add(q_register) def new_creg(self, name, size): """Create a new classical register. name = name of the register sz = size of the register """ assert size >= 0, "invalid creg size" c_register = ClassicalRegister(size, name) self.circuit.add(c_register) def define_gate(self, name, gatedata): """Define a new quantum gate. We don't check that the definition and name agree. name is a string. gatedata is the AST node for the gate. """ self.gates[name] = gatedata def _map_qubit(self, qubit): """Map qubit tuple (regname, index) to (QuantumRegister, index).""" qregs = self.circuit.get_qregs() if qubit[0] not in qregs: raise BackendError("qreg %s does not exist" % qubit[0]) return (qregs[qubit[0]], qubit[1]) def _map_bit(self, bit): """Map bit tuple (regname, index) to (ClassicalRegister, index).""" cregs = self.circuit.get_cregs() if bit[0] not in cregs: raise BackendError("creg %s does not exist" % bit[0]) return (cregs[bit[0]], bit[1]) def _map_creg(self, creg): """Map creg name to ClassicalRegister.""" cregs = self.circuit.get_cregs() if creg not in cregs: raise BackendError("creg %s does not exist" % creg) return cregs[creg] def u(self, arg, qubit, nested_scope=None): """Fundamental single qubit gate. arg is 3-tuple of Node expression objects. qubit is (regname,idx) tuple. nested_scope is a list of dictionaries mapping expression variables to Node expression objects in order of increasing nesting depth. """ if self.listen: if "U" not in self.basis: self.basis.append("U") (theta, phi, lam) = list(map(lambda x: x.sym(nested_scope), arg)) this_gate = self.circuit.u_base(theta, phi, lam, self._map_qubit(qubit)) if self.creg is not None: this_gate.c_if(self._map_creg(self.creg), self.cval) def cx(self, qubit0, qubit1): """Fundamental two qubit gate. qubit0 is (regname,idx) tuple for the control qubit. qubit1 is (regname,idx) tuple for the target qubit. """ if self.listen: if "CX" not in self.basis: self.basis.append("CX") this_gate = self.circuit.cx_base(self._map_qubit(qubit0), self._map_qubit(qubit1)) if self.creg is not None: this_gate.c_if(self._map_creg(self.creg), self.cval) def measure(self, qubit, bit): """Measurement operation. qubit is (regname, idx) tuple for the input qubit. bit is (regname, idx) tuple for the output bit. """ if "measure" not in self.basis: self.basis.append("measure") this_op = self.circuit.measure(self._map_qubit(qubit), self._map_bit(bit)) if self.creg is not None: this_op.c_if(self._map_creg(self.creg), self.cval) def barrier(self, qubitlists): """Barrier instruction. qubitlists is a list of lists of (regname, idx) tuples. """ if self.listen: if "barrier" not in self.basis: self.basis.append("barrier") flatlist = map(self._map_qubit, [qubit for qubitlist in qubitlists for qubit in qubitlist]) self.circuit.barrier(*list(flatlist)) def reset(self, qubit): """Reset instruction. qubit is a (regname, idx) tuple. """ if "reset" not in self.basis: self.basis.append("reset") this_op = self.circuit.reset(self._map_qubit(qubit)) if self.creg is not None: this_op.c_if(self._map_creg(self.creg), self.cval) def set_condition(self, creg, cval): """Attach a current condition. creg is a name string. cval is the integer value for the test. """ self.creg = creg self.cval = cval def drop_condition(self): """Drop the current condition.""" self.creg = None self.cval = None def start_gate(self, name, args, qubits, nested_scope=None): """Begin a custom gate. name is name string. args is list of Node expression objects. qubits is list of (regname, idx) tuples. nested_scope is a list of dictionaries mapping expression variables to Node expression objects in order of increasing nesting depth. """ if self.listen and name not in self.basis \ and self.gates[name]["opaque"]: raise BackendError("opaque gate %s not in basis" % name) if self.listen and name in self.basis: self.in_gate = name self.listen = False # Gate names mapped to number of arguments and qubits # and method to invoke on [args, qubits] lut = {"ccx": [(0, 3), lambda x: self.circuit.ccx(x[1][0], x[1][1], x[1][2])], "ch": [(0, 2), lambda x: self.circuit.ch(x[1][0], x[1][1])], "crz": [(1, 2), lambda x: self.circuit.crz(x[0][0], x[1][0], x[1][1])], "cswap": [(0, 3), lambda x: self.circuit.cswap(x[1][0], x[1][1], x[1][2])], "cu1": [(1, 2), lambda x: self.circuit.cu1(x[0][0], x[1][0], x[1][1])], "cu3": [(3, 2), lambda x: self.circuit.cu3(x[0][0], x[0][1], x[0][2], x[1][0], x[1][1])], "cx": [(0, 2), lambda x: self.circuit.cx(x[1][0], x[1][1])], "cy": [(0, 2), lambda x: self.circuit.cy(x[1][0], x[1][1])], "cz": [(0, 2), lambda x: self.circuit.cz(x[1][0], x[1][1])], "swap": [(0, 2), lambda x: self.circuit.swap(x[1][0], x[1][1])], "h": [(0, 1), lambda x: self.circuit.h(x[1][0])], "id": [(0, 1), lambda x: self.circuit.iden(x[1][0])], "rx": [(1, 1), lambda x: self.circuit.rx(x[0][0], x[1][0])], "ry": [(1, 1), lambda x: self.circuit.ry(x[0][0], x[1][0])], "rz": [(1, 1), lambda x: self.circuit.rz(x[0][0], x[1][0])], "s": [(0, 1), lambda x: self.circuit.s(x[1][0])], "sdg": [(0, 1), lambda x: self.circuit.s(x[1][0]).inverse()], "t": [(0, 1), lambda x: self.circuit.t(x[1][0]).inverse()], "tdg": [(0, 1), lambda x: self.circuit.t(x[1][0]).inverse()], "u1": [(1, 1), lambda x: self.circuit.u1(x[0][0], x[1][0])], "u2": [(2, 1), lambda x: self.circuit.u2(x[0][0], x[0][1], x[1][0])], "u3": [(3, 1), lambda x: self.circuit.u3(x[0][0], x[0][1], x[0][2], x[1][0])], "x": [(0, 1), lambda x: self.circuit.x(x[1][0])], "y": [(0, 1), lambda x: self.circuit.y(x[1][0])], "z": [(0, 1), lambda x: self.circuit.z(x[1][0])]} if name not in lut: raise BackendError("gate %s not in standard extensions" % name) gate_data = lut[name] if gate_data[0] != (len(args), len(qubits)): raise BackendError("gate %s signature (%d, %d) is " % (name, len(args), len(qubits)) + "incompatible with the standard " + "extensions") this_gate = gate_data[1]([list(map(lambda x: x.sym(nested_scope), args)), list(map(self._map_qubit, qubits))]) if self.creg is not None: this_gate.c_if(self._map_creg(self.creg), self.cval) def end_gate(self, name, args, qubits, nested_scope=None): """End a custom gate. name is name string. args is list of Node expression objects. qubits is list of (regname, idx) tuples. nested_scope is a list of dictionaries mapping expression variables to Node expression objects in order of increasing nesting depth. """ if name == self.in_gate: self.in_gate = "" self.listen = True def get_output(self): """Return the QuantumCircuit object.""" return self.circuit
# In the following example, we are going to see the projection of a qbit state on the fundamental state $\ket{0}$, when changing the value of $\theta$ from 0 to $2 \pi$, in 50 steps. # In[1]: # example_u3.py import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, execute, Aer # Build the circuits circuits = [] middle = QuantumCircuit(1, 1) meas = QuantumCircuit(1, 1) meas.barrier() meas.measure(0, 0) # I use 50 values of theta exp_vector = range(0, 50) exp_theta = [] theta = 0.0 for exp_index in exp_vector: delta_theta = 2 * np.pi / len(exp_vector) theta = theta + delta_theta exp_theta.append(theta) middle.u3(delta_theta, 0, 0, 0) circuits.append(middle + meas) # In[6]:
def test_mapping_correction(self): """Test mapping works in previous failed case. """ backend = FakeRueschlikon() qr = QuantumRegister(name='qr', size=11) cr = ClassicalRegister(name='qc', size=11) circuit = QuantumCircuit(qr, cr) circuit.u3(1.564784764685993, -1.2378965763410095, 2.9746763177861713, qr[3]) circuit.u3(1.2269835563676523, 1.1932982847014162, -1.5597357740824318, qr[5]) circuit.cx(qr[5], qr[3]) circuit.u1(0.856768317675967, qr[3]) circuit.u3(-3.3911273825190915, 0.0, 0.0, qr[5]) circuit.cx(qr[3], qr[5]) circuit.u3(2.159209321625547, 0.0, 0.0, qr[5]) circuit.cx(qr[5], qr[3]) circuit.u3(0.30949966910232335, 1.1706201763833217, 1.738408691990081, qr[3]) circuit.u3(1.9630571407274755, -0.6818742967975088, 1.8336534616728195, qr[5]) circuit.u3(1.330181833806101, 0.6003162754946363, -3.181264980452862, qr[7]) circuit.u3(0.4885914820775024, 3.133297443244865, -2.794457469189904, qr[8]) circuit.cx(qr[8], qr[7]) circuit.u1(2.2196187596178616, qr[7]) circuit.u3(-3.152367609631023, 0.0, 0.0, qr[8]) circuit.cx(qr[7], qr[8]) circuit.u3(1.2646005789809263, 0.0, 0.0, qr[8]) circuit.cx(qr[8], qr[7]) circuit.u3(0.7517780502091939, 1.2828514296564781, 1.6781179605443775, qr[7]) circuit.u3(0.9267400575390405, 2.0526277839695153, 2.034202361069533, qr[8]) circuit.u3(2.550304293455634, 3.8250017126569698, -2.1351609599720054, qr[1]) circuit.u3(0.9566260876600556, -1.1147561503064538, 2.0571590492298797, qr[4]) circuit.cx(qr[4], qr[1]) circuit.u1(2.1899329069137394, qr[1]) circuit.u3(-1.8371715243173294, 0.0, 0.0, qr[4]) circuit.cx(qr[1], qr[4]) circuit.u3(0.4717053496327104, 0.0, 0.0, qr[4]) circuit.cx(qr[4], qr[1]) circuit.u3(2.3167620677708145, -1.2337330260253256, -0.5671322899563955, qr[1]) circuit.u3(1.0468499525240678, 0.8680750644809365, -1.4083720073192485, qr[4]) circuit.u3(2.4204244021892807, -2.211701932616922, 3.8297006565735883, qr[10]) circuit.u3(0.36660280497727255, 3.273119149343493, -1.8003362351299388, qr[6]) circuit.cx(qr[6], qr[10]) circuit.u1(1.067395863586385, qr[10]) circuit.u3(-0.7044917541291232, 0.0, 0.0, qr[6]) circuit.cx(qr[10], qr[6]) circuit.u3(2.1830003849921527, 0.0, 0.0, qr[6]) circuit.cx(qr[6], qr[10]) circuit.u3(2.1538343756723917, 2.2653381826084606, -3.550087952059485, qr[10]) circuit.u3(1.307627685019188, -0.44686656993522567, -2.3238098554327418, qr[6]) circuit.u3(2.2046797998462906, 0.9732961754855436, 1.8527865921467421, qr[9]) circuit.u3(2.1665254613904126, -1.281337664694577, -1.2424905413631209, qr[0]) circuit.cx(qr[0], qr[9]) circuit.u1(2.6209599970201007, qr[9]) circuit.u3(0.04680566321901303, 0.0, 0.0, qr[0]) circuit.cx(qr[9], qr[0]) circuit.u3(1.7728411151289603, 0.0, 0.0, qr[0]) circuit.cx(qr[0], qr[9]) circuit.u3(2.4866395967434443, 0.48684511243566697, -3.0069186877854728, qr[9]) circuit.u3(1.7369112924273789, -4.239660866163805, 1.0623389015296005, qr[0]) circuit.barrier(qr) circuit.measure(qr, cr) circuits = transpile(circuit, backend) self.assertIsInstance(circuits, QuantumCircuit)
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer import math %matplotlib inline ## Example 2-3: Root-of-not # Set up the program reg = QuantumRegister(1, name='reg') reg_c = ClassicalRegister(1, name='regc') qc = QuantumCircuit(reg, reg_c) qc.reset(reg) # write the value 0 # One root-of-not gate qc.h(reg) qc.rz(math.radians(-90), reg) qc.h(reg) qc.barrier() # One root-of-not gate qc.h(reg) qc.rz(math.radians(-90), reg) qc.h(reg) qc.barrier() backend = BasicAer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() outputstate = result.get_statevector(qc, decimals=3) print(outputstate) qc.draw() # draw the circuit
from qiskit.tools.visualization import plot_histogram from qiskit.tools.monitor import job_monitor IBMQ.load_account() provider = IBMQ.get_provider() # List Aer backends Aer.backends() # Construct quantum circuit n = 10 circ = QuantumCircuit(2, 2) circ.x(0) while n > 0: circ.swap(0, 1) circ.barrier() n = n - 1 circ.measure([0, 1], [0, 1]) print(circ) # Select the QasmSimulator from the Aer provider simulator = Aer.get_backend('qasm_simulator') # Execute and get counts sim_result = execute(circ, simulator, shots=10000).result() sim_counts = sim_result.get_counts(circ) print("Sim SWAP counts:", sim_counts) plot_histogram(sim_counts, title='Sim SWAP counts') # Import the least busy backend from qiskit.providers.ibmq import least_busy backend = least_busy(provider.backends(operational=True, simulator=False))
4. Use the measurement result to teleport qubit """ from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.quantum_info import random_state import numpy as np # Load IBM account provider = IBMQ.load_account() # Define register of 3 qubits q = QuantumRegister(3) c = ClassicalRegister(2) circuit = QuantumCircuit(q,c) # Generate entanglement circuit.h(1) circuit.cx(1, 2) circuit.barrier() # Perform Bell state measurement circuit.cx(0, 1) circuit.h(0) circuit.measure(0, 0) circuit.measure(1, 1) # Operate on Bob's qubit given result circuit.cx(0, 2) circuit.cz(1, 2) print(circuit)
def evolution_instruction(pauli_list, evo_time, num_time_slices, controlled=False, power=1, use_basis_gates=True, shallow_slicing=False, barrier=False): """ Construct the evolution circuit according to the supplied specification. Args: pauli_list (list([[complex, Pauli]])): The list of pauli terms corresponding to a single time slice to be evolved evo_time (Union(complex, float, Parameter, ParameterExpression)): The evolution time num_time_slices (int): The number of time slices for the expansion controlled (bool, optional): Controlled circuit or not power (int, optional): The power to which the unitary operator is to be raised use_basis_gates (bool, optional): boolean flag for indicating only using basis gates when building circuit. shallow_slicing (bool, optional): boolean flag for indicating using shallow qc.data reference repetition for slicing barrier (bool, optional): whether or not add barrier for every slice Returns: Instruction: The Instruction corresponding to specified evolution. Raises: OpflowError: power must be an integer and greater or equal to 1 ValueError: Unrecognized pauli """ if not isinstance(power, (int, np.int)) or power < 1: raise OpflowError("power must be an integer and greater or equal to 1.") state_registers = QuantumRegister(pauli_list[0][1].num_qubits) if controlled: inst_name = 'Controlled-Evolution^{}'.format(power) ancillary_registers = QuantumRegister(1) qc_slice = QuantumCircuit(state_registers, ancillary_registers, name=inst_name) else: inst_name = 'Evolution^{}'.format(power) qc_slice = QuantumCircuit(state_registers, name=inst_name) # for each pauli [IXYZ]+, record the list of qubit pairs needing CX's cnot_qubit_pairs = [None] * len(pauli_list) # for each pauli [IXYZ]+, record the highest index of the nontrivial pauli gate (X,Y, or Z) top_xyz_pauli_indices = [-1] * len(pauli_list) for pauli_idx, pauli in enumerate(reversed(pauli_list)): n_qubits = pauli[1].num_qubits # changes bases if necessary nontrivial_pauli_indices = [] for qubit_idx in range(n_qubits): # pauli I if not pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]: continue if cnot_qubit_pairs[pauli_idx] is None: nontrivial_pauli_indices.append(qubit_idx) if pauli[1].x[qubit_idx]: # pauli X if not pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.h(state_registers[qubit_idx]) else: qc_slice.h(state_registers[qubit_idx]) # pauli Y elif pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.u(pi / 2, -pi / 2, pi / 2, state_registers[qubit_idx]) else: qc_slice.rx(pi / 2, state_registers[qubit_idx]) # pauli Z elif pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]: pass else: raise ValueError('Unrecognized pauli: {}'.format(pauli[1])) if nontrivial_pauli_indices: top_xyz_pauli_indices[pauli_idx] = nontrivial_pauli_indices[-1] # insert lhs cnot gates if cnot_qubit_pairs[pauli_idx] is None: cnot_qubit_pairs[pauli_idx] = list(zip( sorted(nontrivial_pauli_indices)[:-1], sorted(nontrivial_pauli_indices)[1:] )) for pair in cnot_qubit_pairs[pauli_idx]: qc_slice.cx(state_registers[pair[0]], state_registers[pair[1]]) # insert Rz gate if top_xyz_pauli_indices[pauli_idx] >= 0: # Because Parameter does not support complexity number operation; thus, we do # the following tricks to generate parameterized instruction. # We assume the coefficient in the pauli is always real. and can not do imaginary time # evolution if isinstance(evo_time, (Parameter, ParameterExpression)): lam = 2.0 * pauli[0] / num_time_slices lam = lam.real if lam.imag == 0 else lam lam = lam * evo_time else: lam = (2.0 * pauli[0] * evo_time / num_time_slices).real if not controlled: if use_basis_gates: qc_slice.p(lam, state_registers[top_xyz_pauli_indices[pauli_idx]]) else: qc_slice.rz(lam, state_registers[top_xyz_pauli_indices[pauli_idx]]) else: if use_basis_gates: qc_slice.p(lam / 2, state_registers[top_xyz_pauli_indices[pauli_idx]]) qc_slice.cx(ancillary_registers[0], state_registers[top_xyz_pauli_indices[pauli_idx]]) qc_slice.p(-lam / 2, state_registers[top_xyz_pauli_indices[pauli_idx]]) qc_slice.cx(ancillary_registers[0], state_registers[top_xyz_pauli_indices[pauli_idx]]) else: qc_slice.crz(lam, ancillary_registers[0], state_registers[top_xyz_pauli_indices[pauli_idx]]) # insert rhs cnot gates for pair in reversed(cnot_qubit_pairs[pauli_idx]): qc_slice.cx(state_registers[pair[0]], state_registers[pair[1]]) # revert bases if necessary for qubit_idx in range(n_qubits): if pauli[1].x[qubit_idx]: # pauli X if not pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.h(state_registers[qubit_idx]) else: qc_slice.h(state_registers[qubit_idx]) # pauli Y elif pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.u(-pi / 2, -pi / 2, pi / 2, state_registers[qubit_idx]) else: qc_slice.rx(-pi / 2, state_registers[qubit_idx]) # repeat the slice if shallow_slicing: logger.info('Under shallow slicing mode, the qc.data reference is repeated shallowly. ' 'Thus, changing gates of one slice of the output circuit might affect ' 'other slices.') if barrier: qc_slice.barrier(state_registers) qc_slice.data *= (num_time_slices * power) qc = qc_slice else: qc = QuantumCircuit(name=inst_name) for _ in range(num_time_slices * power): qc += qc_slice if barrier: qc.barrier(state_registers) return qc.to_instruction()
class quantum_sparse_sampling: def __init__(self, states=None, actions=None, tKernel=None, gamma=1.0, is_stochastic=True, env=None): if states is None: raise AquaError("Missing State space") if actions is None: raise AquaError("Missing Action space") if tKernel is None: raise AquaError("Missing Transition Kernel") self.states = states self.actions = actions self.is_stochastic = is_stochastic self.gamma = gamma self.sqbits = math.ceil(math.log2(self.states)) self.aqbits = math.ceil(math.log2(self.actions)) self.qa = {} self.st = {} self.st["st{0}".format(0)] = QuantumRegister(self.sqbits, name="initialState") self.qc = QuantumCircuit(self.st["st{0}".format(0)]) #Transition Kernel tKernel[state][action] -> Probability | sprime | reward #Turn states into into binary and probability into sqrt(probability) self.tk = np.zeros((self.states, self.actions), dtype=object) self.reward_max = -1 self.rewards = [] self.is_openai = len(tKernel[0][0][0]) == 4 self.env = env if self.is_openai: for s in range(self.states): for a in range(self.actions): self.tk[s][a] = [(p, sprime, reward) for (p, sprime, reward, _) in tKernel[s][a]] for (p, sp, r) in self.tk[s][a]: self.rewards.append( (bin(sp)[2:].zfill(self.sqbits), r)) if r > self.reward_max: self.reward_max = r if self.env == "grid": for s in range(self.states): for a in range(self.actions): self.tk[s][a] = [(p, sprime, reward) for (p, sprime, reward) in tKernel[s][a]] for (p, sp, r) in self.tk[s][a]: self.rewards.append( (bin(sp)[2:].zfill(self.sqbits), r)) if r > self.reward_max: self.reward_max = r else: for s in range(self.states): for a in range(self.actions): self.tk[s][a] = [(math.sqrt(p), sprime, reward) for (p, sprime, reward) in tKernel[s][a]] for (p, sp, r) in self.tk[s][a]: self.rewards.append( (bin(sp)[2:].zfill(self.sqbits), r)) if r > self.reward_max: self.reward_max = r self.was_executed = False if self.is_openai: self.positions = np.arange(self.states).reshape( self.sqbits, self.sqbits) #self.rewards = set(self.rewards) def stochastic_transition_oracle(self, step, R): #create new circuit to make call to the oracle efficient. Theres no need to run this for loops if we #can just past a circuit with these logic gates combinations st_circuit = QuantumCircuit(name="qEnv") st_s = QuantumRegister(self.sqbits) st_sprime = QuantumRegister(self.sqbits) st_a = QuantumRegister(self.aqbits) st_r = QuantumRegister(1) st_circuit.add_register(st_s, st_a, st_sprime, st_r) if self.env == "grid": new_neighbours = [] for s in self.neighbours: for a in range(self.actions): #prepare complex vector from the transition probabilities #If (s,a) doesnt happn then we need to make sprime == s state = [complex(0.0, 0.0) for i in range(2**self.sqbits)] for (p, sp, r) in self.tk[s][a]: state[sp] += complex(p, 0.0) if sp not in self.states_visited: new_neighbours.append(sp) self.states_visited.append(sp) state = [complex(math.sqrt(p.real), 0.0) for p in state] sbin = bin(s)[2:].zfill(self.sqbits) abin = bin(a)[2:].zfill(self.aqbits) ctrls = [i for i in st_s] + [i for i in st_a] #ctr_initialization to make the transition st_circuit.ctrl_initialize(statevector=state, ctrl_state=abin + sbin, ctrl_qubits=ctrls, qubits=st_sprime) regs = [i for i in st_s] + [i for i in st_a] + [ i for i in st_sprime ] + [i for i in st_r] for (p, sp, r) in self.tk[s][a]: if r > 0: spbin = bin(sp)[2:].zfill(self.sqbits) st_circuit.append( self.stochastic_reward_oracle( sbin, abin, spbin, r, step - 1, R), regs) ''' spbin = bin(sp)[2:].zfill(self.sqbits) st_circuit.append(self.stochastic_reward_oracle(sbin,abin,spbin,r,step-1,R),regs) ''' self.neighbours = new_neighbours else: if self.is_openai: possible_transitions = list( np.fliplr(self.positions).diagonal(self.sqbits - step)) for s in possible_transitions: for a in range(self.actions): #prepare complex vector from the transition probabilities #If (s,a) doesnt happn then we need to make sprime == s state = [ complex(0.0, 0.0) for i in range(2**self.sqbits) ] for (p, sp, r) in self.tk[s][a]: state[sp] += complex(p, 0.0) state = [ complex(math.sqrt(p.real), 0.0) for p in state ] #We need to turn s,a into binary repr to make the ctrl_state in the initialization sbin = bin(s)[2:].zfill(self.sqbits) abin = bin(a)[2:].zfill(self.aqbits) ctrls = [i for i in st_s] + [i for i in st_a] #ctr_initialization to make the transition st_circuit.ctrl_initialize(statevector=state, ctrl_state=abin + sbin, ctrl_qubits=ctrls, qubits=st_sprime) regs = [i for i in st_s] + [i for i in st_a] + [ i for i in st_sprime ] + [i for i in st_r] for (p, sp, r) in self.tk[s][a]: spbin = bin(sp)[2:].zfill(self.sqbits) st_circuit.append( self.stochastic_reward_oracle( sbin, abin, spbin, r, step - 1, R), regs) else: for s in range(self.states): for a in range(self.actions): #prepare complex vector from the transition probabilities #If (s,a) doesnt happn then we need to make sprime == s state = [ complex(0.0, 0.0) for i in range(2**self.sqbits) ] for (p, sp, r) in self.tk[s][a]: state[sp] += complex(p, 0.0) sbin = bin(s)[2:].zfill(self.sqbits) abin = bin(a)[2:].zfill(self.aqbits) ctrls = [i for i in st_s] + [i for i in st_a] #ctr_initialization to make the transition st_circuit.ctrl_initialize(statevector=state, ctrl_state=abin + sbin, ctrl_qubits=ctrls, qubits=st_sprime) regs = [i for i in st_s] + [i for i in st_a] + [ i for i in st_sprime ] + [i for i in st_r] for (p, sp, r) in self.tk[s][a]: spbin = bin(sp)[2:].zfill(self.sqbits) st_circuit.append( self.stochastic_reward_oracle( sbin, abin, spbin, r, step - 1, R), regs) return st_circuit def stochastic_reward_oracle(self, s, a, sp, r, step, R): #APPEND REWARD AS A ROTATION IN THE Y AXIS TO TURN INTO PROBABILITY qr = QuantumRegister(1) qrs = QuantumRegister(self.sqbits) qra = QuantumRegister(self.aqbits) qrsp = QuantumRegister(self.sqbits) qc = QuantumCircuit(qrs, qra, qrsp, qr, name="Reward Oracle t={}".format(step)) #reward function: Ry gates rotates by theta/2 reward_step = (np.pi) / (2 * R) * (r * self.gamma**step / self.reward_max) #reward_step = (pi/10) * ((self.gamma**step * r)/self.reward_max) for i, j in zip(range(len(s)), reversed(range(len(s)))): if s[i] == '0': qc.x(qrs[j]) for i, j in zip(range(len(a)), reversed(range(len(a)))): if a[i] == '0': qc.x(qra[j]) for i, j in zip(range(len(sp)), reversed(range(len(sp)))): if sp[i] == '0': qc.x(qrsp[j]) #cry_gate = RYGate(reward_step).control(num_ctrl_qubits=2*self.sqbits+self.aqbits,ctrl_state=sp+a+s) cry_gate = RYGate(reward_step).control( num_ctrl_qubits=2 * self.sqbits + self.aqbits) qc.append(cry_gate, [i for i in qrs] + [i for i in qra] + [i for i in qrsp] + [i for i in qr]) for i, j in zip(range(len(s)), reversed(range(len(s)))): if s[i] == '0': qc.x(qrs[j]) for i, j in zip(range(len(a)), reversed(range(len(a)))): if a[i] == '0': qc.x(qra[j]) for i, j in zip(range(len(sp)), reversed(range(len(sp)))): if sp[i] == '0': qc.x(qrsp[j]) return qc def stateActionTransitionOracle(self, currentState, newState, step): self.qc.barrier() for t in self.tk: i = self.sqbits - 1 for s in t[0]: if not int(s): self.qc.x(currentState[i]) i -= 1 i = self.aqbits - 1 #state=int(t[0],base=2) for a in t[1]: if not int(a): self.qc.x(self.qa["action{0}".format(step)][i]) i -= 1 i = self.sqbits - 1 for ss in t[2]: if int(ss): controls = [ currentState[i] for i in range(len(currentState)) ] controls = controls + [ self.qa["action{0}".format(step)][i] for i in range(self.aqbits) ] self.qc.mct(controls, newState[i], None, mode="noancilla") i -= 1 i = self.aqbits - 1 #state=int(t[0],base=2) for a in t[1]: if not int(a): self.qc.x(self.qa["action{0}".format(step)][i]) i -= 1 i = self.sqbits - 1 for s in t[0]: if not int(s): self.qc.x(currentState[i]) i -= 1 self.qc.barrier() def rewardOracle(self, state, rewardReg, qinc): self.qc.barrier() for i in range(len(self.reward_model)): if self.reward_model[i]: b = np.binary_repr(i, width=self.sqbits) j = self.sqbits - 1 for q in b: if not int(q): self.qc.x(state[j]) j -= 1 ###Decompose multi control increment with an ancilla first### self.qc.mct(state, qinc, None, mode='advanced') #self.qc.reset(qinc) j = self.sqbits - 1 for q in b: if not int(q): self.qc.x(state[j]) j -= 1 increment(self.qc, rewardReg, control=qinc) self.qc.barrier() def step(self, initState=0, horizon="infinite"): #if horizon is infinite then the system evolves until the end of the computer resources #self.horizon = self.nstates/2 if horizon=="infinite" else horizon self.horizon = horizon if initState != 0: s = bin(initState)[2:].zfill(self.sqbits) i = self.sqbits - 1 for q in s: if int(q): self.qc.x(self.st["st{0}".format(0)][i]) i -= 1 #reward_model register size will depend on the horizon #given that we're working with binary rewards then for a horizon t, #the maximum reward_model collected is t, so the register has log2(t) qubits #create dictionary to save state transition registers for easy acess in the future for i in range(self.horizon): self.qa["action{0}".format(i)] = QuantumRegister( self.aqbits, "action{0}".format(i)) self.qc.add_register(self.qa["action{0}".format(i)]) #Apply the superposition policy - hadamard on action register #Same as applying an hadamard at each state transition for i in range(self.horizon): self.qc.h(self.qa["action{0}".format(i)]) if self.is_stochastic: #Just one qubit for reward because reward will be amplitude encoded self.rqbits = 1 self.qr = QuantumRegister(self.rqbits, "reward") self.qc.add_register(self.qr) R = 0 for i in range(horizon): R += (self.gamma)**i #Apply transition and reward_model oracles self.neighbours = [initState] self.states_visited = [initState] oracles = {} for i in range(1, self.horizon + 1): oracles[i] = self.stochastic_transition_oracle(i, R) self.st["st{0}".format(i)] = QuantumRegister( self.sqbits, "stateTransition{0}".format(i)) self.qc.add_register(self.st["st{0}".format(i)]) regs = [i for i in self.st["st{0}".format(i - 1)]] + [ i for i in self.qa["action{0}".format(i - 1)] ] + [i for i in self.st["st{0}".format(i)] ] + [i for i in self.qr] if self.is_openai or self.env == "grid": for j in range(1, i + 1): self.qc.append(oracles[j], regs) else: self.qc.append(oracles[i], regs) #regs_reward = [i for i in self.st["st{0}".format(i)]]+[i for i in self.qr] #self.qc.append(self.stochastic_reward_oracle(i-1,self.horizon), regs_reward) self.qc.barrier() else: self.rqbits = math.ceil(math.log2(self.horizon)) self.qr = QuantumRegister(self.rqbits, "reward") self.qinc = {} self.clqinc = ClassicalRegister(1, "controlInc") self.qc.add_register(self.qr) #create action register - Depend on the horizon: #Horizon T - we have Tlog(aqbits) qubits to represent the action register for i in range(1, self.horizon + 1): self.st["st{0}".format(i)] = QuantumRegister( self.sqbits, "stateTransition{0}".format(i)) self.qc.add_register(self.st["st{0}".format(i)]) self.stateActionTransitionOracle( self.st["st{0}".format(i - 1)], self.st["st{0}".format(i)], i - 1) self.qinc["qinc{0}".format(i - 1)] = QuantumRegister( 1, "qinc{0}".format(i - 1)) self.qc.add_register(self.qinc["qinc{0}".format(i - 1)]) self.rewardOracle(self.st["st{0}".format(i)], self.qr, self.qinc["qinc{0}".format(i - 1)]) self.qc.barrier() def draw_circuit(self, decompose_circuit=False, mode="text", layers=1, inverse=False): if inverse: if decompose_circuit: if layers == 1: return self.qc_inverse.decompose().draw(output=mode) elif layers == 2: return self.qc_inverse.decompose().decompose().draw( output=mode) elif layers == 3: return self.qc_inverse.decompose().decompose().decompose( ).draw(output=mode) else: return self.qc_inverse.decompose().decompose().decompose( ).decompose().draw(output=mode) else: return self.qc_inverse.draw(output=mode) else: if decompose_circuit: if layers == 1: return self.qc.decompose().draw(output=mode) elif layers == 2: return self.qc.decompose().decompose().draw(output=mode) elif layers == 3: return self.qc.decompose().decompose().decompose().draw( output=mode) else: return self.qc.decompose().decompose().decompose( ).decompose().draw(output=mode) else: return self.qc.draw(output=mode) #AMPLITUDE AMPLIFCATION BY HOYER,P BRASSARD ET.AL https://arxiv.org/pdf/quant-ph/0005055.pdf def Grover_Iterate(self, circuit, ctrls, regs): #invert phase o \1> terms circuit.z(self.qr) circuit.barrier() circuit.append(self.qc_pre_amplification_inverse, regs) for j in range(self.horizon + 1): circuit.x(self.st["st{0}".format(j)]) circuit.x(self.qr) for j in range(self.horizon): circuit.x(self.qa["action{0}".format(j)]) circuit.barrier() circuit.h(self.st["st{0}".format(self.horizon)][-1]) circuit.barrier() #circuit.append(CXGate().control(num_ctrl_qubits=len(ctrls)),ctrls+[self.st["st{0}".format(self.horizon)][-1]]) circuit.mct(ctrls, self.st["st{0}".format(self.horizon)][-1], None, mode="noancilla") circuit.barrier() circuit.h(self.st["st{0}".format(self.horizon)][-1]) ''' for j in range(1,self.horizon+1): circuit.h(self.st["st{0}".format(j)]) circuit.h(self.qr) for j in range(self.horizon): circuit.h(self.qa["action{0}".format(j)]) ''' circuit.barrier() for j in range(self.horizon): circuit.x(self.qa["action{0}".format(j)]) circuit.x(self.qr) for j in range(self.horizon + 1): circuit.x(self.st["st{0}".format(j)]) circuit.barrier() circuit.append(self.qc_pre_amplification, regs) def QSearch(self, shots=1, backend="qasm_simulator"): it, lambd = 1, 6 / 5 max_it = ((2**(self.aqbits) * self.horizon) + (2**(self.sqbits) * (self.horizon + 1))) / 2 qcGrover = {} c = 0 while it < max_it: qcGrover = QuantumCircuit() qcGrover += self.qc g_it = np.random.randint(it) + 1 for i in range(g_it): self.Grover_Iterate(qcGrover, self.ctrls, self.regs) qcGrover.measure_all() r, rc = execute_locally(qcGrover, nshots=shots, backend=backend) best_measure = max(rc.items(), key=operator.itemgetter(1))[0] reward_measure = int( best_measure[(self.sqbits * self.horizon):(self.sqbits * self.horizon) + 1], 2) if reward_measure: break else: it = min(lambd * it, max_it) c += 1 if it >= max_it: raise ValueError("Search not Worked! Aborted!") return rc, best_measure def solve(self, backend="qasm_simulator", shots=1, iterations=None, draw_circuit=False, amplify=False, measure_all=True, outpath=None, filename=None, plot_show=False, algorithm=None): #reward_model that will serve as index for the quantum maximum finding (qmf) routine #qmf - apply ST and reward_model Oracles again and circuit is the oracle for qmf #we then mark all the elements in the reward_model register that are greater than the test_reward #measurement of qmf will result in a new_reward > test_reward -> test_reward = new_reward #we do this procedure for O(sqrt |A|.T) #At each measurement given by the qmf we need to construct the oracle responsible for marking #the elements in the superposition greater than test_reward # round up the number of iterations # qmf gives the correct answer with prob 1 - (1/2)^k , with k being the number of times # the algorithm is repeated #self.qc.measure_all() if self.is_stochastic: #self.qc.measure_all() ''' result,result_counts = execute_locally(self.qc,nshots=shots,show=True) return result, result_counts ''' self.regs = [i for i in self.st["st{0}".format(0)]] self.ctrls = [i for i in self.st["st{0}".format(0)]] for j in range(self.horizon): self.regs += [i for i in self.qa["action{0}".format(j)]] self.ctrls += [i for i in self.qa["action{0}".format(j)]] self.regs += [i for i in self.qr] self.ctrls += [i for i in self.qr] for j in range(1, self.horizon + 1): self.regs += [i for i in self.st["st{0}".format(j)]] for j in range(1, self.horizon): self.ctrls += [i for i in self.st["st{0}".format(j)]] self.ctrls += [ i for i in self.st["st{0}".format(self.horizon)][:-1] ] #self.qc_pre_amplification = self.qc.copy() #self.qc_pre_amplification_inverse=self.qc.inverse().copy() if algorithm is None: if not self.was_executed: self.qc_pre_amplification = self.qc.copy() self.qc_pre_amplification_inverse = self.qc.inverse().copy( ) if amplify: if not iterations: for i in range( int( round( np.sqrt( 2 * self.actions**self.horizon)))): self.Grover_Iterate(self.ctrls, self.regs) else: for i in range(iterations): self.Grover_Iterate(self.ctrls, self.regs) if measure_all: self.qc.measure_all() else: self.aclassical = ClassicalRegister(self.aqbits) self.rclassical = ClassicalRegister(1) self.qc.add_register(self.aclassical, self.rclassical) self.qc.measure(self.qa["action{0}".format(0)], self.aclassical) self.qc.measure(self.qr, self.rclassical) self.was_executed = True else: if amplify: self.qc.remove_final_measurements() if not iterations: for i in range((int( round( np.sqrt( 2 * self.actions**self.horizon))))): self.Grover_Iterate(self.ctrls, self.regs) else: for i in range(iterations): self.Grover_Iterate(self.ctrls, self.regs) if measure_all: self.qc.measure_all() else: self.aclassical = ClassicalRegister(self.aqbits) self.rclassical = ClassicalRegister(1) self.qc.add_register(self.aclassical, self.rclassical) self.qc.measure(self.qa["action{0}".format(0)], self.aclassical) self.qc.measure(self.qr, self.rclassical) import operator r, rc = execute_locally(self.qc, nshots=shots, backend=backend) best_measure = max(rc.items(), key=operator.itemgetter(1))[0] if measure_all: best_action = best_measure[ (self.sqbits * self.horizon) + 1 + (self.aqbits * (self.horizon - 1)):-self.sqbits] else: best_action = best_measure[1:] ''' if len(rc) > 15: plt.figure(figsize=(len(rc) * 0.45,12)) plt.gca().set_facecolor("gray") plt.gcf().set_facecolor("gray") #plt.bar(range(len(rc)), list(rc.values()), color="darkorange" ,align='center') ''' action_reward = [] new_dict = {} if measure_all: for p in list(rc.keys()): reward = p[( self.sqbits * self.horizon):(self.sqbits * self.horizon) + 1] action = p[(self.sqbits * self.horizon) + 1 + (self.aqbits * (self.horizon - 1)):-self.sqbits] action_reward.append( str(int(action, 2)) + " " + str(int(reward))) ### new code added from here ### new_key = str(int(action, 2)) + " " + str(int(reward)) if new_key in new_dict: new_dict[new_key] += rc.get(p) else: new_dict[new_key] = rc.get(p) ### until here ### else: for p in list(rc.keys()): reward = p[-1] action = p[1:] action_reward.append( str(int(action, 2)) + " " + str(int(reward))) ''' plt.xticks(range(len(rc)), action_reward) plt.xlabel(r"$\mathbf{|action\rangle |reward\rangle}$",fontsize=14) plt.ylabel(r'$\mathbf{\mathbb{E}}$'+" cumulative reward",fontweight="bold",fontsize=14) plt.show() ''' ### replace rc by new_dict #if len(rc) > 15: if len(new_dict) > 15: #fig, ax = plt.subplots(figsize=(len(rc) * 0.45,12)) fig, ax = plt.subplots(figsize=(len(new_dict) * 0.45, 12)) else: fig, ax = plt.subplots() # Create bar plot #bar1 = ax.bar(range(len(rc)), list(rc.values()),color="darkorange") bar1 = ax.bar(range(len(new_dict)), list(new_dict.values()), color="darkorange") ax.set_facecolor("lightgray") #ax.set_xticks(range(len(rc))) ax.set_xticks(range(len(new_dict))) #ax.set_xticklabels(action_reward) ax.set_xticklabels(list(new_dict.keys())) ax.set_title('# Samples = ' + str(shots), fontweight="bold", fontsize=14) ax.set_xlabel(r"$\mathbf{|action\rangle |reward\rangle}$", fontsize=14) ax.set_ylabel("Counts", fontweight="bold", fontsize=14) #ax.axhline(np.mean(counts),linestyle="dashed",color="r",label="Average") #ax.legend() #plt.savefig("random_dist.png") def autolabel(rects): """Attach a text label above each bar in *rects*, displaying its height.""" for rect in rects: height = rect.get_height() ax.annotate( "{}".format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') autolabel(bar1) from os import path if filename is not None: if outpath is not None: plt.savefig(path.join(outpath, filename)) else: plt.savefig(filename) if plot_show: plt.show() return rc, int(best_action, 2) else: if self.was_executed: self.qc.remove_final_measurements() else: self.qc_pre_amplification = self.qc.copy() self.qc_pre_amplification_inverse = self.qc.inverse().copy( ) rc, best_measure = self.QSearch(shots=shots) if measure_all: best_action = best_measure[ (self.sqbits * self.horizon) + 1 + (self.aqbits * (self.horizon - 1)):-self.sqbits] else: best_action = best_measure[1:] ''' if len(rc) > 15: plt.figure(figsize=(len(rc) * 0.45,12)) plt.gca().set_facecolor("gray") plt.gcf().set_facecolor("gray") #plt.bar(range(len(rc)), list(rc.values()), color="darkorange" ,align='center') ''' action_reward = [] new_dict = {} if measure_all: for p in list(rc.keys()): reward = p[( self.sqbits * self.horizon):(self.sqbits * self.horizon) + 1] action = p[(self.sqbits * self.horizon) + 1 + (self.aqbits * (self.horizon - 1)):-self.sqbits] action_reward.append( str(int(action, 2)) + " " + str(int(reward))) ### new code added from here ### new_key = str(int(action, 2)) + " " + str(int(reward)) if new_key in new_dict: new_dict[new_key] += rc.get(p) else: new_dict[new_key] = rc.get(p) ### until here ### else: for p in list(rc.keys()): reward = p[-1] action = p[1:] action_reward.append( str(int(action, 2)) + " " + str(int(reward))) ''' plt.xticks(range(len(rc)), action_reward) plt.xlabel(r"$\mathbf{|action\rangle |reward\rangle}$",fontsize=14) plt.ylabel(r'$\mathbf{\mathbb{E}}$'+" cumulative reward",fontweight="bold",fontsize=14) plt.show() ''' ### replace rc by new_dict #if len(rc) > 15: if len(new_dict) > 15: #fig, ax = plt.subplots(figsize=(len(rc) * 0.45,12)) fig, ax = plt.subplots(figsize=(len(new_dict) * 0.45, 12)) else: fig, ax = plt.subplots() # Create bar plot #bar1 = ax.bar(range(len(rc)), list(rc.values()),color="darkorange") bar1 = ax.bar(range(len(new_dict)), list(new_dict.values()), color="darkorange") ax.set_facecolor("lightgray") #ax.set_xticks(range(len(rc))) ax.set_xticks(range(len(new_dict))) #ax.set_xticklabels(action_reward) ax.set_xticklabels(list(new_dict.keys())) ax.set_title('# Samples = ' + str(shots), fontweight="bold", fontsize=14) ax.set_xlabel(r"$\mathbf{|action\rangle |reward\rangle}$", fontsize=14) ax.set_ylabel("Counts", fontweight="bold", fontsize=14) #ax.axhline(np.mean(counts),linestyle="dashed",color="r",label="Average") #ax.legend() #plt.savefig("random_dist.png") def autolabel(rects): """Attach a text label above each bar in *rects*, displaying its height.""" for rect in rects: height = rect.get_height() ax.annotate( "{}".format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') autolabel(bar1) from os import path if filename is not None: if outpath is not None: plt.savefig(path.join(outpath, filename)) else: plt.savefig(filename) if plot_show: plt.show() return rc, int(best_action, 2) else: self.draw_circuit = draw_circuit qmf_size = self.nactions * self.horizon # We need to pass QMF the extra registers for measuring them # We want to measure the action register actions = [ self.qa["action{0}".format(i)] for i in range(self.horizon) ] #states = [self.st["st{0}".format(i)] for i in range(self.horizon+1)] extra_measure = actions qmf = QMF(circuit=self.qc, search_register=self.qr, size=qmf_size, extra_registers=extra_measure, draw_circuit=self.draw_circuit, max_observation=self.horizon) maximum, top_measurement = qmf.run(backend=backend, shots=shots) return maximum, top_measurement
def test_fusion_operations(self): """Test Fusion enable/disable option""" shots = 100 qr = QuantumRegister(10) cr = ClassicalRegister(10) circuit = QuantumCircuit(qr, cr) for i in range(10): circuit.h(qr[i]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.cx(qr[2], qr[3]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.cx(qr[2], qr[3]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.cx(qr[2], qr[3]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.measure(qr, cr) qobj = compile([circuit], self.SIMULATOR, shots=shots, seed=1) result_fusion = self.SIMULATOR.run(qobj, backend_options={ 'fusion_enable': True, 'fusion_verbose': True, 'fusion_threshold': 1 }).result() self.is_completed(result_fusion) result_nonfusion = self.SIMULATOR.run(qobj, backend_options={ 'fusion_enable': False, 'fusion_verbose': True, 'fusion_threshold': 1 }).result() self.is_completed(result_nonfusion) self.assertDictAlmostEqual(result_fusion.get_counts(circuit), result_nonfusion.get_counts(circuit), delta=0.0, msg="fusion x-x-x was failed")
for r1 in range(runs1): circ = QuantumCircuit(n,n) circ.h(0) noise(0 , single_q_gateerror) for idx in range(1,n): circ.cx(0,idx) noise2(0 , idx , double_q_gateerror ) circ.barrier(range(n)) circ.measure(range(n), range(n)) circuits[n,r1] = circ job_exp = execute(list(circuits.values()) , backend = simulator, shots = shots) results = job_exp.result() noisycounts={} n = 1 r = 0 for i in range(no_of_qubits*runs1): c = {}
class CircuitBackend(UnrollerBackend): """Backend for the unroller that produces a QuantumCircuit. By default, basis gates are the QX gates. """ def __init__(self, basis=None): """Setup this backend. basis is a list of operation name strings. """ super().__init__(basis) self.creg = None self.cval = None if basis: self.basis = basis else: self.basis = ["cx", "u1", "u2", "u3"] self.gates = {} self.listen = True self.in_gate = "" self.circuit = QuantumCircuit() def set_basis(self, basis): """Declare the set of user-defined gates to emit. basis is a list of operation name strings. """ self.basis = basis def version(self, version): """Ignore the version string. v is a version number. """ pass def new_qreg(self, name, size): """Create a new quantum register. name = name of the register sz = size of the register """ assert size >= 0, "invalid qreg size" q_register = QuantumRegister(size, name) self.circuit.add(q_register) def new_creg(self, name, size): """Create a new classical register. name = name of the register sz = size of the register """ assert size >= 0, "invalid creg size" c_register = ClassicalRegister(size, name) self.circuit.add(c_register) def define_gate(self, name, gatedata): """Define a new quantum gate. We don't check that the definition and name agree. name is a string. gatedata is the AST node for the gate. """ self.gates[name] = gatedata def _map_qubit(self, qubit): """Map qubit tuple (regname, index) to (QuantumRegister, index).""" qregs = self.circuit.get_qregs() if qubit[0] not in qregs: raise BackendError("qreg %s does not exist" % qubit[0]) return (qregs[qubit[0]], qubit[1]) def _map_bit(self, bit): """Map bit tuple (regname, index) to (ClassicalRegister, index).""" cregs = self.circuit.get_cregs() if bit[0] not in cregs: raise BackendError("creg %s does not exist" % bit[0]) return (cregs[bit[0]], bit[1]) def _map_creg(self, creg): """Map creg name to ClassicalRegister.""" cregs = self.circuit.get_cregs() if creg not in cregs: raise BackendError("creg %s does not exist" % creg) return cregs[creg] def u(self, arg, qubit, nested_scope=None): """Fundamental single qubit gate. arg is 3-tuple of Node expression objects. qubit is (regname,idx) tuple. nested_scope is a list of dictionaries mapping expression variables to Node expression objects in order of increasing nesting depth. """ if self.listen: if "U" not in self.basis: self.basis.append("U") (theta, phi, lam) = list(map(lambda x: x.sym(nested_scope), arg)) this_gate = self.circuit.u_base(theta, phi, lam, self._map_qubit(qubit)) if self.creg is not None: this_gate.c_if(self._map_creg(self.creg), self.cval) def cx(self, qubit0, qubit1): """Fundamental two qubit gate. qubit0 is (regname,idx) tuple for the control qubit. qubit1 is (regname,idx) tuple for the target qubit. """ if self.listen: if "CX" not in self.basis: self.basis.append("CX") this_gate = self.circuit.cx_base(self._map_qubit(qubit0), self._map_qubit(qubit1)) if self.creg is not None: this_gate.c_if(self._map_creg(self.creg), self.cval) def measure(self, qubit, bit): """Measurement operation. qubit is (regname, idx) tuple for the input qubit. bit is (regname, idx) tuple for the output bit. """ if "measure" not in self.basis: self.basis.append("measure") this_op = self.circuit.measure(self._map_qubit(qubit), self._map_bit(bit)) if self.creg is not None: this_op.c_if(self._map_creg(self.creg), self.cval) def barrier(self, qubitlists): """Barrier instruction. qubitlists is a list of lists of (regname, idx) tuples. """ if self.listen: if "barrier" not in self.basis: self.basis.append("barrier") flatlist = map( self._map_qubit, [qubit for qubitlist in qubitlists for qubit in qubitlist]) self.circuit.barrier(*list(flatlist)) def reset(self, qubit): """Reset instruction. qubit is a (regname, idx) tuple. """ if "reset" not in self.basis: self.basis.append("reset") this_op = self.circuit.reset(self._map_qubit(qubit)) if self.creg is not None: this_op.c_if(self._map_creg(self.creg), self.cval) def set_condition(self, creg, cval): """Attach a current condition. creg is a name string. cval is the integer value for the test. """ self.creg = creg self.cval = cval def drop_condition(self): """Drop the current condition.""" self.creg = None self.cval = None def start_gate(self, name, args, qubits, nested_scope=None, extra_fields=None): """Begin a custom gate. name is name string. args is list of Node expression objects. qubits is list of (regname, idx) tuples. nested_scope is a list of dictionaries mapping expression variables to Node expression objects in order of increasing nesting depth. """ if self.listen and name not in self.basis \ and self.gates[name]["opaque"]: raise BackendError("opaque gate %s not in basis" % name) if self.listen and name in self.basis: self.in_gate = name self.listen = False # Gate names mapped to number of arguments and qubits # and method to invoke on [args, qubits] lut = { "ccx": [(0, 3), lambda x: self.circuit.ccx(x[1][0], x[1][1], x[1][2])], "ch": [(0, 2), lambda x: self.circuit.ch(x[1][0], x[1][1])], "crz": [(1, 2), lambda x: self.circuit.crz(x[0][0], x[1][0], x[1][1])], "cswap": [(0, 3), lambda x: self.circuit.cswap(x[1][0], x[1][1], x[1][2])], "cu1": [(1, 2), lambda x: self.circuit.cu1(x[0][0], x[1][0], x[1][1])], "cu3": [(3, 2), lambda x: self.circuit.cu3( x[0][0], x[0][1], x[0][2], x[1][0], x[1][1])], "cx": [(0, 2), lambda x: self.circuit.cx(x[1][0], x[1][1])], "cy": [(0, 2), lambda x: self.circuit.cy(x[1][0], x[1][1])], "cz": [(0, 2), lambda x: self.circuit.cz(x[1][0], x[1][1])], "swap": [(0, 2), lambda x: self.circuit.swap(x[1][0], x[1][1])], "h": [(0, 1), lambda x: self.circuit.h(x[1][0])], "id": [(0, 1), lambda x: self.circuit.iden(x[1][0])], "rx": [(1, 1), lambda x: self.circuit.rx(x[0][0], x[1][0])], "ry": [(1, 1), lambda x: self.circuit.ry(x[0][0], x[1][0])], "rz": [(1, 1), lambda x: self.circuit.rz(x[0][0], x[1][0])], "s": [(0, 1), lambda x: self.circuit.s(x[1][0])], "sdg": [(0, 1), lambda x: self.circuit.s(x[1][0]).inverse()], "t": [(0, 1), lambda x: self.circuit.t(x[1][0])], "tdg": [(0, 1), lambda x: self.circuit.t(x[1][0]).inverse()], "u1": [(1, 1), lambda x: self.circuit.u1(x[0][0], x[1][0])], "u2": [(2, 1), lambda x: self.circuit.u2(x[0][0], x[0][1], x[1][0])], "u3": [(3, 1), lambda x: self.circuit.u3(x[0][0], x[0][1], x[0][2], x[1][0]) ], "x": [(0, 1), lambda x: self.circuit.x(x[1][0])], "y": [(0, 1), lambda x: self.circuit.y(x[1][0])], "z": [(0, 1), lambda x: self.circuit.z(x[1][0])] } if name not in lut: raise BackendError("gate %s not in standard extensions" % name) gate_data = lut[name] if gate_data[0] != (len(args), len(qubits)): raise BackendError("gate %s signature (%d, %d) is " % (name, len(args), len(qubits)) + "incompatible with the standard " + "extensions") this_gate = gate_data[1]([ list(map(lambda x: x.sym(nested_scope), args)), list(map(self._map_qubit, qubits)) ]) if self.creg is not None: this_gate.c_if(self._map_creg(self.creg), self.cval) def end_gate(self, name, args, qubits, nested_scope=None): """End a custom gate. name is name string. args is list of Node expression objects. qubits is list of (regname, idx) tuples. nested_scope is a list of dictionaries mapping expression variables to Node expression objects in order of increasing nesting depth. """ if name == self.in_gate: self.in_gate = "" self.listen = True def get_output(self): """Return the QuantumCircuit object.""" return self.circuit
############################################################### q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2, name="teleport") # Prepare an initial state qc.u3(0.3, 0.2, 0.1, q[0]) # Prepare a Bell pair qc.h(q[1]) qc.cx(q[1], q[2]) # Barrier following state preparation qc.barrier(q) # Measure in the Bell basis qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) # Apply a correction qc.barrier(q) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.measure(q[2], c2[0]) ############################################################### # Execute.
class Dynamics: """ Class to implement the simulation of quantum dynamics as described in Section 4.7 of Nielsen & Chuang (Quantum computation and quantum information (10th anniv. version), 2010.) A circuit implementing the quantum simulation can be generated for a given problem Hamiltonian parameterized by calling the gen_circuit() method. Attributes ---------- H : ?? The given Hamiltonian whose dynamics we want to simulate barriers : bool should barriers be included in the generated circuit measure : bool should a ClassicalRegister and measurements be added to the circuit regname : str optional string to name the quantum and classical registers. This allows for the easy concatenation of multiple QuantumCircuits. qr : QuantumRegister Qiskit QuantumRegister holding all of the quantum bits circ : QuantumCircuit Qiskit QuantumCircuit that represents the uccsd circuit """ def __init__(self, H, barriers=False, measure=False, regname=None): # Hamiltonian self.H = H # set flags for circuit generation self.barriers = barriers self.nq = self.get_num_qubits() # create a QuantumCircuit object if regname is None: self.qr = QuantumRegister(self.nq) else: self.qr = QuantumRegister(self.nq, name=regname) self.circ = QuantumCircuit(self.qr) # Create and add an ancilla register to the circuit self.ancQ = QuantumRegister(1, "ancQ") self.circ.add_register(self.ancQ) def get_num_qubits(self): """ Given the problem Hamiltonian, return the appropriate number of qubits needed to simulate its dynamics. This number does not include the single ancilla qubit that is added to the circuit. """ numq = 0 for term in self.H: if len(term) > numq: numq = len(term) return numq def compute_to_Z_basis(self, pauli_str): """ Take the given pauli_str of the form ABCD and apply operations to the circuit which will take it from the ABCD basis to the ZZZZ basis Parameters ---------- pauli_str : str string of the form 'p1p2p3...pN' where pK is a Pauli matrix """ for i, pauli in enumerate(pauli_str): if pauli is "X": self.circ.h(self.qr[i]) elif pauli is "Y": self.circ.h(self.qr[i]) self.circ.s(self.qr[i]) def uncompute_to_Z_basis(self, pauli_str): """ Take the given pauli_str of the form ABCD and apply operations to the circuit which will take it from the ZZZZ basis to the ABCD basis Parameters ---------- pauli_str : str string of the form 'p1p2p3...pN' where pK is a Pauli matrix """ for i, pauli in enumerate(pauli_str): if pauli is "X": self.circ.h(self.qr[i]) elif pauli is "Y": self.circ.sdg(self.qr[i]) self.circ.h(self.qr[i]) def apply_phase_shift(self, delta_t): """ Simulate the evolution of exp(-i(dt)Z) """ # apply CNOT ladder -> compute parity for i in range(self.nq): self.circ.cx(self.qr[i], self.ancQ[0]) # apply phase shift to the ancilla # rz applies the unitary: exp(-i*theta*Z/2) self.circ.rz(2 * delta_t, self.ancQ[0]) # apply CNOT ladder -> uncompute parity for i in range(self.nq - 1, -1, -1): self.circ.cx(self.qr[i], self.ancQ[0]) def gen_circuit(self): """ Create a circuit implementing the quantum dynamics simulation Returns ------- QuantumCircuit QuantumCircuit object of size nq with no ClassicalRegister and no measurements """ # generate a naive version of a simulation circuit for term in self.H: self.compute_to_Z_basis(term) if self.barriers: self.circ.barrier() self.apply_phase_shift(1) if self.barriers: self.circ.barrier() self.uncompute_to_Z_basis(term) if self.barriers: self.circ.barrier() # generate a commutation aware version of a simulation circuit # simulate all commuting terms simulataneously by using 1 ancilla per # term that will encode the phase shift based on the parity of the term. return self.circ
# -*- coding: utf-8 -*- """ Created on Mon Apr 13 14:16:04 2020 @author: Neil Gupte """ from qiskit import(QuantumCircuit, execute, Aer) from qiskit.visualization import plot_histogram # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') circuit1 = QuantumCircuit(3, 3) circuit1.x(0) circuit1.draw() circuit1.barrier() circuit1.h(1) circuit1.draw() circuit1.cx(1,2) circuit1.draw() circuit1.cx(0,1) circuit1.draw() circuit1.h(0) circuit1.draw()
def construct_circuit(self, measure=False): """Construct the Phase Estimation circuit""" if self._circuit[measure] is None: if self._operator is not None: # check for identify paulis to get its coef for applying global phase shift on ancillae later num_identities = 0 for p in self._operator.paulis: if np.all(np.logical_not(p[1].z)) and np.all( np.logical_not(p[1].x)): num_identities += 1 if num_identities > 1: raise RuntimeError( 'Multiple identity pauli terms are present.') self._ancilla_phase_coef = p[0].real if isinstance( p[0], complex) else p[0] a = QuantumRegister(self._num_ancillae, name='a') if self._operator is not None: q = QuantumRegister(self._operator.num_qubits, name='q') elif self._operator_circuit_factory is not None: q = QuantumRegister( self._operator_circuit_factory.num_target_qubits, name='q') else: raise RuntimeError('Missing operator specification.') qc = QuantumCircuit(a, q) num_aux_qubits, aux = 0, None if self._state_in_circuit_factory is not None: num_aux_qubits = self._state_in_circuit_factory.required_ancillas( ) if self._operator_circuit_factory is not None: num_aux_qubits = max( num_aux_qubits, self._operator_circuit_factory. required_ancillas_controlled()) if num_aux_qubits > 0: aux = QuantumRegister(num_aux_qubits, name='aux') qc.add_register(aux) # initialize state_in if self._state_in is not None: qc.data += self._state_in.construct_circuit('circuit', q).data elif self._state_in_circuit_factory is not None: self._state_in_circuit_factory.build(qc, q, aux, self._additional_params) else: raise RuntimeError('Missing initial state specification.') # Put all ancillae in uniform superposition qc.u2(0, np.pi, a) # phase kickbacks via dynamics if self._operator is not None: pauli_list = self._operator.reorder_paulis( grouping=self._paulis_grouping) if len(pauli_list) == 1: slice_pauli_list = pauli_list else: if self._expansion_mode == 'trotter': slice_pauli_list = pauli_list elif self._expansion_mode == 'suzuki': slice_pauli_list = Operator._suzuki_expansion_slice_pauli_list( pauli_list, 1, self._expansion_order) else: raise ValueError( 'Unrecognized expansion mode {}.'.format( self._expansion_mode)) for i in range(self._num_ancillae): qc_evolutions = Operator.construct_evolution_circuit( slice_pauli_list, -2 * np.pi, self._num_time_slices, q, a, ctl_idx=i, shallow_slicing=self._shallow_circuit_concat) if self._shallow_circuit_concat: qc.data += qc_evolutions.data else: qc += qc_evolutions # global phase shift for the ancilla due to the identity pauli term qc.u1(2 * np.pi * self._ancilla_phase_coef * (2**i), a[i]) elif self._operator_circuit_factory is not None: for i in range(self._num_ancillae): self._operator_circuit_factory.build_controlled_power( qc, q, a[i], 2**i, aux, self._additional_params) # inverse qft on ancillae self._iqft.construct_circuit('circuit', a, qc) # measuring ancillae if measure: c = ClassicalRegister(self._num_ancillae, name='c') qc.add_register(c) qc.barrier(a) qc.measure(a, c) self._circuit[measure] = qc return self._circuit[measure]
def shor_corrected(error, ry_error, rz_error): # A combination of a three qubit phase flip code, and 3 bit flip codes qc = QuantumCircuit(9, 1) print("\nOriginal LSB qubit, in state |...0>") display(plot_state_qsphere(get_psi(qc))) # Start of phase flip code qc.cx(0, 3) qc.cx(0, 6) qc.h(0) qc.h(3) qc.h(6) qc.barrier([x for x in range(qc.num_qubits)]) # Start of bit flip codes qc.cx(0, 1) qc.cx(3, 4) qc.cx(6, 7) qc.cx(0, 2) qc.cx(3, 5) qc.cx(6, 8) # Error code add_error(error, qc, ry_error, rz_error) print( "Qubit with error... LSB can be in |...0> and in |...1>, with various phase." ) display(plot_state_qsphere(get_psi(qc))) display(qc.draw('mpl')) # End of bit flip codes qc.cx(0, 1) qc.cx(3, 4) qc.cx(6, 7) qc.cx(0, 2) qc.cx(3, 5) qc.cx(6, 8) qc.ccx(1, 2, 0) qc.ccx(4, 5, 3) qc.ccx(8, 7, 6) # End of phase flip code qc.h(0) qc.h(3) qc.h(6) qc.cx(0, 3) qc.cx(0, 6) qc.ccx(6, 3, 0) qc.barrier([x for x in range(qc.num_qubits)]) qc.measure(0, 0) print("Error corrected qubit... LSB in |...0> with phase 0.") display(plot_state_qsphere(get_psi(qc))) display(qc.draw('mpl')) job = execute(qc, backend, shots=1000) counts = job.result().get_counts() print("\nResult of qubit error after Shor code correction:") print("--------------------------------------------------") print(counts)
class SAT_3(object): def __init__(self): self.n = 4 self.q = QuantumRegister(self.n, 'q') self.anc2 = QuantumRegister(self.n, 'anc2') self.anc1 = QuantumRegister(self.n, 'anc1') self.anc = QuantumRegister(self.n, 'anc') self.c = ClassicalRegister(self.n, 'c') self.tar = QuantumRegister(1, 'tar') self.qc = QuantumCircuit(self.q, self.anc1, self.anc, self.anc2, self.tar, self.c) # self.qc.x(self.tar[0]) def run(self): for i in range(self.n): self.qc.x(self.q[i]) self.qc.barrier() for i in range(self.n // 2): self.qc.h(self.q[i]) self.qc.barrier() for i in range(int(self.n)): self.oracle() self.qc.barrier() self.diffusion_gate() self.qc.barrier() self.qc.measure(self.q, self.c) """run_sim""" # See a list of available local simulators # print("Local backends: ", Aer.available_backends()) # compile and run the Quantum circuit on a simulator backend backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(self.qc, backend_sim) result_sim = job_sim.result() # Show the results print("simulation: ", result_sim) counts = result_sim.get_counts(self.qc) counts_l = [(i, counts[i]) for i in counts.keys()] print('Sim: ', sorted(counts_l, key=lambda x: x[1], reverse=True)[:5]) plot_histogram(counts) # circuit_drawer(self.qc, filename="./Pictures/3SAT.png") def oracle(self): # first statment self.qc.ccx(self.q[0], self.q[2], self.anc1[0]) self.qc.ccx(self.anc1[0], self.q[3], self.anc[0]) self.qc.barrier() # second statement self.qc.x(self.q[1]) self.qc.x(self.q[2]) self.qc.barrier() self.qc.ccx(self.q[1], self.q[2], self.anc1[1]) self.qc.ccx(self.anc1[1], self.q[3], self.anc[1]) self.qc.barrier() self.qc.x(self.q[1]) self.qc.x(self.q[2]) self.qc.barrier() # third statement self.qc.x(self.q[0]) self.qc.x(self.q[3]) self.qc.barrier() self.qc.ccx(self.q[0], self.q[1], self.anc1[2]) self.qc.ccx(self.anc1[2], self.q[3], self.anc[2]) self.qc.barrier() self.qc.x(self.q[0]) self.qc.x(self.q[3]) self.qc.barrier() # fourth statement self.qc.x(self.q[1]) self.qc.barrier() self.qc.ccx(self.q[0], self.q[1], self.anc1[3]) self.qc.ccx(self.anc1[3], self.q[2], self.anc[3]) self.qc.barrier() self.qc.x(self.q[1]) self.qc.barrier() # hitting with z-gate self.qc.ccx(self.anc[0], self.anc[1], self.anc2[0]) self.qc.ccx(self.anc2[0], self.anc[2], self.anc2[1]) self.qc.ccx(self.anc2[1], self.anc[3], self.tar[0]) self.qc.barrier() self.qc.z(self.tar[0]) self.qc.barrier() self.qc.ccx(self.anc2[1], self.anc[3], self.tar[0]) self.qc.ccx(self.anc2[0], self.anc[2], self.anc2[1]) self.qc.ccx(self.anc[0], self.anc[1], self.anc2[0]) self.qc.barrier() # uncompute # fourth statement self.qc.x(self.q[1]) self.qc.barrier() self.qc.ccx(self.q[0], self.q[1], self.anc1[3]) self.qc.ccx(self.anc1[3], self.q[2], self.anc[3]) self.qc.barrier() self.qc.x(self.q[1]) self.qc.barrier() # third statement self.qc.x(self.q[0]) self.qc.x(self.q[3]) self.qc.barrier() self.qc.ccx(self.q[0], self.q[1], self.anc1[2]) self.qc.ccx(self.anc1[2], self.q[3], self.anc[2]) self.qc.barrier() self.qc.x(self.q[0]) self.qc.x(self.q[3]) self.qc.barrier() # second statement self.qc.x(self.q[1]) self.qc.x(self.q[2]) self.qc.barrier() self.qc.ccx(self.q[1], self.q[2], self.anc1[1]) self.qc.ccx(self.anc1[1], self.q[3], self.anc[1]) self.qc.barrier() self.qc.x(self.q[1]) self.qc.x(self.q[2]) self.qc.barrier() # first statment self.qc.ccx(self.q[0], self.q[2], self.anc1[0]) self.qc.ccx(self.anc1[0], self.q[3], self.anc[0]) self.qc.barrier() def diffusion_gate(self): """diffusion_gate""" # apply hadamard gates for i in range(self.n): self.qc.h(self.q[i]) # apply pauli-X gates for i in range(self.n): self.qc.x(self.q[i]) self.qc.barrier() """Apply multi-qubit control-pauli-Z gate """ if self.n > 2: for i in range(self.n - 1): if i == 0: self.qc.ccx(self.q[i], self.q[i + 1], self.anc1[i]) elif i == 1: pass else: self.qc.ccx(self.q[i], self.anc1[i - 2], self.anc1[i - 1]) self.qc.cz(self.anc1[self.n - 3], self.q[self.n - 1]) for i in range(self.n - 2, -1, -1): if i == 0: self.qc.ccx(self.q[i], self.q[i + 1], self.anc1[i]) elif i == 1: pass else: # print('i: ', i) # print('q: ', len(self.q)) # print('anc1: ', len(self.anc1)) self.qc.ccx(self.q[i], self.anc1[i - 2], self.anc1[i - 1]) else: # if n == 2, only need to control-z the first with the second self.qc.cx(self.q[0], self.anc1[0]) self.qc.cz(self.anc1[0], self.q[1]) self.qc.cx(self.q[0], self.anc1[0]) self.qc.barrier() # apply pauli-X gates for i in range(self.n): self.qc.x(self.q[i]) # apply hadamard gates for i in range(self.n): self.qc.h(self.q[i]) def toffoli_n_unborrowed(self, qubits, borrowed, target): """toffoli_n :param qubits: list of indexes for global qubits There are n-qubits and n-2 borrowed bits :param borrowed: list of indexes for the borrowed bits :param target: index of the target qubit """ if isinstance(target, int): target_bit = self.q[target] else: target_bit = target if len(qubits) <= 3: if len(qubits) <= 2: self.qc.ccx( self.q[qubits[0]] if isinstance(qubits[0], int) else qubits[0], self.q[qubits[1]] if isinstance( qubits[1], int) else qubits[1], target_bit) else: self.qc.ccx( self.q[qubits[0]] if isinstance(qubits[0], int) else qubits[0], self.q[qubits[1]] if isinstance( qubits[1], int) else qubits[1], target_bit) else: m = len(qubits) - 2 - 1 print(len(qubits), m) self.qc.ccx( self.q[qubits[m + 2]] if isinstance(qubits[m + 2], int) else qubits[m + 2], self.q[borrowed[m]] if isinstance( borrowed[m], int) else borrowed[m], target_bit) # first forward pass for i in range(m - 1, -1, -1): if i == 0: print(qubits[i]) self.qc.ccx( self.q[qubits[i]] if isinstance(qubits[i], int) else qubits[i], self.q[qubits[i + 1]] if isinstance( qubits[i + 1], int) else qubits[i + 1], self.q[borrowed[i]]) else: self.qc.ccx( self.q[qubits[i + 2]] if isinstance( qubits[i + 2], int) else qubits[i + 2], self.q[borrowed[i]] if isinstance(borrowed[i], int) else borrowed[i], self.q[borrowed[i + 1]] if isinstance( borrowed[i + 1], int) else borrowed[i + 1]) # first backwards pass for i in range(1, m - 1): self.qc.ccx( self.q[borrowed[i]] if isinstance(borrowed[i], int) else borrowed[i], self.q[qubits[i + 2]] if isinstance( qubits[i + 2], int) else qubits[i + 2], self.q[borrowed[i + 1]] if isinstance( borrowed[i + 1], int) else borrowed[i + 1]) # second forward pass self.qc.ccx( self.q[qubits[m + 2]] if isinstance(qubits[m + 2], int) else qubits[m + 2], self.q[borrowed[m]] if isinstance( borrowed[m], int) else borrowed[m], target_bit) for i in range(m - 1, -1, -1): if i == 0: self.qc.ccx( self.q[qubits[i]] if isinstance(qubits[i], int) else qubits[i], self.q[qubits[i + 1]] if isinstance( qubits[i + 1], int) else qubits[i + 1], self.q[borrowed[i]] if isinstance(borrowed[i], int) else borrowed[i]) else: self.qc.ccx( self.q[qubits[i + 2]] if isinstance( qubits[i + 2], int) else qubits[i + 2], self.q[borrowed[i]] if isinstance(borrowed[i], int) else borrowed[i], self.q[borrowed[i + 1]] if isinstance( borrowed[i + 1], int) else borrowed[i + 1]) # second backwards pass for i in range(1, m - 1): self.qc.ccx( self.q[borrowed[i]] if isinstance(borrowed[i], int) else borrowed[i], self.q[qubits[i + 2]] if isinstance( qubits[i + 2], int) else qubits[i + 2], self.q[borrowed[i + 1]] if isinstance( borrowed[i + 1], int) else borrowed[i + 1])
from qiskit.tools.visualization import plot_histogram from IPython.core.display import display print("Ch 5: Three-qubit coin toss") print("---------------------------") qc = QuantumCircuit(3, 3) qc.h([0, 1, 2]) qc.measure([0, 1, 2], [0, 1, 2]) display(qc.draw('mpl')) backend = Aer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1000).result().get_counts(qc) display(plot_histogram(counts)) qc.barrier([0, 1, 2]) qc.reset([0, 1, 2]) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.measure([0, 1, 2], [0, 1, 2]) display(qc.draw('mpl')) counts = execute(qc, backend, shots=1000).result().get_counts(qc) display(plot_histogram(counts))
def create_circuit(self, angles): """ Creating the quantum circuit by filling in the gaps with the defined `angles` that are required to load the test and training vectors. """ # create empty quantum circuit qc = QuantumCircuit(self.q, self.c) ####################################### #START of the state preparation routine # put the ancilla and the index qubits into uniform superposition qc.h(self.ancilla_qubit) qc.h(self.index_qubit) # loading the test vector (which we wish to classify) qc.cx(self.ancilla_qubit, self.data_qubit) qc.u3(-angles[0], 0, 0, self.data_qubit) qc.cx(self.ancilla_qubit, self.data_qubit) qc.u3(angles[0], 0, 0, self.data_qubit) # barriers make sure that our circuit is being executed the way we want # otherwise some gates might be executed before we want to qc.barrier() # flipping the ancilla qubit > this moves the input vector to the |0> state of the ancilla qc.x(self.ancilla_qubit) qc.barrier() # loading the first training vector # [0,1] -> class 0 # we can load this with a straightforward Toffoli qc.ccx(self.ancilla_qubit, self.index_qubit, self.data_qubit) qc.barrier() # flip the index qubit > moves the first training vector to the |0> state of the index qubit qc.x(self.index_qubit) qc.barrier() # loading the second training vector # [0.78861, 0.61489] -> class 1 qc.ccx(self.ancilla_qubit, self.index_qubit, self.data_qubit) qc.cx(self.index_qubit, self.data_qubit) qc.u3(angles[1], 0, 0, self.data_qubit) qc.cx(self.index_qubit, self.data_qubit) qc.u3(-angles[1], 0, 0, self.data_qubit) qc.ccx(self.ancilla_qubit, self.index_qubit, self.data_qubit) qc.cx(self.index_qubit, self.data_qubit) qc.u3(-angles[1], 0, 0, self.data_qubit) qc.cx(self.index_qubit, self.data_qubit) qc.u3(angles[1], 0, 0, self.data_qubit) qc.barrier() # END of state preparation routine #################################################### # at this point we would usually swap the data and class qubit # however, we can be lazy and let the Qiskit compiler take care of it # flip the class label for training vector #2 qc.cx(self.index_qubit, self.class_qubit) qc.barrier() ############################################# # START of the mini distance-based classifier # interfere the input vector with the training vectors qc.h(self.ancilla_qubit) qc.barrier() # Measure all qubits and record the results in the classical registers qc.measure(self.q, self.c) # END of the mini distance-based classifier ############################################# return qc
def _tomography_circuits(circuit, measured_qubits, prepared_qubits=None, meas_labels='Pauli', meas_basis='Pauli', prep_labels=None, prep_basis=None): """ Return a list of quantum tomography circuits. This is the general circuit preparation function called by `state_tomography_circuits` and `process_tomography_circuits` and allows partial tomography circuits to be generated, or tomography circuits with custom preparation and measurement operators. Args: circuit (QuantumCircuit): the QuantumCircuit circuit to be tomographed. measured_qubits (QuantumRegister): the qubits to be measured. This can also be a list of whole QuantumRegisters or individual QuantumRegister qubit tuples. prepared_qubits (QuantumRegister or None): the qubits to have state preparation applied, if different from measured_qubits. If None measured_qubits will be used for prepared qubits (Default: None). meas_labels (None, str, tuple, list(tuple)): The measurement operator labels. If None no measurements will be appended. See additional information for details (Default: 'Pauli'). prep_labels (None, str, tuple, list(tuple)): The preparation operator labels. If None no preparations will be appended. See additional information for details (Default: None). meas_circuit_fn (None, str, function): The measurement circuit function. See additional information for details (Default: None). prep_circuit_fn (None, str, function): The preparation circuit function. See additional information for details (Default: None). Returns: A list of QuantumCircuit objects containing the original circuit with state preparation circuits prepended, and measurement circuits appended. Additional Information Specifying Labels ----------------- `meas_labels` and `prep_labels` may be specified as either: - None: no measurements, or preparation, will be added. - str: use a built-in basis. For meas_labels the built-in basis is 'Pauli'. For prep_labels the built-in bases are 'Pauli' and 'SIC'. - tuple(str): specify single qubit operator labels and generate all n-qubit combinations. - list(tuple(str)): specify a custom list of n-qubit label tuples. If a str argument is used then it is not necessary to specify the corresponding meas_circuit_fn or prep_circuit_fn as the defaults will be used for the corresponding basis. However, when using a tuple or list value these functions must be manually specified using either a str for the build in bases, or a function (See below for documentation.) Specifying a tuple can be used to only measure certain operators. For example if we specify meas_labels=('Z', ) the resulting circuits will only contain measurements in the Z-basis. Specifying meas_labels=('X','Z') will only contain 2 ** n measurements in X and Z basis etc. Specifying a tuple is necessary when using a custom `meas_circuit_fn` or `prep_circuit_fn` as these will be the str passed to the function to return the corresponding QuantumCircuit objects. Specifying a list of tuples will override an automatic generation. This can be for partial tomography. For example for a 2-qubit state tomography experiment we might only specify correlated measurements eg: meas_labels=[('X','X'), ('Y','Y'), ('Z','Z')] Custom Measurement Circuit Function ---------------------------------- Custom measurement circuit functions can be used by passing the function using the `meas_circuit_fn` keyword. These functions should have the signature: meas_circuit_fn(op, qubit, clbit) Args: op (str): the operator label qubit (Qubit): measured qubit clbit (Clbit): measurement clbit Returns: A QuantumCircuit object for the measurement. See the built-in function `pauli_measurement_circuit` for an example. The built-in Pauli measurement function `pauli_measurement_circuit` may be invoked using the meas_circuit_fn='Pauli'. Custom Preparation Circuit Function ---------------------------------- Custom preparation circuit functions can be used by passing the function using the `prep_circuit_fn` keyword. These functions should have the signature: prep_circuit_fn(op, qubit) Args: op (str): the operator label qubit (Qubit): measured qubit Returns: A QuantumCircuit object for the preparation gates. See the build-in function `pauli_preparation_circuit` for an example. See the built-in function `pauli_measurement_circuit` for an example. The built-in Pauli preparation function `pauli_preparation_circuit` may be invoked using the prep_circuit_fn='Pauli'. The built-in SIC-POVM preparation function `sicpovm_preparation_circuit` may be invoked using the prep_circuit_fn='SIC'. """ # Check for different prepared qubits if prepared_qubits is None: prepared_qubits = measured_qubits # Check input circuit for measurements and measured qubits if isinstance(measured_qubits, list): # Unroll list of registers meas_qubits = _format_registers(*measured_qubits) else: meas_qubits = _format_registers(measured_qubits) if isinstance(prepared_qubits, list): # Unroll list of registers prep_qubits = _format_registers(*prepared_qubits) else: prep_qubits = _format_registers(prepared_qubits) if len(prep_qubits) != len(meas_qubits): raise QiskitError( "prepared_qubits and measured_qubits are different length.") num_qubits = len(meas_qubits) meas_qubit_registers = set(q.register for q in meas_qubits) # Check qubits being measured are defined in circuit for reg in meas_qubit_registers: if reg not in circuit.qregs: logger.warning('WARNING: circuit does not contain ' 'measured QuantumRegister: %s', reg.name) prep_qubit_registers = set(q.register for q in prep_qubits) # Check qubits being measured are defined in circuit for reg in prep_qubit_registers: if reg not in circuit.qregs: logger.warning('WARNING: circuit does not contain ' 'prepared QuantumRegister: %s', reg.name) # Get combined registers qubit_registers = prep_qubit_registers.union(meas_qubit_registers) # Check if there are already measurements in the circuit for op in circuit: if isinstance(op, Measure): logger.warning('WARNING: circuit already contains measurements') if isinstance(op, Reset): logger.warning('WARNING: circuit contains resets') # Load built-in circuit functions if callable(meas_basis): measurement = meas_basis else: measurement = default_basis(meas_basis) if isinstance(measurement, TomographyBasis): if measurement.measurement is not True: raise QiskitError("Invalid measurement basis") measurement = measurement.measurement_circuit if callable(prep_basis): preparation = prep_basis else: preparation = default_basis(prep_basis) if isinstance(preparation, TomographyBasis): if preparation.preparation is not True: raise QiskitError("Invalid preparation basis") preparation = preparation.preparation_circuit # Check we have circuit functions defined if measurement is None and meas_labels is not None: raise ValueError("Measurement basis is not specified.") if preparation is None and prep_labels is not None: raise ValueError("Preparation basis is not specified.") # Load built-in basis labels if isinstance(meas_labels, str): meas_labels = _default_measurement_labels(meas_labels) if isinstance(prep_labels, str): prep_labels = _default_preparation_labels(prep_labels) # Generate n-qubit labels meas_labels = _generate_labels(meas_labels, num_qubits) prep_labels = _generate_labels(prep_labels, num_qubits) # Note if the input circuit already has classical registers defined # the returned circuits add a new classical register for the tomography # measurements which will be inserted as the first classical register in # the list of returned circuits. registers = qubit_registers.copy() if measurement is not None: clbits = ClassicalRegister(num_qubits) registers.add(clbits) # Generate the circuits qst_circs = [] for pl in prep_labels: prep = QuantumCircuit(*registers) # Generate preparation circuit if pl is not None: for j in range(num_qubits): prep += preparation(pl[j], prep_qubits[j]) prep.barrier(*qubit_registers) # Add circuit being tomographed prep += circuit # Generate Measurement circuit for ml in meas_labels: meas = QuantumCircuit(*registers) if ml is not None: meas.barrier(*qubit_registers) for j in range(num_qubits): meas += measurement(ml[j], meas_qubits[j], clbits[j]) circ = prep + meas if pl is None: # state tomography circuit circ.name = str(ml) else: # process tomography circuit circ.name = str((pl, ml)) qst_circs.append(circ) return qst_circs
def test_example_swap_bits(self): """Test a toy example swapping a set bit around. Uses the mapper. Pass if results are correct. """ backend = BasicAer.get_backend("qasm_simulator") coupling_map = [ [0, 1], [0, 8], [1, 2], [1, 9], [2, 3], [2, 10], [3, 4], [3, 11], [4, 5], [4, 12], [5, 6], [5, 13], [6, 7], [6, 14], [7, 15], [8, 9], [9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], ] # ┌───┐ ░ ┌─┐ # q0_0: ┤ X ├─X───────────░─┤M├─────────────── # └───┘ │ ░ └╥┘ ┌─┐ # q0_1: ──────┼─────X──X──░──╫────┤M├───────── # │ │ │ ░ ║ └╥┘ ┌─┐ # q0_2: ──────X──X──┼──┼──░──╫─────╫────┤M├─── # │ │ │ ░ ║ ┌─┐ ║ └╥┘ # q1_0: ─────────┼──┼──┼──░──╫─┤M├─╫─────╫──── # │ │ │ ░ ║ └╥┘ ║ ┌─┐ ║ # q1_1: ─────────┼──┼──X──░──╫──╫──╫─┤M├─╫──── # │ │ ░ ║ ║ ║ └╥┘ ║ ┌─┐ # q1_2: ─────────X──X─────░──╫──╫──╫──╫──╫─┤M├ # ░ ║ ║ ║ ║ ║ └╥┘ # c0: 6/═════════════════════╩══╩══╩══╩══╩══╩═ # 0 3 1 4 2 5 n = 3 # make this at least 3 qr0 = QuantumRegister(n) qr1 = QuantumRegister(n) ans = ClassicalRegister(2 * n) qc = QuantumCircuit(qr0, qr1, ans) # Set the first bit of qr0 qc.x(qr0[0]) # Swap the set bit qc.swap(qr0[0], qr0[n - 1]) qc.swap(qr0[n - 1], qr1[n - 1]) qc.swap(qr1[n - 1], qr0[1]) qc.swap(qr0[1], qr1[1]) # Insert a barrier before measurement qc.barrier() # Measure all of the qubits in the standard basis for j in range(n): qc.measure(qr0[j], ans[j]) qc.measure(qr1[j], ans[j + n]) # First version: no mapping result = execute( qc, backend=backend, coupling_map=None, shots=1024, seed_simulator=14 ).result() self.assertEqual(result.get_counts(qc), {"010000": 1024}) # Second version: map to coupling graph result = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, seed_simulator=14 ).result() self.assertEqual(result.get_counts(qc), {"010000": 1024})
def build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit: # implement the Bernstein-Vazirani circuit zero = np.binary_repr(0, n) b = f(zero) # initial n + 1 bits input_qubit = QuantumRegister(n+1, "qc") classicals = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classicals) # inverse last one (can be omitted if using O_f^\pm) prog.x(input_qubit[n]) # circuit begin prog.h(input_qubit[1]) # number=1 prog.h(input_qubit[2]) # number=38 prog.cz(input_qubit[0],input_qubit[2]) # number=39 prog.h(input_qubit[2]) # number=40 prog.h(input_qubit[2]) # number=59 prog.cz(input_qubit[0],input_qubit[2]) # number=60 prog.h(input_qubit[2]) # number=61 prog.h(input_qubit[2]) # number=42 prog.cz(input_qubit[0],input_qubit[2]) # number=43 prog.h(input_qubit[2]) # number=44 prog.h(input_qubit[2]) # number=48 prog.cz(input_qubit[0],input_qubit[2]) # number=49 prog.h(input_qubit[2]) # number=50 prog.cx(input_qubit[0],input_qubit[2]) # number=54 prog.x(input_qubit[2]) # number=55 prog.h(input_qubit[2]) # number=67 prog.cz(input_qubit[0],input_qubit[2]) # number=68 prog.h(input_qubit[2]) # number=69 prog.h(input_qubit[2]) # number=64 prog.cz(input_qubit[0],input_qubit[2]) # number=65 prog.h(input_qubit[2]) # number=66 prog.cx(input_qubit[0],input_qubit[2]) # number=37 prog.h(input_qubit[2]) # number=51 prog.cz(input_qubit[0],input_qubit[2]) # number=52 prog.h(input_qubit[2]) # number=53 prog.h(input_qubit[2]) # number=25 prog.cz(input_qubit[0],input_qubit[2]) # number=26 prog.h(input_qubit[2]) # number=27 prog.h(input_qubit[1]) # number=7 prog.cz(input_qubit[2],input_qubit[1]) # number=8 prog.rx(0.17592918860102857,input_qubit[2]) # number=34 prog.rx(-0.3989822670059037,input_qubit[1]) # number=30 prog.h(input_qubit[1]) # number=9 prog.h(input_qubit[1]) # number=18 prog.rx(2.3310617489636263,input_qubit[2]) # number=58 prog.cz(input_qubit[2],input_qubit[1]) # number=19 prog.h(input_qubit[1]) # number=20 prog.cx(input_qubit[0],input_qubit[1]) # number=70 prog.x(input_qubit[1]) # number=71 prog.cx(input_qubit[0],input_qubit[1]) # number=72 prog.y(input_qubit[1]) # number=14 prog.h(input_qubit[1]) # number=22 prog.cz(input_qubit[2],input_qubit[1]) # number=23 prog.rx(-0.9173450548482197,input_qubit[1]) # number=57 prog.cx(input_qubit[2],input_qubit[1]) # number=63 prog.h(input_qubit[1]) # number=24 prog.z(input_qubit[2]) # number=3 prog.z(input_qubit[1]) # number=41 prog.x(input_qubit[1]) # number=17 prog.y(input_qubit[2]) # number=5 prog.x(input_qubit[2]) # number=21 # apply H to get superposition for i in range(n): prog.h(input_qubit[i]) prog.h(input_qubit[n]) prog.barrier() # apply oracle O_f oracle = build_oracle(n, f) prog.append( oracle.to_gate(), [input_qubit[i] for i in range(n)] + [input_qubit[n]]) # apply H back (QFT on Z_2^n) for i in range(n): prog.h(input_qubit[i]) prog.barrier() # measure return prog
def test_grovers_circuit(self): """Testing a circuit originated in the Grover algorithm""" shots = 1000 coupling_map = None # 6-qubit grovers # # ┌───┐┌───┐ ┌───┐┌───┐ ┌───┐ ┌───┐┌───┐ ░ ┌─┐ # q0_0: ┤ H ├┤ X ├──■──┤ X ├┤ X ├──■──┤ X ├──■──┤ X ├┤ H ├──────░─┤M├─── # ├───┤└───┘ │ └───┘└───┘ │ ├───┤ │ ├───┤├───┤ ░ └╥┘┌─┐ # q0_1: ┤ H ├──■────┼─────────■────┼──┤ X ├──■──┤ X ├┤ H ├──────░──╫─┤M├ # ├───┤ │ ┌─┴─┐ │ ┌─┴─┐└───┘ │ └───┘└───┘ ░ ║ └╥┘ # q0_2: ┤ X ├──┼──┤ X ├──■────┼──┤ X ├───────┼──────────────────░──╫──╫─ # ├───┤┌─┴─┐└───┘ │ ┌─┴─┐└───┘ │ ░ ║ ║ # q0_3: ┤ X ├┤ X ├───────■──┤ X ├────────────┼──────────────────░──╫──╫─ # └───┘└───┘ ┌─┴─┐├───┤┌───┐ ┌─┴─┐┌───┐┌───┐┌───┐ ░ ║ ║ # q0_4: ───────────────┤ X ├┤ X ├┤ H ├─────┤ X ├┤ H ├┤ X ├┤ H ├─░──╫──╫─ # └───┘└───┘└───┘ └───┘└───┘└───┘└───┘ ░ ║ ║ # q0_5: ────────────────────────────────────────────────────────░──╫──╫─ # ░ ║ ║ # c0: 2/═══════════════════════════════════════════════════════════╩══╩═ # 0 1 qr = QuantumRegister(6) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr, name="grovers") circuit.h(qr[0]) circuit.h(qr[1]) circuit.x(qr[2]) circuit.x(qr[3]) circuit.x(qr[0]) circuit.cx(qr[0], qr[2]) circuit.x(qr[0]) circuit.cx(qr[1], qr[3]) circuit.ccx(qr[2], qr[3], qr[4]) circuit.cx(qr[1], qr[3]) circuit.x(qr[0]) circuit.cx(qr[0], qr[2]) circuit.x(qr[0]) circuit.x(qr[1]) circuit.x(qr[4]) circuit.h(qr[4]) circuit.ccx(qr[0], qr[1], qr[4]) circuit.h(qr[4]) circuit.x(qr[0]) circuit.x(qr[1]) circuit.x(qr[4]) circuit.h(qr[0]) circuit.h(qr[1]) circuit.h(qr[4]) circuit.barrier(qr) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) result = execute( circuit, backend=self.backend, coupling_map=coupling_map, seed_simulator=self.seed_simulator, shots=shots, ) counts = result.result().get_counts() expected_probs = {"00": 0.64, "01": 0.117, "10": 0.113, "11": 0.13} target = {key: shots * val for key, val in expected_probs.items()} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold)
def runHypergraphWithBias (weightsV, dataset, nshots, threshold, toleration, qBias): """ This function takes weightsV = an initial array of weights only to test it, not to improve dataset = the dataset to split it in to the array of input and the class for all the dataset nshots = the number of shots to run on qasm_simulator threshold = the % of nshots that we should consider that 1 is the winner """ acertos = 0 erros = 0 lenInput = len(dataset[0][0:-1]) + qBias datasize = len(dataset) tempoTotal = 0 random.seed(1) '''Inicializando/Resetando o circuito ''' Nqubits = int(sqrt(lenInput)) qubitsInput = QuantumRegister(Nqubits, 'qin') anc = QuantumRegister(Nqubits-1, 'anc') qubitOutput = QuantumRegister(1, 'qout') output = ClassicalRegister(1, 'cout') '''Testando weightsV em todo o dataset ''' program_starts = time.time() for i in range(datasize): # Vetor de entrada Ui (estados a serem marcados) inputV = dataset[i][0:-1] + [1 for iAux in range(qBias)] # valor da class do Ui atual (é cruz o não?) theClass = dataset[i][-1] circuit = QuantumCircuit(qubitsInput,anc,qubitOutput,output) #input patternsI = transformMatrixToVector(inputV) #weights patternsW = transformMatrixToVector(weightsV) createSuperposition(circuit, Nqubits, qubitsInput) # Superposiçóes inicial patternsInitialI = [1 for i in range(lenInput)] patternsInitialW = [1 for i in range(lenInput)] createU(circuit, Nqubits, patternsI, qubitsInput, anc) # Ui circuit.barrier() createU(circuit, Nqubits, patternsW, qubitsInput, anc) # Uw createSuperposition(circuit, Nqubits, qubitsInput) # Superposiçóes final createXN(circuit, Nqubits, qubitsInput) # Nots finais generateCCX(circuit, qubitsInput, range(Nqubits), anc, qubitOutput) # Produto interno increaseThreshold(circuit, toleration, qubitsInput, Nqubits, anc, qubitOutput ) circuit.measure(qubitOutput, output) # Medição circuit.barrier() job = execute(circuit, backend=backendSimulador, shots=nshots) result = job.result() contagem = result.get_counts() results1 = contagem.get('1') # Resultados que deram 1 if str(type(results1)) == "<class 'NoneType'>": results1 = 0 results0 = contagem.get('0') # Resultados que deram 0 if str(type(results0)) == "<class 'NoneType'>": results0 = 0 # Utilizando threshold if results1 >= (nshots * threshold): ##print("saida quantico 1") its1 = True its0 = False else: ##print("saida quantico 0") its1 = False its0 = True ##print("results 0", results0, "results 1",results1 ) # Verificação de resultado e classe: acerto/erro if its0: #neuronio deu como saida 0 if theClass != 0: erros = erros + 1 else: acertos = acertos + 1 else: #neuronio deu como saida 1 if theClass != 1: erros = erros + 1 else: acertos = acertos + 1 now = time.time() tempoTotal = now - program_starts # print("Acurácia: ", "{0:.2f}".format((acertos/datasize) * 100),"%| Erros: ", "{0:.2f}".format((erros/datasize) * 100), "% | Tempo: ", "%.2f" % tempoTotal, " segundos") # print(weightsV, float("{0:.2f}".format((acertos/datasize) * 100))) return float("{0:.2f}".format((acertos/datasize) * 100))
# apply x-gate to the fourth quantum bit once qc2.x(q2[3]) # apply x-gate to the third quantum bit three times qc2.x(q2[2]) qc2.x(q2[2]) qc2.x(q2[2]) # apply x-gate to the second quantum bit four times qc2.x(q2[1]) qc2.x(q2[1]) qc2.x(q2[1]) qc2.x(q2[1]) # define a barrier (for a better visualization) qc2.barrier() # if the sizes of quantum and classical registers are the same, we can define measurements with a single line of code qc2.measure(q2, c2) # then quantum bits and classical bits are associated with respect to their indices # run the codes until now, and then draw our circuit print("The design of the circuit is done.") for i in range(11): print(randrange(n)) job = execute(qc2, Aer.get_backend('qasm_simulator'), shots=100) counts = job.result().get_counts(qc2) print(counts)
from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt ha = QuantumCircuit(4, 2) # input ha.x(0) ha.x(1) ha.barrier() # XOR on bit 1 ha.cx(0, 2) ha.cx(1, 2) ha.barrier() # output ha.measure(2, 0) ha.measure(3, 1) ha.draw(output='mpl') # simulate counts = execute(ha, Aer.get_backend('qasm_simulator')).result().get_counts() # plot the result plot_histogram(counts) plt.subplots_adjust(bottom=0.25) plt.show()
basis_gates = ['u1', 'u2', 'u3', 'cx'] # Start Circuit 1 # Generate 3-qubit GHZ state num_qubits = 3 q5 = QuantumRegister(3) circuit = QuantumCircuit(q5) # Start of Deutsch-Josza Algorithm - mod 2 =0 circuit.h(0) circuit.h(1) circuit.x(2) circuit.h(2) circuit.barrier() circuit.cx(0, 2) circuit.cx(1, 2) circuit.x(2) circuit.barrier() circuit.h(0) circuit.h(1) circuit.h(2) # measurement # circuit.measure(range(num_qubits),range(num_qubits)) # End of Deutsch-Josza Algorithm - mod 2 =0 # Start Noise Configuration noise_model = NoiseModel()
class TestStandard1Q(StandardExtensionTest): """Standard Extension Test. Gates with a single Qubit""" def setUp(self): self.q = QuantumRegister(3, "q") self.r = QuantumRegister(3, "r") self.c = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.q, self.r, self.c) self.c_header = 69 # lenght of the header def test_barrier(self): self.circuit.barrier(self.q[1]) qasm_txt = 'barrier q[1];' self.assertResult(Barrier, qasm_txt, qasm_txt) def test_barrier_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.barrier, self.c[0]) self.assertRaises(QISKitError, c.barrier, self.c) self.assertRaises(QISKitError, c.barrier, (self.q, 3)) self.assertRaises(QISKitError, c.barrier, (self.q, 'a')) self.assertRaises(QISKitError, c.barrier, 0) def test_barrier_reg(self): self.circuit.barrier(self.q) qasm_txt = 'barrier q[0],q[1],q[2];' self.assertResult(Barrier, qasm_txt, qasm_txt) def test_barrier_None(self): self.circuit.barrier() qasm_txt = 'barrier q[0],q[1],q[2],r[0],r[1],r[2];' self.assertResult(Barrier, qasm_txt, qasm_txt) def test_ccx(self): self.circuit.ccx(self.q[0], self.q[1], self.q[2]) qasm_txt = 'ccx q[0],q[1],q[2];' self.assertResult(ToffoliGate, qasm_txt, qasm_txt) def test_ccx_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.ccx, self.c[0], self.c[1], self.c[2]) self.assertRaises(QISKitError, c.ccx, self.q[0], self.q[0], self.q[2]) self.assertRaises(QISKitError, c.ccx, 0, self.q[0], self.q[2]) self.assertRaises(QISKitError, c.ccx, (self.q, 3), self.q[1], self.q[2]) self.assertRaises(QISKitError, c.ccx, self.c, self.q, self.q) self.assertRaises(QISKitError, c.ccx, 'a', self.q[1], self.q[2]) def test_ch(self): self.circuit.ch(self.q[0], self.q[1]) qasm_txt = 'ch q[0],q[1];' self.assertResult(CHGate, qasm_txt, qasm_txt) def test_ch_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.ch, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.ch, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.ch, 0, self.q[0]) self.assertRaises(QISKitError, c.ch, (self.q, 3), self.q[0]) self.assertRaises(QISKitError, c.ch, self.c, self.q) self.assertRaises(QISKitError, c.ch, 'a', self.q[1]) def test_crz(self): self.circuit.crz(1, self.q[0], self.q[1]) self.assertResult(CrzGate, 'crz(1) q[0],q[1];', 'crz(-1) q[0],q[1];') def test_crz_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.crz, 0, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.crz, 0, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.crz, 0, 0, self.q[0]) # TODO self.assertRaises(QISKitError, c.crz, self.q[2], self.q[1], self.q[0]) self.assertRaises(QISKitError, c.crz, 0, self.q[1], self.c[2]) self.assertRaises(QISKitError, c.crz, 0, (self.q, 3), self.q[1]) self.assertRaises(QISKitError, c.crz, 0, self.c, self.q) # TODO self.assertRaises(QISKitError, c.crz, 'a', self.q[1], self.q[2]) def test_cswap(self): self.circuit.cswap(self.q[0], self.q[1], self.q[2]) qasm_txt = 'cx q[2],q[1];\nccx q[0],q[1],q[2];\ncx q[2],q[1];' self.assertResult(FredkinGate, qasm_txt, qasm_txt) def test_cswap_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.cswap, self.c[0], self.c[1], self.c[2]) self.assertRaises(QISKitError, c.cswap, self.q[1], self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cswap, self.q[1], 0, self.q[0]) self.assertRaises(QISKitError, c.cswap, self.c[0], self.c[1], self.q[0]) self.assertRaises(QISKitError, c.cswap, self.q[0], self.q[0], self.q[1]) self.assertRaises(QISKitError, c.cswap, 0, self.q[0], self.q[1]) self.assertRaises(QISKitError, c.cswap, (self.q, 3), self.q[0], self.q[1]) self.assertRaises(QISKitError, c.cswap, self.c, self.q[0], self.q[1]) self.assertRaises(QISKitError, c.cswap, 'a', self.q[1], self.q[2]) def test_cu1(self): self.circuit.cu1(1, self.q[1], self.q[2]) self.assertResult(Cu1Gate, 'cu1(1) q[1],q[2];', 'cu1(-1) q[1],q[2];') def test_cu1_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.cu1, self.c[0], self.c[1], self.c[2]) self.assertRaises(QISKitError, c.cu1, 1, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cu1, self.q[1], 0, self.q[0]) self.assertRaises(QISKitError, c.cu1, 0, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.cu1, 0, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cu1, 0, 0, self.q[0]) # TODO self.assertRaises(QISKitError, c.cu1, self.q[2], self.q[1], self.q[0]) self.assertRaises(QISKitError, c.cu1, 0, self.q[1], self.c[2]) self.assertRaises(QISKitError, c.cu1, 0, (self.q, 3), self.q[1]) self.assertRaises(QISKitError, c.cu1, 0, self.c, self.q) # TODO self.assertRaises(QISKitError, c.cu1, 'a', self.q[1], self.q[2]) def test_cu3(self): self.circuit.cu3(1, 2, 3, self.q[1], self.q[2]) self.assertResult(Cu3Gate, 'cu3(1,2,3) q[1],q[2];', 'cu3(-1,-3,-2) q[1],q[2];') def test_cu3_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.cu3, 0, 0, self.q[0], self.q[1], self.c[2]) self.assertRaises(QISKitError, c.cu3, 0, 0, 0, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cu3, 0, 0, self.q[1], 0, self.q[0]) self.assertRaises(QISKitError, c.cu3, 0, 0, 0, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cu3, 0, 0, 0, 0, self.q[0]) self.assertRaises(QISKitError, c.cu3, 0, 0, 0, (self.q, 3), self.q[1]) self.assertRaises(QISKitError, c.cu3, 0, 0, 0, self.c, self.q) # TODO self.assertRaises(QISKitError, c.cu3, 0, 0, 'a', self.q[1], self.q[2]) def test_cx(self): self.circuit.cx(self.q[1], self.q[2]) qasm_txt = 'cx q[1],q[2];' self.assertResult(CnotGate, qasm_txt, qasm_txt) def test_cx_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.cx, self.c[1], self.c[2]) self.assertRaises(QISKitError, c.cx, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cx, 0, self.q[0]) self.assertRaises(QISKitError, c.cx, (self.q, 3), self.q[0]) self.assertRaises(QISKitError, c.cx, self.c, self.q) self.assertRaises(QISKitError, c.cx, 'a', self.q[1]) def test_cxbase(self): qasm_txt = 'CX q[1],q[2];' self.circuit.cx_base(self.q[1], self.q[2]) self.assertResult(CXBase, qasm_txt, qasm_txt) def test_cxbase_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.cx_base, self.c[1], self.c[2]) self.assertRaises(QISKitError, c.cx_base, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cx_base, 0, self.q[0]) self.assertRaises(QISKitError, c.cx_base, (self.q, 3), self.q[0]) self.assertRaises(QISKitError, c.cx_base, self.c, self.q) self.assertRaises(QISKitError, c.cx_base, 'a', self.q[1]) def test_cy(self): qasm_txt = 'cy q[1],q[2];' self.circuit.cy(self.q[1], self.q[2]) self.assertResult(CyGate, qasm_txt, qasm_txt) def test_cy_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.cy, self.c[1], self.c[2]) self.assertRaises(QISKitError, c.cy, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cy, 0, self.q[0]) self.assertRaises(QISKitError, c.cy, (self.q, 3), self.q[0]) self.assertRaises(QISKitError, c.cy, self.c, self.q) self.assertRaises(QISKitError, c.cy, 'a', self.q[1]) def test_cz(self): qasm_txt = 'cz q[1],q[2];' self.circuit.cz(self.q[1], self.q[2]) self.assertResult(CzGate, qasm_txt, qasm_txt) def test_cz_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.cz, self.c[1], self.c[2]) self.assertRaises(QISKitError, c.cz, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.cz, 0, self.q[0]) self.assertRaises(QISKitError, c.cz, (self.q, 3), self.q[0]) self.assertRaises(QISKitError, c.cz, self.c, self.q) self.assertRaises(QISKitError, c.cz, 'a', self.q[1]) def test_h(self): qasm_txt = 'h q[1];' self.circuit.h(self.q[1]) self.assertResult(HGate, qasm_txt, qasm_txt) def test_h_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.h, self.c[0]) self.assertRaises(QISKitError, c.h, self.c) self.assertRaises(QISKitError, c.h, (self.q, 3)) self.assertRaises(QISKitError, c.h, (self.q, 'a')) self.assertRaises(QISKitError, c.h, 0) def test_h_reg(self): qasm_txt = 'h q[0];\nh q[1];\nh q[2];' instruction_set = self.circuit.h(self.q) self.assertStmtsType(instruction_set.instructions, HGate) self.assertQasm(qasm_txt) def test_h_reg_inv(self): qasm_txt = 'h q[0];\nh q[1];\nh q[2];' instruction_set = self.circuit.h(self.q).inverse() self.assertStmtsType(instruction_set.instructions, HGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 22) def test_iden(self): self.circuit.iden(self.q[1]) self.assertResult(IdGate, 'id q[1];', 'id q[1];') def test_iden_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.iden, self.c[0]) self.assertRaises(QISKitError, c.iden, self.c) self.assertRaises(QISKitError, c.iden, (self.q, 3)) self.assertRaises(QISKitError, c.iden, (self.q, 'a')) self.assertRaises(QISKitError, c.iden, 0) def test_iden_reg(self): qasm_txt = 'id q[0];\nid q[1];\nid q[2];' instruction_set = self.circuit.iden(self.q) self.assertStmtsType(instruction_set.instructions, IdGate) self.assertQasm(qasm_txt) def test_iden_reg_inv(self): qasm_txt = 'id q[0];\nid q[1];\nid q[2];' instruction_set = self.circuit.iden(self.q).inverse() self.assertStmtsType(instruction_set.instructions, IdGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 25) def test_rx(self): self.circuit.rx(1, self.q[1]) self.assertResult(RXGate, 'rx(1) q[1];', 'rx(-1) q[1];') def test_rx_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.rx, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.rx, self.q[1], 0) self.assertRaises(QISKitError, c.rx, 0, self.c[0]) self.assertRaises(QISKitError, c.rx, 0, 0) # TODO self.assertRaises(QISKitError, c.rx, self.q[2], self.q[1]) self.assertRaises(QISKitError, c.rx, 0, (self.q, 3)) self.assertRaises(QISKitError, c.rx, 0, self.c) # TODO self.assertRaises(QISKitError, c.rx, 'a', self.q[1]) self.assertRaises(QISKitError, c.rx, 0, 'a') def test_rx_reg(self): qasm_txt = 'rx(1) q[0];\nrx(1) q[1];\nrx(1) q[2];' instruction_set = self.circuit.rx(1, self.q) self.assertStmtsType(instruction_set.instructions, RXGate) self.assertQasm(qasm_txt) def test_rx_reg_inv(self): qasm_txt = 'rx(-1) q[0];\nrx(-1) q[1];\nrx(-1) q[2];' instruction_set = self.circuit.rx(1, self.q).inverse() self.assertStmtsType(instruction_set.instructions, RXGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 37) def test_rx_pi(self): c = self.circuit c.rx(pi / 2, self.q[1]) self.assertResult(RXGate, 'rx(pi/2) q[1];', 'rx(-pi/2) q[1];') def test_ry(self): self.circuit.ry(1, self.q[1]) self.assertResult(RYGate, 'ry(1) q[1];', 'ry(-1) q[1];') def test_ry_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.ry, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.ry, self.q[1], 0) self.assertRaises(QISKitError, c.ry, 0, self.c[0]) self.assertRaises(QISKitError, c.ry, 0, 0) # TODO self.assertRaises(QISKitError, c.ry, self.q[2], self.q[1]) self.assertRaises(QISKitError, c.ry, 0, (self.q, 3)) self.assertRaises(QISKitError, c.ry, 0, self.c) # TODO self.assertRaises(QISKitError, c.ry, 'a', self.q[1]) self.assertRaises(QISKitError, c.ry, 0, 'a') def test_ry_reg(self): qasm_txt = 'ry(1) q[0];\nry(1) q[1];\nry(1) q[2];' instruction_set = self.circuit.ry(1, self.q) self.assertStmtsType(instruction_set.instructions, RYGate) self.assertQasm(qasm_txt) def test_ry_reg_inv(self): qasm_txt = 'ry(-1) q[0];\nry(-1) q[1];\nry(-1) q[2];' instruction_set = self.circuit.ry(1, self.q).inverse() self.assertStmtsType(instruction_set.instructions, RYGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 37) def test_ry_pi(self): c = self.circuit c.ry(pi / 2, self.q[1]) self.assertResult(RYGate, 'ry(pi/2) q[1];', 'ry(-pi/2) q[1];') def test_rz(self): self.circuit.rz(1, self.q[1]) self.assertResult(RZGate, 'rz(1) q[1];', 'rz(-1) q[1];') def test_rz_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.rz, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.rz, self.q[1], 0) self.assertRaises(QISKitError, c.rz, 0, self.c[0]) self.assertRaises(QISKitError, c.rz, 0, 0) # TODO self.assertRaises(QISKitError, c.rz, self.q[2], self.q[1]) self.assertRaises(QISKitError, c.rz, 0, (self.q, 3)) self.assertRaises(QISKitError, c.rz, 0, self.c) # TODO self.assertRaises(QISKitError, c.rz, 'a', self.q[1]) self.assertRaises(QISKitError, c.rz, 0, 'a') def test_rz_reg(self): qasm_txt = 'rz(1) q[0];\nrz(1) q[1];\nrz(1) q[2];' instruction_set = self.circuit.rz(1, self.q) self.assertStmtsType(instruction_set.instructions, RZGate) self.assertQasm(qasm_txt) def test_rz_reg_inv(self): qasm_txt = 'rz(-1) q[0];\nrz(-1) q[1];\nrz(-1) q[2];' instruction_set = self.circuit.rz(1, self.q).inverse() self.assertStmtsType(instruction_set.instructions, RZGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 37) def test_rz_pi(self): c = self.circuit c.rz(pi / 2, self.q[1]) self.assertResult(RZGate, 'rz(pi/2) q[1];', 'rz(-pi/2) q[1];') def test_s(self): self.circuit.s(self.q[1]) self.assertResult(SGate, 's q[1];', 'sdg q[1];') def test_s_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.s, self.c[0]) self.assertRaises(QISKitError, c.s, self.c) self.assertRaises(QISKitError, c.s, (self.q, 3)) self.assertRaises(QISKitError, c.s, (self.q, 'a')) self.assertRaises(QISKitError, c.s, 0) def test_s_reg(self): qasm_txt = 's q[0];\ns q[1];\ns q[2];' instruction_set = self.circuit.s(self.q) self.assertStmtsType(instruction_set.instructions, SGate) self.assertQasm(qasm_txt) def test_s_reg_inv(self): qasm_txt = 'sdg q[0];\nsdg q[1];\nsdg q[2];' instruction_set = self.circuit.s(self.q).inverse() self.assertStmtsType(instruction_set.instructions, SGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 28) def test_sdg(self): self.circuit.sdg(self.q[1]) self.assertResult(SGate, 'sdg q[1];', 's q[1];') def test_sdg_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.sdg, self.c[0]) self.assertRaises(QISKitError, c.sdg, self.c) self.assertRaises(QISKitError, c.sdg, (self.q, 3)) self.assertRaises(QISKitError, c.sdg, (self.q, 'a')) self.assertRaises(QISKitError, c.sdg, 0) def test_sdg_reg(self): qasm_txt = 'sdg q[0];\nsdg q[1];\nsdg q[2];' instruction_set = self.circuit.sdg(self.q) self.assertStmtsType(instruction_set.instructions, SGate) self.assertQasm(qasm_txt) def test_sdg_reg_inv(self): qasm_txt = 's q[0];\ns q[1];\ns q[2];' instruction_set = self.circuit.sdg(self.q).inverse() self.assertStmtsType(instruction_set.instructions, SGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 22) def test_swap(self): self.circuit.swap(self.q[1], self.q[2]) self.assertResult(SwapGate, 'swap q[1],q[2];', 'swap q[1],q[2];') def test_swap_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.swap, self.c[1], self.c[2]) self.assertRaises(QISKitError, c.swap, self.q[0], self.q[0]) self.assertRaises(QISKitError, c.swap, 0, self.q[0]) self.assertRaises(QISKitError, c.swap, (self.q, 3), self.q[0]) self.assertRaises(QISKitError, c.swap, self.c, self.q) self.assertRaises(QISKitError, c.swap, 'a', self.q[1]) self.assertRaises(QISKitError, c.swap, self.q, self.r[1]) self.assertRaises(QISKitError, c.swap, self.q[1], self.r) def test_t(self): c = self.circuit self.assertRaises(QISKitError, c.t, self.c[0]) # TODO self.assertRaises(QISKitError, c.t, 1) c.t(self.q[1]) self.assertResult(TGate, 't q[1];', 'tdg q[1];') def test_t_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.t, self.c[0]) self.assertRaises(QISKitError, c.t, self.c) self.assertRaises(QISKitError, c.t, (self.q, 3)) self.assertRaises(QISKitError, c.t, (self.q, 'a')) self.assertRaises(QISKitError, c.t, 0) def test_t_reg(self): qasm_txt = 't q[0];\nt q[1];\nt q[2];' instruction_set = self.circuit.t(self.q) self.assertStmtsType(instruction_set.instructions, TGate) self.assertQasm(qasm_txt) def test_t_reg_inv(self): qasm_txt = 'tdg q[0];\ntdg q[1];\ntdg q[2];' instruction_set = self.circuit.t(self.q).inverse() self.assertStmtsType(instruction_set.instructions, TGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 28) def test_tdg(self): c = self.circuit self.assertRaises(QISKitError, c.tdg, self.c[0]) # TODO self.assertRaises(QISKitError, c.tdg, 1) c.tdg(self.q[1]) self.assertResult(TGate, 'tdg q[1];', 't q[1];') def test_tdg_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.tdg, self.c[0]) self.assertRaises(QISKitError, c.tdg, self.c) self.assertRaises(QISKitError, c.tdg, (self.q, 3)) self.assertRaises(QISKitError, c.tdg, (self.q, 'a')) self.assertRaises(QISKitError, c.tdg, 0) def test_tdg_reg(self): qasm_txt = 'tdg q[0];\ntdg q[1];\ntdg q[2];' instruction_set = self.circuit.tdg(self.q) self.assertStmtsType(instruction_set.instructions, TGate) self.assertQasm(qasm_txt) def test_tdg_reg_inv(self): qasm_txt = 't q[0];\nt q[1];\nt q[2];' instruction_set = self.circuit.tdg(self.q).inverse() self.assertStmtsType(instruction_set.instructions, TGate) self.assertQasm(qasm_txt, offset=len(qasm_txt) - 22) def test_u1(self): self.circuit.u1(1, self.q[1]) self.assertResult(U1Gate, 'u1(1) q[1];', 'u1(-1) q[1];') def test_u1_invalid(self): c = self.circuit # CHECKME? self.assertRaises(QISKitError, c.u1, self.c[0], self.q[0]) self.assertRaises(QISKitError, c.u1, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.u1, self.q[1], 0) self.assertRaises(QISKitError, c.u1, 0, self.c[0]) self.assertRaises(QISKitError, c.u1, 0, 0) # TODO self.assertRaises(QISKitError, c.u1, self.q[2], self.q[1]) self.assertRaises(QISKitError, c.u1, 0, (self.q, 3)) self.assertRaises(QISKitError, c.u1, 0, self.c) # TODO self.assertRaises(QISKitError, c.u1, 'a', self.q[1]) self.assertRaises(QISKitError, c.u1, 0, 'a') def test_u1_reg(self): qasm_txt = 'u1(1) q[0];\nu1(1) q[1];\nu1(1) q[2];' instruction_set = self.circuit.u1(1, self.q) self.assertStmtsType(instruction_set.instructions, U1Gate) self.assertQasm(qasm_txt) def test_u1_reg_inv(self): qasm_txt = 'u1(-1) q[0];\nu1(-1) q[1];\nu1(-1) q[2];' instruction_set = self.circuit.u1(1, self.q).inverse() self.assertStmtsType(instruction_set.instructions, U1Gate) self.assertQasm(qasm_txt) def test_u1_pi(self): c = self.circuit c.u1(pi / 2, self.q[1]) self.assertResult(U1Gate, 'u1(pi/2) q[1];', 'u1(-pi/2) q[1];') def test_u2(self): self.circuit.u2(1, 2, self.q[1]) self.assertResult(U2Gate, 'u2(1,2) q[1];', 'u2(-pi - 2,-1 + pi) q[1];') def test_u2_invalid(self): c = self.circuit # CHECKME? self.assertRaises(QISKitError, c.u2, 0, self.c[0], self.q[0]) self.assertRaises(QISKitError, c.u2, 0, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.u2, 0, self.q[1], 0) self.assertRaises(QISKitError, c.u2, 0, 0, self.c[0]) self.assertRaises(QISKitError, c.u2, 0, 0, 0) # TODO self.assertRaises(QISKitError, c.u2, 0, self.q[2], self.q[1]) self.assertRaises(QISKitError, c.u2, 0, 0, (self.q, 3)) self.assertRaises(QISKitError, c.u2, 0, 0, self.c) # TODO self.assertRaises(QISKitError, c.u2, 0, 'a', self.q[1]) self.assertRaises(QISKitError, c.u2, 0, 0, 'a') def test_u2_reg(self): qasm_txt = 'u2(1,2) q[0];\nu2(1,2) q[1];\nu2(1,2) q[2];' instruction_set = self.circuit.u2(1, 2, self.q) self.assertStmtsType(instruction_set.instructions, U2Gate) self.assertQasm(qasm_txt) def test_u2_reg_inv(self): qasm_txt = 'u2(-pi - 2,-1 + pi) q[0];\nu2(-pi - 2,-1 + pi) q[1];\nu2(-pi - 2,-1 + pi) q[2];' instruction_set = self.circuit.u2(1, 2, self.q).inverse() self.assertStmtsType(instruction_set.instructions, U2Gate) self.assertQasm(qasm_txt) def test_u2_pi(self): c = self.circuit c.u2(pi / 2, 0.3 * pi, self.q[1]) self.assertResult(U2Gate, 'u2(pi/2,0.3*pi) q[1];', 'u2(-1.3*pi,pi/2) q[1];') def test_u3(self): self.circuit.u3(1, 2, 3, self.q[1]) self.assertResult(U3Gate, 'u3(1,2,3) q[1];', 'u3(-1,-3,-2) q[1];') def test_u3_invalid(self): c = self.circuit # CHECKME? self.assertRaises(QISKitError, c.u3, 0, self.c[0], self.q[0]) self.assertRaises(QISKitError, c.u3, 0, 0, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.u3, 0, 0, self.q[1], 0) self.assertRaises(QISKitError, c.u3, 0, 0, 0, self.c[0]) self.assertRaises(QISKitError, c.u3, 0, 0, 0, 0) # TODO self.assertRaises(QISKitError, c.u3, 0, 0, self.q[2], self.q[1]) self.assertRaises(QISKitError, c.u3, 0, 0, 0, (self.q, 3)) self.assertRaises(QISKitError, c.u3, 0, 0, 0, self.c) # TODO self.assertRaises(QISKitError, c.u3, 0, 0, 'a', self.q[1]) self.assertRaises(QISKitError, c.u3, 0, 0, 0, 'a') def test_u3_reg(self): qasm_txt = 'u3(1,2,3) q[0];\nu3(1,2,3) q[1];\nu3(1,2,3) q[2];' instruction_set = self.circuit.u3(1, 2, 3, self.q) self.assertStmtsType(instruction_set.instructions, U3Gate) self.assertQasm(qasm_txt) def test_u3_reg_inv(self): qasm_txt = 'u3(-1,-3,-2) q[0];\nu3(-1,-3,-2) q[1];\nu3(-1,-3,-2) q[2];' instruction_set = self.circuit.u3(1, 2, 3, self.q).inverse() self.assertStmtsType(instruction_set.instructions, U3Gate) self.assertQasm(qasm_txt) def test_u3_pi(self): c = self.circuit c.u3(pi, pi / 2, 0.3 * pi, self.q[1]) self.assertResult(U3Gate, 'u3(pi,pi/2,0.3*pi) q[1];', 'u3(-pi,-0.3*pi,-pi/2) q[1];') def test_ubase(self): self.circuit.u_base(1, 2, 3, self.q[1]) self.assertResult(UBase, 'U(1,2,3) q[1];', 'U(-1,-3,-2) q[1];') def test_ubase_invalid(self): c = self.circuit # CHECKME? self.assertRaises(QISKitError, c.u_base, 0, self.c[0], self.q[0]) self.assertRaises(QISKitError, c.u_base, 0, 0, self.c[0], self.c[1]) self.assertRaises(QISKitError, c.u_base, 0, 0, self.q[1], 0) self.assertRaises(QISKitError, c.u_base, 0, 0, 0, self.c[0]) self.assertRaises(QISKitError, c.u_base, 0, 0, 0, 0) # TODO self.assertRaises(QISKitError, c.u_base, 0, 0, self.q[2], self.q[1]) self.assertRaises(QISKitError, c.u_base, 0, 0, 0, (self.q, 3)) self.assertRaises(QISKitError, c.u_base, 0, 0, 0, self.c) # TODO self.assertRaises(QISKitError, c.u_base, 0, 0, 'a', self.q[1]) self.assertRaises(QISKitError, c.u_base, 0, 0, 0, 'a') def test_ubase_reg(self): qasm_txt = 'U(1,2,3) q[0];\nU(1,2,3) q[1];\nU(1,2,3) q[2];' instruction_set = self.circuit.u_base(1, 2, 3, self.q) self.assertStmtsType(instruction_set.instructions, UBase) self.assertQasm(qasm_txt) def test_ubase_reg_inv(self): qasm_txt = 'U(-1,-3,-2) q[0];\nU(-1,-3,-2) q[1];\nU(-1,-3,-2) q[2];' instruction_set = self.circuit.u_base(1, 2, 3, self.q).inverse() self.assertStmtsType(instruction_set.instructions, UBase) self.assertQasm(qasm_txt) def test_ubase_pi(self): c = self.circuit c.u_base(pi, pi / 2, 0.3 * pi, self.q[1]) self.assertResult(UBase, 'U(pi,pi/2,0.3*pi) q[1];', 'U(-pi,-0.3*pi,-pi/2) q[1];') def test_x(self): self.circuit.x(self.q[1]) self.assertResult(XGate, 'x q[1];', 'x q[1];') def test_x_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.x, self.c[0]) self.assertRaises(QISKitError, c.x, self.c) self.assertRaises(QISKitError, c.x, (self.q, 3)) self.assertRaises(QISKitError, c.x, (self.q, 'a')) self.assertRaises(QISKitError, c.x, 0) def test_x_reg(self): qasm_txt = 'x q[0];\nx q[1];\nx q[2];' instruction_set = self.circuit.x(self.q) self.assertStmtsType(instruction_set.instructions, XGate) self.assertQasm(qasm_txt) def test_x_reg_inv(self): qasm_txt = 'x q[0];\nx q[1];\nx q[2];' instruction_set = self.circuit.x(self.q).inverse() self.assertStmtsType(instruction_set.instructions, XGate) self.assertQasm(qasm_txt) def test_y(self): self.circuit.y(self.q[1]) self.assertResult(YGate, 'y q[1];', 'y q[1];') def test_y_invalid(self): c = self.circuit self.assertRaises(QISKitError, c.y, self.c[0]) self.assertRaises(QISKitError, c.y, self.c) self.assertRaises(QISKitError, c.y, (self.q, 3)) self.assertRaises(QISKitError, c.y, (self.q, 'a')) self.assertRaises(QISKitError, c.y, 0) def test_y_reg(self): qasm_txt = 'y q[0];\ny q[1];\ny q[2];' instruction_set = self.circuit.y(self.q) self.assertStmtsType(instruction_set.instructions, YGate) self.assertQasm(qasm_txt) def test_y_reg_inv(self): qasm_txt = 'y q[0];\ny q[1];\ny q[2];' instruction_set = self.circuit.y(self.q).inverse() self.assertStmtsType(instruction_set.instructions, YGate) self.assertQasm(qasm_txt) def test_z(self): self.circuit.z(self.q[1]) self.assertResult(ZGate, 'z q[1];', 'z q[1];') def test_rzz(self): c = self.circuit self.assertRaises(QISKitError, c.rzz, 0.1, self.c[1], self.c[2]) self.assertRaises(QISKitError, c.rzz, 0.1, self.q[0], self.q[0]) c.rzz(pi/2, self.q[1], self.q[2]) self.assertResult(RZZGate, 'rzz(pi/2) q[1],q[2];', 'rzz(-pi/2) q[1],q[2];') def assertResult(self, t, qasm_txt, qasm_txt_): """ t: type qasm_txt: qasm representation qasm_txt_: qasm representation of inverse """ c = self.circuit self.assertRaises(QISKitError, c.z, self.c[0]) self.assertRaises(QISKitError, c.z, self.c) self.assertRaises(QISKitError, c.z, (self.q, 3)) self.assertRaises(QISKitError, c.z, (self.q, 'a')) self.assertRaises(QISKitError, c.z, 0) def test_z_reg(self): qasm_txt = 'z q[0];\nz q[1];\nz q[2];' instruction_set = self.circuit.z(self.q) self.assertStmtsType(instruction_set.instructions, ZGate) self.assertQasm(qasm_txt) def test_z_reg_inv(self): qasm_txt = 'z q[0];\nz q[1];\nz q[2];' instruction_set = self.circuit.z(self.q).inverse() self.assertStmtsType(instruction_set.instructions, ZGate) self.assertQasm(qasm_txt)
def createCircuit_ExactCover(x, depth, options=None): """ implements https://arxiv.org/pdf/1912.10499.pdf FR is a matrix r1 r2 ..... rN f1 f2 . . . fn where each column indicates if route r uses flight f (entry is 1) or not (entry is 0) CR is a vector of route costs [c1 ... cN] where c1 is the cost of route r1 """ FR = options.get('FR', None) CR = options.get('CR', None) usebarrier = options.get('usebarrier', False) name = options.get('name', None) fn = FR.shape[0] ### number of flights rN = FR.shape[1] ### number of routes q = QuantumRegister(rN) c = ClassicalRegister(rN) circ = QuantumCircuit(q, c, name=name) circ.h(range(rN)) for d in range(depth): gamma = x[2 * d] beta = x[2 * d + 1] for i in range(rN): w = 0 for j in range(fn): w += .5 * FR[j, i] * (np.sum(FR[j, :]) - 2) if CR is not None: w += .25 * CR[i]**2 if abs(w) > 1e-14: wg = w * gamma circ.rz(wg, q[i]) ### for j in range(i + 1, rN): w = 0 for k in range(fn): w += 0.5 * FR[k, i] * FR[k, j] if CR is not None: if (i == j): w += 0.25 * CR[i]**2 if w > 0: wg = w * gamma circ.cx(q[i], q[j]) circ.rz(wg, q[j]) circ.cx(q[i], q[j]) # this is an equivalent implementation: # circ.cu1(-2 * wg, i, j) # circ.u1(wg, i) # circ.u1(wg, j) if usebarrier: circ.barrier() circ.rx(-2 * beta, range(rN)) if usebarrier: circ.barrier() circ.measure(q, c) return circ
class TestStandard2Q(StandardExtensionTest): """Standard Extension Test. Gates with two Qubits""" def setUp(self): self.q = QuantumRegister(3, "q") self.r = QuantumRegister(3, "r") self.c = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.q, self.r, self.c) self.c_header = 69 # lenght of the header def test_barrier_None(self): self.circuit.barrier() qasm_txt = 'barrier q[0],q[1],q[2],r[0],r[1],r[2];' self.assertResult(Barrier, qasm_txt, qasm_txt) def test_barrier_reg_bit(self): self.circuit.barrier(self.q, self.r[0]) qasm_txt = 'barrier q[0],q[1],q[2],r[0];' self.assertResult(Barrier, qasm_txt, qasm_txt) def test_ch_reg_reg(self): qasm_txt = 'ch q[0],r[0];\nch q[1],r[1];\nch q[2],r[2];' instruction_set = self.circuit.ch(self.q, self.r) self.assertStmtsType(instruction_set.instructions, CHGate) self.assertQasm(qasm_txt) def test_ch_reg_reg_inv(self): qasm_txt = 'ch q[0],r[0];\nch q[1],r[1];\nch q[2],r[2];' instruction_set = self.circuit.ch(self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, CHGate) self.assertQasm(qasm_txt) def test_ch_reg_bit(self): qasm_txt = 'ch q[0],r[1];\nch q[1],r[1];\nch q[2],r[1];' instruction_set = self.circuit.ch(self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, CHGate) self.assertQasm(qasm_txt) def test_ch_reg_bit_inv(self): qasm_txt = 'ch q[0],r[1];\nch q[1],r[1];\nch q[2],r[1];' instruction_set = self.circuit.ch(self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, CHGate) self.assertQasm(qasm_txt) def test_ch_bit_reg(self): qasm_txt = 'ch q[1],r[0];\nch q[1],r[1];\nch q[1],r[2];' instruction_set = self.circuit.ch(self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, CHGate) self.assertQasm(qasm_txt) def test_ch_bit_reg_inv(self): qasm_txt = 'ch q[1],r[0];\nch q[1],r[1];\nch q[1],r[2];' instruction_set = self.circuit.ch(self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, CHGate) self.assertQasm(qasm_txt) def test_crz_reg_reg(self): qasm_txt = 'crz(1) q[0],r[0];\ncrz(1) q[1],r[1];\ncrz(1) q[2],r[2];' instruction_set = self.circuit.crz(1, self.q, self.r) self.assertStmtsType(instruction_set.instructions, CrzGate) self.assertQasm(qasm_txt) def test_crz_reg_reg_inv(self): qasm_txt = 'crz(-1) q[0],r[0];\ncrz(-1) q[1],r[1];\ncrz(-1) q[2],r[2];' instruction_set = self.circuit.crz(1, self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, CrzGate) self.assertQasm(qasm_txt) def test_crz_reg_bit(self): qasm_txt = 'crz(1) q[0],r[1];\ncrz(1) q[1],r[1];\ncrz(1) q[2],r[1];' instruction_set = self.circuit.crz(1, self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, CrzGate) self.assertQasm(qasm_txt) def test_crz_reg_bit_inv(self): qasm_txt = 'crz(-1) q[0],r[1];\ncrz(-1) q[1],r[1];\ncrz(-1) q[2],r[1];' instruction_set = self.circuit.crz(1, self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, CrzGate) self.assertQasm(qasm_txt) def test_crz_bit_reg(self): qasm_txt = 'crz(1) q[1],r[0];\ncrz(1) q[1],r[1];\ncrz(1) q[1],r[2];' instruction_set = self.circuit.crz(1, self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, CrzGate) self.assertQasm(qasm_txt) def test_crz_bit_reg_inv(self): qasm_txt = 'crz(-1) q[1],r[0];\ncrz(-1) q[1],r[1];\ncrz(-1) q[1],r[2];' instruction_set = self.circuit.crz(1, self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, CrzGate) self.assertQasm(qasm_txt) def test_cu1_reg_reg(self): qasm_txt = 'cu1(1) q[0],r[0];\ncu1(1) q[1],r[1];\ncu1(1) q[2],r[2];' instruction_set = self.circuit.cu1(1, self.q, self.r) self.assertStmtsType(instruction_set.instructions, Cu1Gate) self.assertQasm(qasm_txt) def test_cu1_reg_reg_inv(self): qasm_txt = 'cu1(-1) q[0],r[0];\ncu1(-1) q[1],r[1];\ncu1(-1) q[2],r[2];' instruction_set = self.circuit.cu1(1, self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, Cu1Gate) self.assertQasm(qasm_txt) def test_cu1_reg_bit(self): qasm_txt = 'cu1(1) q[0],r[1];\ncu1(1) q[1],r[1];\ncu1(1) q[2],r[1];' instruction_set = self.circuit.cu1(1, self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, Cu1Gate) self.assertQasm(qasm_txt) def test_cu1_reg_bit_inv(self): qasm_txt = 'cu1(-1) q[0],r[1];\ncu1(-1) q[1],r[1];\ncu1(-1) q[2],r[1];' instruction_set = self.circuit.cu1(1, self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, Cu1Gate) self.assertQasm(qasm_txt) def test_cu1_bit_reg(self): qasm_txt = 'cu1(1) q[1],r[0];\ncu1(1) q[1],r[1];\ncu1(1) q[1],r[2];' instruction_set = self.circuit.cu1(1, self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, Cu1Gate) self.assertQasm(qasm_txt) def test_cu1_bit_reg_inv(self): qasm_txt = 'cu1(-1) q[1],r[0];\ncu1(-1) q[1],r[1];\ncu1(-1) q[1],r[2];' instruction_set = self.circuit.cu1(1, self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, Cu1Gate) self.assertQasm(qasm_txt) def test_cu3_reg_reg(self): qasm_txt = 'cu3(1,2,3) q[0],r[0];\ncu3(1,2,3) q[1],r[1];\ncu3(1,2,3) q[2],r[2];' instruction_set = self.circuit.cu3(1, 2, 3, self.q, self.r) self.assertStmtsType(instruction_set.instructions, Cu3Gate) self.assertQasm(qasm_txt) def test_cu3_reg_reg_inv(self): qasm_txt = 'cu3(-1,-3,-2) q[0],r[0];\ncu3(-1,-3,-2) q[1],r[1];\ncu3(-1,-3,-2) q[2],r[2];' instruction_set = self.circuit.cu3(1, 2, 3, self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, Cu3Gate) self.assertQasm(qasm_txt) def test_cu3_reg_bit(self): qasm_txt = 'cu3(1,2,3) q[0],r[1];\ncu3(1,2,3) q[1],r[1];\ncu3(1,2,3) q[2],r[1];' instruction_set = self.circuit.cu3(1, 2, 3, self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, Cu3Gate) self.assertQasm(qasm_txt) def test_cu3_reg_bit_inv(self): qasm_txt = 'cu3(-1,-3,-2) q[0],r[1];\ncu3(-1,-3,-2) q[1],r[1];\ncu3(-1,-3,-2) q[2],r[1];' instruction_set = self.circuit.cu3(1, 2, 3, self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, Cu3Gate) self.assertQasm(qasm_txt) def test_cu3_bit_reg(self): qasm_txt = 'cu3(1,2,3) q[1],r[0];\ncu3(1,2,3) q[1],r[1];\ncu3(1,2,3) q[1],r[2];' instruction_set = self.circuit.cu3(1, 2, 3, self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, Cu3Gate) self.assertQasm(qasm_txt) def test_cu3_bit_reg_inv(self): qasm_txt = 'cu3(-1,-3,-2) q[1],r[0];\ncu3(-1,-3,-2) q[1],r[1];\ncu3(-1,-3,-2) q[1],r[2];' instruction_set = self.circuit.cu3(1, 2, 3, self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, Cu3Gate) self.assertQasm(qasm_txt) def test_cx_reg_reg(self): qasm_txt = 'cx q[0],r[0];\ncx q[1],r[1];\ncx q[2],r[2];' instruction_set = self.circuit.cx(self.q, self.r) self.assertStmtsType(instruction_set.instructions, CnotGate) self.assertQasm(qasm_txt) def test_cx_reg_reg_inv(self): qasm_txt = 'cx q[0],r[0];\ncx q[1],r[1];\ncx q[2],r[2];' instruction_set = self.circuit.cx(self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, CnotGate) self.assertQasm(qasm_txt) def test_cx_reg_bit(self): qasm_txt = 'cx q[0],r[1];\ncx q[1],r[1];\ncx q[2],r[1];' instruction_set = self.circuit.cx(self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, CnotGate) self.assertQasm(qasm_txt) def test_cx_reg_bit_inv(self): qasm_txt = 'cx q[0],r[1];\ncx q[1],r[1];\ncx q[2],r[1];' instruction_set = self.circuit.cx(self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, CnotGate) self.assertQasm(qasm_txt) def test_cx_bit_reg(self): qasm_txt = 'cx q[1],r[0];\ncx q[1],r[1];\ncx q[1],r[2];' instruction_set = self.circuit.cx(self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, CnotGate) self.assertQasm(qasm_txt) def test_cx_bit_reg_inv(self): qasm_txt = 'cx q[1],r[0];\ncx q[1],r[1];\ncx q[1],r[2];' instruction_set = self.circuit.cx(self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, CnotGate) self.assertQasm(qasm_txt) def test_cxbase_reg_reg(self): qasm_txt = 'CX q[0],r[0];\nCX q[1],r[1];\nCX q[2],r[2];' instruction_set = self.circuit.cx_base(self.q, self.r) self.assertStmtsType(instruction_set.instructions, CXBase) self.assertQasm(qasm_txt) def test_cxbase_reg_reg_inv(self): qasm_txt = 'CX q[0],r[0];\nCX q[1],r[1];\nCX q[2],r[2];' instruction_set = self.circuit.cx_base(self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, CXBase) self.assertQasm(qasm_txt) def test_cxbase_reg_bit(self): qasm_txt = 'CX q[0],r[1];\nCX q[1],r[1];\nCX q[2],r[1];' instruction_set = self.circuit.cx_base(self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, CXBase) self.assertQasm(qasm_txt) def test_cxbase_reg_bit_inv(self): qasm_txt = 'CX q[0],r[1];\nCX q[1],r[1];\nCX q[2],r[1];' instruction_set = self.circuit.cx_base(self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, CXBase) self.assertQasm(qasm_txt) def test_cxbase_bit_reg(self): qasm_txt = 'CX q[1],r[0];\nCX q[1],r[1];\nCX q[1],r[2];' instruction_set = self.circuit.cx_base(self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, CXBase) self.assertQasm(qasm_txt) def test_cxbase_bit_reg_inv(self): qasm_txt = 'CX q[1],r[0];\nCX q[1],r[1];\nCX q[1],r[2];' instruction_set = self.circuit.cx_base(self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, CXBase) self.assertQasm(qasm_txt) def test_cy_reg_reg(self): qasm_txt = 'cy q[0],r[0];\ncy q[1],r[1];\ncy q[2],r[2];' instruction_set = self.circuit.cy(self.q, self.r) self.assertStmtsType(instruction_set.instructions, CyGate) self.assertQasm(qasm_txt) def test_cy_reg_reg_inv(self): qasm_txt = 'cy q[0],r[0];\ncy q[1],r[1];\ncy q[2],r[2];' instruction_set = self.circuit.cy(self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, CyGate) self.assertQasm(qasm_txt) def test_cy_reg_bit(self): qasm_txt = 'cy q[0],r[1];\ncy q[1],r[1];\ncy q[2],r[1];' instruction_set = self.circuit.cy(self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, CyGate) self.assertQasm(qasm_txt) def test_cy_reg_bit_inv(self): qasm_txt = 'cy q[0],r[1];\ncy q[1],r[1];\ncy q[2],r[1];' instruction_set = self.circuit.cy(self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, CyGate) self.assertQasm(qasm_txt) def test_cy_bit_reg(self): qasm_txt = 'cy q[1],r[0];\ncy q[1],r[1];\ncy q[1],r[2];' instruction_set = self.circuit.cy(self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, CyGate) self.assertQasm(qasm_txt) def test_cy_bit_reg_inv(self): qasm_txt = 'cy q[1],r[0];\ncy q[1],r[1];\ncy q[1],r[2];' instruction_set = self.circuit.cy(self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, CyGate) self.assertQasm(qasm_txt) def test_cz_reg_reg(self): qasm_txt = 'cz q[0],r[0];\ncz q[1],r[1];\ncz q[2],r[2];' instruction_set = self.circuit.cz(self.q, self.r) self.assertStmtsType(instruction_set.instructions, CzGate) self.assertQasm(qasm_txt) def test_cz_reg_reg_inv(self): qasm_txt = 'cz q[0],r[0];\ncz q[1],r[1];\ncz q[2],r[2];' instruction_set = self.circuit.cz(self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, CzGate) self.assertQasm(qasm_txt) def test_cz_reg_bit(self): qasm_txt = 'cz q[0],r[1];\ncz q[1],r[1];\ncz q[2],r[1];' instruction_set = self.circuit.cz(self.q, self.r[1]) self.assertStmtsType(instruction_set.instructions, CzGate) self.assertQasm(qasm_txt) def test_cz_reg_bit_inv(self): qasm_txt = 'cz q[0],r[1];\ncz q[1],r[1];\ncz q[2],r[1];' instruction_set = self.circuit.cz(self.q, self.r[1]).inverse() self.assertStmtsType(instruction_set.instructions, CzGate) self.assertQasm(qasm_txt) def test_cz_bit_reg(self): qasm_txt = 'cz q[1],r[0];\ncz q[1],r[1];\ncz q[1],r[2];' instruction_set = self.circuit.cz(self.q[1], self.r) self.assertStmtsType(instruction_set.instructions, CzGate) self.assertQasm(qasm_txt) def test_cz_bit_reg_inv(self): qasm_txt = 'cz q[1],r[0];\ncz q[1],r[1];\ncz q[1],r[2];' instruction_set = self.circuit.cz(self.q[1], self.r).inverse() self.assertStmtsType(instruction_set.instructions, CzGate) self.assertQasm(qasm_txt) def test_swap_reg_reg(self): qasm_txt = 'swap q[0],r[0];\nswap q[1],r[1];\nswap q[2],r[2];' instruction_set = self.circuit.swap(self.q, self.r) self.assertStmtsType(instruction_set.instructions, SwapGate) self.assertQasm(qasm_txt) def test_swap_reg_reg_inv(self): qasm_txt = 'swap q[0],r[0];\nswap q[1],r[1];\nswap q[2],r[2];' instruction_set = self.circuit.swap(self.q, self.r).inverse() self.assertStmtsType(instruction_set.instructions, SwapGate) self.assertQasm(qasm_txt)
# negative_superposition_state_xbasis.py from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer # Define the Quantum and Classical Registers q = QuantumRegister(1) c = ClassicalRegister(1) # Build the circuit negative_superposition_state_xbasis = QuantumCircuit(q, c) negative_superposition_state_xbasis.x(q) negative_superposition_state_xbasis.h(q) negative_superposition_state_xbasis.barrier() negative_superposition_state_xbasis.h(q) negative_superposition_state_xbasis.measure(q, c) # Execute the circuit job = execute(negative_superposition_state_xbasis, backend = Aer.get_backend('qasm_simulator'), shots=1024) result = job.result() # Print the result print(result.get_counts(negative_superposition_state_xbasis))
def test_fusion_operations(self): """Test Fusion enable/disable option""" shots = 100 num_qubits = 8 qr = QuantumRegister(num_qubits) cr = ClassicalRegister(num_qubits) circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[0]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[1]) circuit.barrier(qr) circuit.cx(qr[1], qr[0]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[0]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[1]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.cx(qr[2], qr[3]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.cx(qr[2], qr[3]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.u3(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.measure(qr, cr) circuit = transpile(circuit, backend=self.SIMULATOR, optimization_level=0) qobj = assemble([circuit], self.SIMULATOR, shots=shots, seed_simulator=1) backend_options = self.fusion_options(enabled=False, threshold=1) result_disabled = self.SIMULATOR.run( qobj, backend_options=backend_options).result() meta_disabled = self.fusion_metadata(result_disabled) backend_options = self.fusion_options(enabled=True, threshold=1) result_enabled = self.SIMULATOR.run( qobj, backend_options=backend_options).result() meta_enabled = self.fusion_metadata(result_enabled) self.assertTrue(getattr(result_disabled, 'success', 'False')) self.assertTrue(getattr(result_enabled, 'success', 'False')) self.assertEqual(meta_disabled, {}) self.assertTrue(meta_enabled.get('applied', False)) self.assertDictAlmostEqual(result_enabled.get_counts(circuit), result_disabled.get_counts(circuit), delta=0.0, msg="fusion for qft was failed")
def construct_circuit( self, parameters: Union[np.ndarray, List[Parameter], ParameterVector], q: Optional[QuantumRegister] = None) -> QuantumCircuit: """ Construct the variational form, given its parameters. Args: parameters: circuit parameters q: Quantum Register for the circuit. Returns: QuantumCircuit: a quantum circuit with given `parameters` Raises: ValueError: the number of parameters is incorrect. ValueError: if num_qubits has not been set and is still None ValueError: only supports single and double excitations at the moment. """ if len(parameters) != self._num_parameters: raise ValueError('The number of parameters has to be {}'.format( self._num_parameters)) if self._num_qubits is None: raise ValueError( 'The number of qubits is None and must be set before the circuit ' 'can be created.') if q is None: q = QuantumRegister(self._num_qubits, name='q') if isinstance(self._initial_state, QuantumCircuit): circuit = QuantumCircuit(q) circuit.append(self._initial_state.to_gate(), range(self._initial_state.num_qubits)) elif self._initial_state is not None: circuit = self._initial_state.construct_circuit('circuit', q) else: circuit = QuantumCircuit(q) count = 0 for _ in range(self._reps): for idx in self._excitations: if len(idx) == 2: i = idx[0] r = idx[1] circuit.p(-parameters[count] / 4 + np.pi / 4, q[i]) circuit.p(-parameters[count] / 4 - np.pi / 4, q[r]) circuit.h(q[i]) circuit.h(q[r]) if self._ladder: for qubit in range(i, r): circuit.cx(q[qubit], q[qubit + 1]) else: circuit.cx(q[i], q[r]) circuit.p(parameters[count], q[r]) if self._ladder: for qubit in range(r, i, -1): circuit.cx(q[qubit - 1], q[qubit]) else: circuit.cx(q[i], q[r]) circuit.h(q[i]) circuit.h(q[r]) circuit.p(-parameters[count] / 4 - np.pi / 4, q[i]) circuit.p(-parameters[count] / 4 + np.pi / 4, q[r]) elif len(idx) == 4: i = idx[0] r = idx[1] j = idx[2] s = idx[3] # pylint: disable=locally-disabled, invalid-name circuit.sdg(q[r]) circuit.h(q[i]) circuit.h(q[r]) circuit.h(q[j]) circuit.h(q[s]) if self._ladder: for qubit in range(i, r): circuit.cx(q[qubit], q[qubit + 1]) circuit.barrier(q[qubit], q[qubit + 1]) else: circuit.cx(q[i], q[r]) circuit.cx(q[r], q[j]) if self._ladder: for qubit in range(j, s): circuit.cx(q[qubit], q[qubit + 1]) circuit.barrier(q[qubit], q[qubit + 1]) else: circuit.cx(q[j], q[s]) circuit.p(parameters[count], q[s]) if self._ladder: for qubit in range(s, j, -1): circuit.cx(q[qubit - 1], q[qubit]) circuit.barrier(q[qubit - 1], q[qubit]) else: circuit.cx(q[j], q[s]) circuit.cx(q[r], q[j]) if self._ladder: for qubit in range(r, i, -1): circuit.cx(q[qubit - 1], q[qubit]) circuit.barrier(q[qubit - 1], q[qubit]) else: circuit.cx(q[i], q[r]) circuit.h(q[i]) circuit.h(q[r]) circuit.h(q[j]) circuit.h(q[s]) circuit.p(-parameters[count] / 2 + np.pi / 2, q[i]) circuit.p(-parameters[count] / 2 + np.pi, q[r]) else: raise ValueError( 'Limited to single and double excitations, ' 'higher order is not implemented') count += 1 return circuit