def test_controlled_random_unitary(self, num_ctrl_qubits): """Test the matrix data of an Operator based on a random UnitaryGate.""" num_target = 2 base_gate = random_unitary(2**num_target).to_instruction() base_mat = base_gate.to_matrix() cgate = base_gate.control(num_ctrl_qubits) test_op = Operator(cgate) cop_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertTrue(matrix_equal(cop_mat, test_op.data, ignore_phase=True))
def test_stinespring_to_operator(self): """Test Stinespring to Operator transformation.""" for mat in self.unitary_mat: chan1 = Operator(mat) chan2 = Operator(Stinespring(mat)) self.assertTrue( matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, Operator, Stinespring(self.depol_stine(0.5)))
def test_controlled_random_unitary(self, num_ctrl_qubits): """test controlled unitary""" num_target = 2 base_gate = UnitaryGate(scipy.stats.unitary_group.rvs(num_target)) base_mat = base_gate.to_matrix() cgate = base_gate.control(num_ctrl_qubits) test_op = Operator(cgate) cop_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertTrue(matrix_equal(cop_mat, test_op.data, ignore_phase=True))
def test_ptm_to_unitary(self): """Test PTM to UnitaryChannel transformation.""" for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = UnitaryChannel(mat) chan2 = UnitaryChannel(PTM(ptm)) self.assertTrue( matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, UnitaryChannel, PTM(self.depol_ptm(0.5)))
def test_open_controlled_unitary_z(self, num_ctrl_qubits, ctrl_state): """Test that UnitaryGate with control returns params.""" umat = np.array([[1, 0], [0, -1]]) ugate = UnitaryGate(umat).control(num_ctrl_qubits, ctrl_state=ctrl_state) ref_mat = _compute_control_matrix(umat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertTrue(matrix_equal(Operator(ugate).data, ref_mat))
def test_stinespring_to_unitary(self): """Test Stinespring to UnitaryChannel transformation.""" for mat in self.unitary_mat: chan1 = UnitaryChannel(mat) chan2 = UnitaryChannel(Stinespring(mat)) self.assertTrue( matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, UnitaryChannel, Stinespring(self.depol_stine(0.5)))
def test_chi_to_unitary(self): """Test Chi to UnitaryChannel transformation.""" for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = UnitaryChannel(mat) chan2 = UnitaryChannel(Chi(chi)) self.assertTrue( matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, UnitaryChannel, Chi(self.depol_chi(0.5)))
def test_kraus_to_unitary(self): """Test Kraus to UnitaryChannel transformation.""" for mat in self.unitary_mat: chan1 = UnitaryChannel(mat) chan2 = UnitaryChannel(Kraus(mat)) self.assertTrue( matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, UnitaryChannel, Kraus(self.depol_kraus(0.5)))
def test_superop_to_unitary(self): """Test SuperOp to UnitaryChannel transformation.""" for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = UnitaryChannel(mat) chan2 = UnitaryChannel(SuperOp(sop)) self.assertTrue( matrix_equal(chan2.data, chan1.data, ignore_phase=True)) self.assertRaises(QiskitError, UnitaryChannel, SuperOp(self.depol_sop(0.5)))
def test_multi_controlled_y_rotation_matrix_basic_mode( self, num_controls, use_basis_gates): """Test the multi controlled Y rotation using the mode 'basic'. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcr.py """ # get the number of required ancilla qubits if num_controls <= 2: num_ancillas = 0 else: num_ancillas = num_controls - 2 q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] theta = 0.871236 * pi if num_ancillas > 0: q_ancillas = QuantumRegister(num_ancillas) qc = QuantumCircuit(q_controls, q_target, q_ancillas) else: qc = QuantumCircuit(q_controls, q_target) q_ancillas = None for idx, bit in enumerate(bitstr): if bit == '0': qc.x(q_controls[idx]) qc.mcry(theta, q_controls, q_target[0], q_ancillas, mode='basic', use_basis_gates=use_basis_gates) for idx, bit in enumerate(bitstr): if bit == '0': qc.x(q_controls[idx]) rot_mat = RYGate(theta).to_matrix() backend = BasicAer.get_backend('unitary_simulator') simulated = execute(qc, backend).result().get_unitary(qc) if num_ancillas > 0: simulated = simulated[:2**(num_controls + 1), :2**(num_controls + 1)] expected = _compute_control_matrix(rot_mat, num_controls, ctrl_state=ctrl_state) with self.subTest(msg='control state = {}'.format(ctrl_state)): self.assertTrue(matrix_equal(simulated, expected))
def test_from_circuit_constructor_reverse_user_specified_layout(self): """Test initialization from a circuit with a user specified reverse layout.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(2) circuit.x(1) circuit.ry(np.pi / 2, 0) layout = Layout({ circuit.qubits[2]: 0, circuit.qubits[1]: 1, circuit.qubits[0]: 2 }) op = Operator.from_circuit(circuit, layout=layout) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 1, 0) layout = Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}) op = Operator.from_circuit(circuit, layout=layout) target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(1, 0) layout = Layout({circuit.qubits[1]: 0, circuit.qubits[0]: 1}) op = Operator.from_circuit(circuit, layout=layout) target = np.kron(self.UI, np.diag([1, 0])) + np.kron( self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent)
def __eq__(self, other): if not isinstance(other, HamiltonianGate): return False if self.label != other.label: return False operators_eq = matrix_equal(self.params[0], other.params[0], ignore_phase=False) times_eq = self.params[1] == other.params[1] return operators_eq and times_eq
def test_multi_control_u3(self): """Test the matrix representation of the controlled and controlled-controlled U3 gate.""" import qiskit.circuit.library.standard_gates.u3 as u3 num_ctrl = 3 # U3 gate params alpha, beta, gamma = 0.2, 0.3, 0.4 # cnu3 gate u3gate = u3.U3Gate(alpha, beta, gamma) cnu3 = u3gate.control(num_ctrl) width = cnu3.num_qubits qr = QuantumRegister(width) qcnu3 = QuantumCircuit(qr) qcnu3.append(cnu3, qr, []) # U3 gate qu3 = QuantumCircuit(1) qu3.u3(alpha, beta, gamma, 0) # CU3 gate qcu3 = QuantumCircuit(2) qcu3.cu3(alpha, beta, gamma, 0, 1) # c-cu3 gate width = 3 qr = QuantumRegister(width) qc_cu3 = QuantumCircuit(qr) cu3gate = u3.CU3Gate(alpha, beta, gamma) c_cu3 = cu3gate.control(1) qc_cu3.append(c_cu3, qr, []) # Circuit unitaries mat_cnu3 = Operator(qcnu3).data mat_u3 = Operator(qu3).data mat_cu3 = Operator(qcu3).data mat_c_cu3 = Operator(qc_cu3).data # Target Controlled-U3 unitary target_cnu3 = _compute_control_matrix(mat_u3, num_ctrl) target_cu3 = np.kron(mat_u3, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0])) target_c_cu3 = np.kron(mat_cu3, np.diag([0, 1])) + np.kron(np.eye(4), np.diag([1, 0])) tests = [('check unitary of u3.control against tensored unitary of u3', target_cu3, mat_cu3), ('check unitary of cu3.control against tensored unitary of cu3', target_c_cu3, mat_c_cu3), ('check unitary of cnu3 against tensored unitary of u3', target_cnu3, mat_cnu3)] for itest in tests: info, target, decomp = itest[0], itest[1], itest[2] with self.subTest(i=info): self.assertTrue(matrix_equal(target, decomp, ignore_phase=True, atol=1e-8, rtol=1e-5))
def test_multi_controlled_rotation_gate_matrices(self, num_controls, base_gate_name, use_basis_gates): """Test the multi controlled rotation gates without ancillas. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcr.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) # iterate over all possible combinations of control qubits for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] theta = 0.871236 * pi qc = QuantumCircuit(q_controls, q_target) for idx, bit in enumerate(bitstr): if bit == '0': qc.x(q_controls[idx]) # call mcrx/mcry/mcrz if base_gate_name == 'y': qc.mcry(theta, q_controls, q_target[0], None, mode='noancilla', use_basis_gates=use_basis_gates) else: # case 'x' or 'z' only support the noancilla mode and do not have this keyword getattr(qc, 'mcr' + base_gate_name)( theta, q_controls, q_target[0], use_basis_gates=use_basis_gates) for idx, bit in enumerate(bitstr): if bit == '0': qc.x(q_controls[idx]) backend = BasicAer.get_backend('unitary_simulator') simulated = execute(qc, backend).result().get_unitary(qc) if base_gate_name == 'x': rot_mat = RXGate(theta).to_matrix() elif base_gate_name == 'y': rot_mat = RYGate(theta).to_matrix() else: # case 'z' rot_mat = U1Gate(theta).to_matrix() expected = _compute_control_matrix(rot_mat, num_controls, ctrl_state=ctrl_state) with self.subTest(msg='control state = {}'.format(ctrl_state)): self.assertTrue(matrix_equal(simulated, expected))
def test_parallel_running(self): """Test that parallel experiments work for this experiment""" backend = AerSimulator.from_backend(FakeParis()) exp1 = CorrelatedReadoutError([0, 2]) exp2 = CorrelatedReadoutError([1, 3]) exp = ParallelExperiment([exp1, exp2]) expdata = exp.run(backend=backend).block_for_results() mit1 = expdata.child_data(0).analysis_results(0).value mit2 = expdata.child_data(1).analysis_results(0).value assignment_matrix1 = mit1.assignment_matrix() assignment_matrix2 = mit2.assignment_matrix() self.assertFalse(matrix_equal(assignment_matrix1, assignment_matrix2))
def test_json_serialization(self): """Verifies that mitigators can be serialized for DB storage""" qubits = [0, 1] backend = AerSimulator.from_backend(FakeParis()) exp = LocalReadoutError(qubits) exp_data = exp.run(backend).block_for_results() mitigator = exp_data.analysis_results(0).value serialized = json.dumps(mitigator, cls=ExperimentEncoder) loaded = json.loads(serialized, cls=ExperimentDecoder) self.assertTrue( matrix_equal(mitigator.assignment_matrix(), loaded.assignment_matrix()))
def test_qv_ideal_probabilities(self): """ Test the probabilities of ideal circuit Compare between simulation and statevector calculation and compare to pre-calculated probabilities with the same seed """ num_of_qubits = 3 qv_exp = QuantumVolume(num_of_qubits, seed=SEED) # set number of trials to a low number to make the test faster qv_exp.set_experiment_options(trials=20) qv_circs = qv_exp.circuits() simulation_probabilities = [ qv_circ.metadata["ideal_probabilities"] for qv_circ in qv_circs ] # create the circuits again, but this time disable simulation so the # ideal probabilities will be calculated using statevector qv_exp = QuantumVolume(num_of_qubits, seed=SEED) qv_exp.set_experiment_options(trials=20) qv_exp._simulation_backend = None qv_circs = qv_exp.circuits() statevector_probabilities = [ qv_circ.metadata["ideal_probabilities"] for qv_circ in qv_circs ] self.assertTrue( matrix_equal(simulation_probabilities, statevector_probabilities), "probabilities calculated using simulation and " "statevector are not the same", ) # compare to pre-calculated probabilities dir_name = os.path.dirname(os.path.abspath(__file__)) probabilities_json_file = "qv_ideal_probabilities.json" with open(os.path.join(dir_name, probabilities_json_file), "r") as json_file: probabilities = json.load(json_file, cls=ExperimentDecoder) self.assertTrue( matrix_equal(simulation_probabilities, probabilities), "probabilities calculated using simulation and " "pre-calculated probabilities are not the same", )
def test_ryy_matrix_representation(self): """Test the matrix representation of the RYY gate. """ from qiskit.extensions.standard.ryy import RYYGate theta = 0.991283 expected = RYYGate(theta).to_matrix() circuit = QuantumCircuit(2) circuit.ryy(theta, 0, 1) backend = BasicAer.get_backend('unitary_simulator') simulated = execute(circuit, backend).result().get_unitary() self.assertTrue(matrix_equal(expected, simulated))
def test_two_qubit_kak_from_paulis(self): """Verify decomposing Paulis with KAK """ pauli_xz = Pauli(label='XZ') unitary = Operator(pauli_xz) decomp_circuit = two_qubit_kak(unitary) result = execute(decomp_circuit, UnitarySimulatorPy()).result() decomp_unitary = Operator(result.get_unitary()) equal_up_to_phase = matrix_equal(unitary.data, decomp_unitary.data, ignore_phase=True, atol=1e-7) self.assertTrue(equal_up_to_phase)
def test_superop_to_stinespring(self): """Test SuperOp to Stinespring transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = Stinespring(mat) chan2 = Stinespring(SuperOp(sop)) self.assertTrue( matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = np.diag([1, 0]) for p in [0.25, 0.5, 0.75, 1]: targ = Stinespring(self.depol_stine(p))._evolve(rho) chan = Stinespring(SuperOp(self.depol_sop(p))) self.assertAllClose(chan._evolve(rho), targ)
def compare_unitary(self, result, circuits, targets, ignore_phase=False, atol=1e-8, rtol=1e-5): """Compare final unitary matrices to targets.""" for pos, test_case in enumerate(zip(circuits, targets)): circuit, target = test_case target = Operator(target) output = Operator(result.get_unitary(circuit)) test_msg = "Circuit ({}/{}):".format(pos + 1, len(circuits)) with self.subTest(msg=test_msg): msg = test_msg + " {} != {}".format(output.data, target.data) delta = matrix_equal(output.data, target.data, ignore_phase=ignore_phase, atol=atol, rtol=rtol) self.assertTrue(delta, msg=msg)
def test_ptm_to_stinespring(self): """Test PTM to Stinespring transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = Kraus(mat) chan2 = Kraus(PTM(ptm)) self.assertTrue( matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(PTM(self.depol_ptm(p)))) self.assertEqual(output, target)
def test_chi_to_kraus(self): """Test Chi to Kraus transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Kraus(mat) chan2 = Kraus(Chi(chi)) self.assertTrue( matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Kraus(self.depol_kraus(p))) output = rho.evolve(Kraus(Chi(self.depol_chi(p)))) self.assertEqual(output, target)
def test_superop_to_stinespring(self): """Test SuperOp to Stinespring transformation.""" # Test unitary channels for mat, sop in zip(self.unitary_mat, self.unitary_sop): chan1 = Stinespring(mat) chan2 = Stinespring(SuperOp(sop)) self.assertTrue( matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = DensityMatrix(np.diag([1, 0])) for p in [0.25, 0.5, 0.75, 1]: target = rho.evolve(Stinespring(self.depol_stine(p))) output = rho.evolve(Stinespring(SuperOp(self.depol_sop(p)))) self.assertEqual(output, target)
def test_ptm_to_stinespring(self): """Test PTM to Stinespring transformation.""" # Test unitary channels for mat, ptm in zip(self.unitary_mat, self.unitary_ptm): chan1 = Kraus(mat) chan2 = Kraus(PTM(ptm)) self.assertTrue( matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = np.diag([1, 0]) for p in [0.25, 0.5, 0.75, 1]: targ = Stinespring(self.depol_stine(p))._evolve(rho) chan = Stinespring(PTM(self.depol_ptm(p))) self.assertAllClose(chan._evolve(rho), targ)
def test_kraus_to_stinespring(self): """Test Kraus to Stinespring transformation.""" # Test unitary channels for mat in self.unitary_mat: chan1 = Stinespring(mat) chan2 = Stinespring(Kraus(mat)) self.assertTrue( matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = np.diag([1, 0]) for p in [0.25, 0.5, 0.75, 1]: targ = Stinespring(self.depol_stine(p))._evolve(rho) chan = Stinespring(Kraus(self.depol_kraus(p))) self.assertAllClose(chan._evolve(rho), targ)
def test_chi_to_kraus(self): """Test Chi to Kraus transformation.""" # Test unitary channels for mat, chi in zip(self.unitary_mat, self.unitary_chi): chan1 = Kraus(mat) chan2 = Kraus(Chi(chi)) self.assertTrue( matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True)) # Test depolarizing channels rho = np.diag([1, 0]) for p in [0.25, 0.5, 0.75, 1]: targ = Kraus(self.depol_kraus(p))._evolve(rho) chan = Kraus(Chi(self.depol_chi(p))) self.assertAllClose(chan._evolve(rho), targ)
def test_two_qubit_kak(self): """Verify KAK decomposition for random Haar 4x4 unitaries. """ for _ in range(100): unitary = random_unitary(4) with self.subTest(unitary=unitary): decomp_circuit = two_qubit_kak(unitary) result = execute(decomp_circuit, UnitarySimulatorPy()).result() decomp_unitary = Operator(result.get_unitary()) equal_up_to_phase = matrix_equal(unitary.data, decomp_unitary.data, ignore_phase=True, atol=1e-7) self.assertTrue(equal_up_to_phase)
def test_local_analysis(self): """Tests local mitigator generation from experimental data""" qubits = [0, 1, 2] run_data = [ { "counts": { "000": 986, "010": 10, "100": 16, "001": 12 }, "metadata": { "state_label": "000" }, "shots": 1024, }, { "counts": { "111": 930, "110": 39, "011": 24, "101": 29, "010": 1, "100": 1 }, "metadata": { "state_label": "111" }, "shots": 1024, }, ] expected_assignment_matrices = [ np.array([[0.98828125, 0.04003906], [0.01171875, 0.95996094]]), np.array([[0.99023438, 0.02929688], [0.00976562, 0.97070312]]), np.array([[0.984375, 0.02441406], [0.015625, 0.97558594]]), ] run_meta = {"physical_qubits": qubits} expdata = ExperimentData() expdata.add_data(run_data) expdata._metadata = run_meta exp = LocalReadoutError(qubits) result = exp.analysis.run(expdata) mitigator = result.analysis_results(0).value self.assertEqual(len(qubits), mitigator._num_qubits) self.assertEqual(qubits, mitigator._qubits) self.assertTrue( matrix_equal(expected_assignment_matrices, mitigator._assignment_mats))
def test_circuit_init(self): """Test initialization from a circuit.""" # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) op = Operator(circuit) y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]]) target = np.kron(y90, np.kron(self.UX, self.UH)) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.cp(lam, 0, 1) op = Operator(circuit) target = np.diag([1, 1, 1, np.exp(1j * lam)]) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circuit.ch(0, 1) op = Operator(circuit) target = np.kron(self.UI, np.diag([1, 0])) + np.kron( self.UH, np.diag([0, 1])) global_phase_equivalent = matrix_equal(op.data, target, ignore_phase=True) self.assertTrue(global_phase_equivalent)