def test_control_removal(self): """Should replace CX by X.""" # ┌───┐ # q_0: ┤ X ├──■── # └───┘┌─┴─┐ # q_1: ─────┤ X ├ # └───┘ circuit = QuantumCircuit(2) circuit.x(0) circuit.cx(0, 1) # ┌───┐ # q_0: ┤ X ├ # ├───┤ # q_1: ┤ X ├ # └───┘ expected = QuantumCircuit(2) expected.x(0) expected.x(1) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=5) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) # Should replace CZ by Z # # ┌───┐ ┌───┐ # q_0: ┤ H ├─■─┤ H ├ # ├───┤ │ └───┘ # q_1: ┤ X ├─■────── # └───┘ circuit = QuantumCircuit(2) circuit.h(0) circuit.x(1) circuit.cz(0, 1) circuit.h(0) # ┌───┐┌───┐┌───┐ # q_0: ┤ H ├┤ Z ├┤ H ├ # ├───┤└───┘└───┘ # q_1: ┤ X ├────────── # └───┘ expected = QuantumCircuit(2) expected.h(0) expected.x(1) expected.z(0) expected.h(0) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=5) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected))
def test_is_good_state_statevector(self): """Test StateVector is_good_state""" oracle = QuantumCircuit(2) oracle.cz(0, 1) is_good_state = Statevector.from_label('11') grover = Grover(oracle=oracle, good_state=is_good_state) self.assertTrue(grover._is_good_state.equiv(Statevector.from_label('11')))
def test_lnn_cnot_removal(self): """ Should remove some cnots from swaps introduced because of linear nearest architecture. Only uses single-gate optimization techniques. """ circuit = QuantumCircuit(5) circuit.h(0) for i in range(0, 3): circuit.cx(i, i + 1) circuit.cx(i + 1, i) circuit.cx(i, i + 1) circuit.cx(3, 4) for i in range(3, 0, -1): circuit.cx(i - 1, i) circuit.cx(i, i - 1) expected = QuantumCircuit(5) expected.h(0) for i in range(0, 3): expected.cx(i, i + 1) expected.cx(i + 1, i) expected.cx(3, 4) for i in range(3, 0, -1): expected.cx(i, i - 1) stv = Statevector.from_label('0' * circuit.num_qubits) self.assertEqual(stv @ circuit, stv @ expected) pass_ = HoareOptimizer(size=0) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected))
def generateQubits(): # Creating registers with n qubits qr = QuantumRegister(chunk, name='qr') cr = ClassicalRegister(chunk, name='cr') # Quantum circuit for alice state alice = QuantumCircuit(qr, cr, name='Alice') # Generate a random number in the range of available qubits [0,65536)) temp_alice_key = randomStringGen(chunk) #app.logger.info("key: ", temp_alice_key) # Switch randomly about half qubits to diagonal basis alice_table = np.array([]) for index in range(len(qr)): if 0.5 < int(randomStringGen(1)): # change to diagonal basis alice.h(qr[index]) alice_table = np.append(alice_table, 'X') else: # stay in computational basis alice_table = np.append(alice_table, 'Z') # Reverse basis table alice_table = alice_table[::-1] # Generate a statevector initialised with the random generated string sve = Statevector.from_label(temp_alice_key) # Evolve stetavector in generated circuit qubits = sve.evolve(alice) # return quantum circuit, basis table and temporary key return qubits, alice_table, temp_alice_key
def test_max_power(self): """Test the iteration stops when the maximum power is reached.""" lam = 10.0 grover = Grover(growth_rate=lam, quantum_instance=self.statevector) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) result = grover.amplify(problem) self.assertEqual(len(result.iterations), 0)
def run(self): global ready global singlets global stop # circuit for singlet generation qre = QuantumRegister(2, name='qre') cre = ClassicalRegister(2, name='cre') singlet = QuantumCircuit(qre, cre, name='Alice') singlet.x(qre[0]) singlet.x(qre[1]) singlet.h(qre[0]) singlet.cx(qre[0],qre[1]) while(True): if ready == False: # generate singlets for i in range(numberOfSinglets): sve = Statevector.from_label('00') entangledBits = sve.evolve(singlet) singlets.append(entangledBits) if stop: break # signal that singlet generation is complete ready = True
def assertBooleanFunctionIsCorrect(self, boolean_circuit, reference): """Assert that ``boolean_circuit`` implements the reference boolean function correctly.""" circuit = QuantumCircuit(boolean_circuit.num_qubits) circuit.h(list(range(boolean_circuit.num_variable_qubits))) circuit.append(boolean_circuit.to_instruction(), list(range(boolean_circuit.num_qubits))) # compute the statevector of the circuit statevector = Statevector.from_label('0' * circuit.num_qubits) statevector = statevector.evolve(circuit) # trace out ancillas probabilities = statevector.probabilities( qargs=list(range(boolean_circuit.num_variable_qubits + 1))) # compute the expected outcome by computing the entries of the statevector that should # have a 1 / sqrt(2**n) factor expectations = np.zeros_like(probabilities) for x in range(2**boolean_circuit.num_variable_qubits): bits = np.array(list( bin(x)[2:].zfill(boolean_circuit.num_variable_qubits)), dtype=int) result = reference(bits[::-1]) entry = int( str(int(result)) + bin(x)[2:].zfill(boolean_circuit.num_variable_qubits), 2) expectations[entry] = 1 / 2**boolean_circuit.num_variable_qubits np.testing.assert_array_almost_equal(probabilities, expectations)
def randomStringGen(string_length): if prefs['rng']['rand'] == 'trng': #output variables used to access quantum computer results at the end of the function output = '' n = string_length temp_n = 10 temp_output = '' for i in range(math.ceil(n / temp_n)): #initialize quantum registers for circuit q = QuantumRegister(temp_n, name='q') c = ClassicalRegister(temp_n, name='c') rs = QuantumCircuit(q, c, name='rs') rs.h(range(temp_n)) label = '0' * temp_n #execute circuit and extract 0s and 1s from key sve = Statevector.from_label(label) res = sve.evolve(rs) temp_output = res.measure()[0] output += temp_output #return output clipped to size of desired string length return output[:n] else: return ''.join(str(random.randint(0, 1)) for i in range(string_length))
def test_circuit_multi(self): """Test circuit multi regs declared at start.""" qreg0 = QuantumRegister(2, 'q0') creg0 = ClassicalRegister(2, 'c0') qreg1 = QuantumRegister(2, 'q1') creg1 = ClassicalRegister(2, 'c1') circ = QuantumCircuit(qreg0, qreg1) circ.x(qreg0[1]) circ.x(qreg1[0]) meas = QuantumCircuit(qreg0, qreg1, creg0, creg1) meas.measure(qreg0, creg0) meas.measure(qreg1, creg1) qc = circ + meas backend_sim = BasicAer.get_backend('qasm_simulator') result = execute(qc, backend_sim, seed_transpiler=34342).result() counts = result.get_counts(qc) target = {'01 10': 1024} backend_sim = BasicAer.get_backend('statevector_simulator') result = execute(circ, backend_sim, seed_transpiler=3438).result() state = result.get_statevector(circ) backend_sim = BasicAer.get_backend('unitary_simulator') result = execute(circ, backend_sim, seed_transpiler=3438).result() unitary = result.get_unitary(circ) self.assertEqual(counts, target) self.assertAlmostEqual(state_fidelity(Statevector.from_label('0110'), state), 1.0, places=7) self.assertAlmostEqual(process_fidelity(Operator.from_label('IXXI'), unitary), 1.0, places=7)
def test_from_int(self): """Initialize from int.""" desired_sv = Statevector.from_label("110101") qc = QuantumCircuit(6) qc.initialize(53, range(6)) actual_sv = Statevector.from_instruction(qc) self.assertTrue(desired_sv == actual_sv)
def test_oracle_statevector(self): """Test StateVector oracle""" mark_state = Statevector.from_label('11') grover = Grover(oracle=mark_state, good_state=['11']) grover_op = grover._grover_operator self.assertTrue( Operator(grover_op).equiv(Operator(self._expected_grover_op)))
def test_iterations_with_good_state(self, iterations): """Test the algorithm with different iteration types and with good state""" grover = Grover(iterations, quantum_instance=self.statevector) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111")
def test_prepare_from_int(self): """Prepare state from int.""" desired_sv = Statevector.from_label("110101") qc = QuantumCircuit(6) qc.prepare_state(53, range(6)) actual_sv = Statevector(qc) self.assertTrue(desired_sv == actual_sv)
def test_prepare_from_label(self): """Prepare state from label.""" desired_sv = Statevector.from_label("01+-lr") qc = QuantumCircuit(6) qc.prepare_state("01+-lr", range(6)) actual_sv = Statevector(qc) self.assertTrue(desired_sv == actual_sv)
def test_from_labels(self): """Initialize from labels.""" desired_sv = Statevector.from_label("01+-lr") qc = QuantumCircuit(6) qc.initialize("01+-lr", range(6)) actual_sv = Statevector.from_instruction(qc) self.assertTrue(desired_sv == actual_sv)
def test_phasegate_removal(self): """Should remove the phase on a classical state, but not on a superposition state. """ # ┌───┐ # q_0: ┤ Z ├────── # ├───┤┌───┐ # q_1:─┤ H ├┤ Z ├─ # └───┘└───┘ circuit = QuantumCircuit(3) circuit.z(0) circuit.h(1) circuit.z(1) # q_0: ─────────── # ┌───┐┌───┐ # q_1:─┤ H ├┤ Z ├─ # └───┘└───┘ expected = QuantumCircuit(3) expected.h(1) expected.z(1) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=0) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected))
def test_mcmt_v_chain_simulation(self, cgate, num_controls, num_targets): """Test the MCMT V-chain implementation test on a simulation.""" controls = QuantumRegister(num_controls) targets = QuantumRegister(num_targets) subsets = [tuple(range(i)) for i in range(num_controls + 1)] for subset in subsets: qc = QuantumCircuit(targets, controls) # Initialize all targets to 1, just to be sure that # the generic gate has some effect (f.e. Z gate has no effect # on a 0 state) qc.x(targets) num_ancillas = max(0, num_controls - 1) if num_ancillas > 0: ancillas = QuantumRegister(num_ancillas) qc.add_register(ancillas) qubits = controls[:] + targets[:] + ancillas[:] else: qubits = controls[:] + targets[:] for i in subset: qc.x(controls[i]) mcmt = MCMTVChain(cgate, num_controls, num_targets) qc.compose(mcmt, qubits, inplace=True) for i in subset: qc.x(controls[i]) vec = Statevector.from_label("0" * qc.num_qubits).evolve(qc) # target register is initially |11...1>, with length equal to 2**(n_targets) vec_exp = np.array([0] * (2 ** (num_targets) - 1) + [1]) if isinstance(cgate, CZGate): # Z gate flips the last qubit only if it's applied an odd number of times if len(subset) == num_controls and (num_controls % 2) == 1: vec_exp[-1] = -1 elif isinstance(cgate, CHGate): # if all the control qubits have been activated, # we repeatedly apply the kronecker product of the Hadamard # with itself and then multiply the results for the original # state of the target qubits if len(subset) == num_controls: h_i = 1 / np.sqrt(2) * np.array([[1, 1], [1, -1]]) h_tot = np.array([1]) for _ in range(num_targets): h_tot = np.kron(h_tot, h_i) vec_exp = np.dot(h_tot, vec_exp) else: raise ValueError(f"Test not implement for gate: {cgate}") # append the remaining part of the state vec_exp = np.concatenate( (vec_exp, [0] * (2 ** (num_controls + num_ancillas + num_targets) - vec_exp.size)) ) f_i = state_fidelity(vec, vec_exp) self.assertAlmostEqual(f_i, 1)
def test_larger_circuit(self, gradient_function): op = (Y ^ Z) + 3 * (X ^ X) + (Z ^ I) + (I ^ Z) + (I ^ X) op = op.to_matrix_op().primitive theta = [0.275932, 0.814824, 0.670661, 0.627729, 0.596198] ansatz = QuantumCircuit(2) ansatz.h([0, 1]) ansatz.ry(theta[0], 0) ansatz.ry(theta[1], 1) ansatz.rz(theta[2], 0) ansatz.rz(theta[3], 1) ansatz.cx(0, 1) ansatz.crx(theta[4], 1, 0) init = Statevector.from_label('00') # set up gradient object and compute gradient grad = StateGradient(op, ansatz, init) grads = getattr(grad, gradient_function)() ref = [1.2990890015773053, 0.47864124516756174, 1.9895319019377231, 0.09137636702470253, 0.40256649191876637] np.testing.assert_array_almost_equal(grads, ref)
def test_lnncnot_advanced_removal(self): """Should remove all cnots from swaps introduced because of linear nearest architecture. This time using multi-gate optimization techniques. """ circuit = QuantumCircuit(5) circuit.h(0) for i in range(0, 3): circuit.cx(i, i + 1) circuit.cx(i + 1, i) circuit.cx(i, i + 1) circuit.cx(3, 4) for i in range(3, 0, -1): circuit.cx(i - 1, i) circuit.cx(i, i - 1) expected = QuantumCircuit(5) expected.h(0) for i in range(0, 4): expected.cx(i, i + 1) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=6) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected))
def test_targetsuccessive_identity_removal(self): """Should remove pair of controlled target successive which are the inverse of each other, if they can be identified to be executed as a unit (either both or none). """ circuit = QuantumCircuit(3) circuit.h(0) circuit.h(1) circuit.h(2) circuit.ccx(0, 1, 2) circuit.cx(1, 0) circuit.x(0) circuit.ccx(0, 1, 2) expected = QuantumCircuit(3) expected.h(0) expected.h(1) expected.h(2) expected.cx(1, 0) expected.x(0) stv = Statevector.from_label("0" * circuit.num_qubits) self.assertEqual(stv & circuit, stv & expected) pass_ = HoareOptimizer(size=4) result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected))
def test_fixed_iterations(self): """Test the iterations argument""" grover = Grover(iterations=2, quantum_instance=self.statevector) problem = AmplificationProblem(Statevector.from_label('111'), is_good_state=['111']) result = grover.amplify(problem) self.assertEqual(result.top_measurement, '111')
def test_growth_rate(self): """Test running the algorithm on a growth rate""" grover = Grover(growth_rate=8 / 7, quantum_instance=self.statevector) problem = AmplificationProblem(Statevector.from_label('111'), is_good_state=['111']) result = grover.amplify(problem) self.assertEqual(result.top_measurement, '111')
def test_run_state_vector_oracle(self): """Test execution with a state vector oracle""" mark_state = Statevector.from_label('11') problem = AmplificationProblem(mark_state, is_good_state=['11']) grover = Grover(quantum_instance=self.qasm) result = grover.amplify(problem) self.assertIn(result.top_measurement, ['11'])
def test_quantum_info_input(self): """Test passing quantum_info.Operator and Statevector as input.""" mark = Statevector.from_label('001') diffuse = 2 * DensityMatrix.from_label('000') - Operator.from_label('III') grover_op = GroverOperator(oracle=mark, zero_reflection=diffuse) self.assertGroverOperatorIsCorrect(grover_op, oracle=np.diag((-1) ** mark.data), zero_reflection=diffuse.data)
def test_iterations_without_good_state(self, iterations): """Test the correct error is thrown for none/list of iterations and without good state""" grover = Grover(iterations, quantum_instance=self.statevector) problem = AmplificationProblem(Statevector.from_label("111")) with self.assertRaisesRegex( TypeError, "An is_good_state function is required with the provided oracle" ): grover.amplify(problem)
def test_multiple_iterations(self): """Test the algorithm for a list of iterations.""" grover = Grover(iterations=[1, 2, 3], quantum_instance=self.statevector) problem = AmplificationProblem(Statevector.from_label('111'), is_good_state=['111']) result = grover.amplify(problem) self.assertEqual(result.top_measurement, '111')
def test_statevector(self): """Initialize gates from a statevector.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/5134 (footnote) desired_vector = [0, 0, 0, 1] qc = QuantumCircuit(2) statevector = Statevector.from_label("11") qc.initialize(statevector, [0, 1]) self.assertEqual(qc.data[0][0].params, desired_vector)
def setUp(self): super().setUp() self._oracle = Statevector.from_label('111') self._expected_grover_op = GroverOperator(oracle=self._oracle) self._expected = QuantumCircuit(self._expected_grover_op.num_qubits) self._expected.compose(self._expected_grover_op.state_preparation, inplace=True) self._expected.compose(self._expected_grover_op.power(2), inplace=True) backend = BasicAer.get_backend('statevector_simulator') self._sv = QuantumInstance(backend)
def _init_grover_ops(self): """ Inits grover oracles for the actions set :return: a list of qiskit instructions ready to be appended to circuit """ states_binars = [format(i, '0{}b'.format(self.acts_reg_dim)) for i in range(self.acts_dim)] targ_states = [Statevector.from_label(s) for s in states_binars] grops = [GroverOperator(oracle=ts) for ts in targ_states] return [g.to_instruction() for g in grops]
def test_state_to_matrix(self): """ state to matrix test """ np.testing.assert_array_equal(Zero.to_matrix(), np.array([1, 0])) np.testing.assert_array_equal(One.to_matrix(), np.array([0, 1])) np.testing.assert_array_almost_equal(Plus.to_matrix(), (Zero.to_matrix() + One.to_matrix()) / (np.sqrt(2))) np.testing.assert_array_almost_equal(Minus.to_matrix(), (Zero.to_matrix() - One.to_matrix()) / (np.sqrt(2))) # TODO Not a great test because doesn't test against validated values # or test internal representation. Fix this. gnarly_state = (One ^ Plus ^ Zero ^ Minus * .3) @ \ StateFn(Statevector.from_label('r0+l')) + (StateFn(X ^ Z ^ Y ^ I) * .1j) gnarly_mat = gnarly_state.to_matrix() gnarly_mat_separate = (One ^ Plus ^ Zero ^ Minus * .3).to_matrix() gnarly_mat_separate = np.dot(gnarly_mat_separate, StateFn(Statevector.from_label('r0+l')).to_matrix()) gnarly_mat_separate = gnarly_mat_separate + (StateFn(X ^ Z ^ Y ^ I) * .1j).to_matrix() np.testing.assert_array_almost_equal(gnarly_mat, gnarly_mat_separate)