def test_primitive_strings(self): """ get primitives test """ self.assertEqual(X.primitive_strings(), {'Pauli'}) gnarly_op = 3 * (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + \ PrimitiveOp(Operator.from_label('+r0IX').data) self.assertEqual(gnarly_op.primitive_strings(), {'QuantumCircuit', 'Matrix'})
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_controlled_standard_gates(self, num_ctrl_qubits, gate_class): """Test controlled versions of all standard gates.""" theta = pi / 2 ctrl_state_ones = 2**num_ctrl_qubits - 1 ctrl_state_zeros = 0 ctrl_state_mixed = ctrl_state_ones >> int(num_ctrl_qubits / 2) numargs = len(_get_free_params(gate_class)) args = [theta] * numargs if gate_class in [MSGate, Barrier]: args[0] = 2 elif gate_class in [MCU1Gate, MCPhaseGate]: args[1] = 2 elif issubclass(gate_class, MCXGate): args = [5] gate = gate_class(*args) for ctrl_state in { ctrl_state_ones, ctrl_state_zeros, ctrl_state_mixed }: with self.subTest(i='{0}, ctrl_state={1}'.format( gate_class.__name__, ctrl_state)): if hasattr( gate, 'num_ancilla_qubits') and gate.num_ancilla_qubits > 0: # skip matrices that include ancilla qubits continue try: cgate = gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) except (AttributeError, QiskitError): # 'object has no attribute "control"' # skipping Id and Barrier continue if gate.name == 'rz': iden = Operator.from_label('I') zgen = Operator.from_label('Z') base_mat = (np.cos(0.5 * theta) * iden - 1j * np.sin(0.5 * theta) * zgen).data else: base_mat = Operator(gate).data target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat))
def test_adjoint(self): """adjoint test""" gnarly_op = 3 * (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + PrimitiveOp( Operator.from_label("+r0IX").data) np.testing.assert_array_almost_equal( np.conj(np.transpose(gnarly_op.to_matrix())), gnarly_op.adjoint().to_matrix())
def test_evals(self): """ evals test """ # pylint: disable=no-member # TODO: Think about eval names self.assertEqual(Z.eval('0').eval('0'), 1) self.assertEqual(Z.eval('1').eval('0'), 0) self.assertEqual(Z.eval('0').eval('1'), 0) self.assertEqual(Z.eval('1').eval('1'), -1) self.assertEqual(X.eval('0').eval('0'), 0) self.assertEqual(X.eval('1').eval('0'), 1) self.assertEqual(X.eval('0').eval('1'), 1) self.assertEqual(X.eval('1').eval('1'), 0) self.assertEqual(Y.eval('0').eval('0'), 0) self.assertEqual(Y.eval('1').eval('0'), -1j) self.assertEqual(Y.eval('0').eval('1'), 1j) self.assertEqual(Y.eval('1').eval('1'), 0) with self.assertRaises(ValueError): Y.eval('11') with self.assertRaises(ValueError): (X ^ Y).eval('1111') with self.assertRaises(ValueError): Y.eval((X ^ X).to_matrix_op()) # Check that Pauli logic eval returns same as matrix logic self.assertEqual(PrimitiveOp(Z.to_matrix()).eval('0').eval('0'), 1) self.assertEqual(PrimitiveOp(Z.to_matrix()).eval('1').eval('0'), 0) self.assertEqual(PrimitiveOp(Z.to_matrix()).eval('0').eval('1'), 0) self.assertEqual(PrimitiveOp(Z.to_matrix()).eval('1').eval('1'), -1) self.assertEqual(PrimitiveOp(X.to_matrix()).eval('0').eval('0'), 0) self.assertEqual(PrimitiveOp(X.to_matrix()).eval('1').eval('0'), 1) self.assertEqual(PrimitiveOp(X.to_matrix()).eval('0').eval('1'), 1) self.assertEqual(PrimitiveOp(X.to_matrix()).eval('1').eval('1'), 0) self.assertEqual(PrimitiveOp(Y.to_matrix()).eval('0').eval('0'), 0) self.assertEqual(PrimitiveOp(Y.to_matrix()).eval('1').eval('0'), -1j) self.assertEqual(PrimitiveOp(Y.to_matrix()).eval('0').eval('1'), 1j) self.assertEqual(PrimitiveOp(Y.to_matrix()).eval('1').eval('1'), 0) pauli_op = Z ^ I ^ X ^ Y mat_op = PrimitiveOp(pauli_op.to_matrix()) full_basis = list(map(''.join, itertools.product('01', repeat=pauli_op.num_qubits))) for bstr1, bstr2 in itertools.product(full_basis, full_basis): # print('{} {} {} {}'.format(bstr1, bstr2, pauli_op.eval(bstr1, bstr2), # mat_op.eval(bstr1, bstr2))) np.testing.assert_array_almost_equal(pauli_op.eval(bstr1).eval(bstr2), mat_op.eval(bstr1).eval(bstr2)) gnarly_op = SummedOp([(H ^ I ^ Y).compose(X ^ X ^ Z).tensor(Z), PrimitiveOp(Operator.from_label('+r0I')), 3 * (X ^ CX ^ T)], coeff=3 + .2j) gnarly_mat_op = PrimitiveOp(gnarly_op.to_matrix()) full_basis = list(map(''.join, itertools.product('01', repeat=gnarly_op.num_qubits))) for bstr1, bstr2 in itertools.product(full_basis, full_basis): np.testing.assert_array_almost_equal(gnarly_op.eval(bstr1).eval(bstr2), gnarly_mat_op.eval(bstr1).eval(bstr2))
def test_primitive_strings(self): """get primitives test""" self.assertEqual(X.primitive_strings(), {"Pauli"}) gnarly_op = 3 * (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + PrimitiveOp( Operator.from_label("+r0IX").data) self.assertEqual(gnarly_op.primitive_strings(), {"QuantumCircuit", "Matrix"})
def test_channel_gate_error(self): """Test the gate_error function for channel inputs""" depol = Choi(np.eye(4) / 2) iden = Choi(Operator.from_label('I')) # Depolarizing channel prob = 0.11 chan = prob * depol + (1 - prob) * iden err = gate_error(chan, require_cp=True, require_tp=True) target = 1 - average_gate_fidelity(chan) self.assertAlmostEqual(err, target, places=7) # Depolarizing channel prob = 0.5 op = Operator.from_label('Y') chan = (prob * depol + (1 - prob) * iden) @ op err = gate_error(chan, op, require_cp=True, require_tp=True) target = 1 - average_gate_fidelity(chan, op) self.assertAlmostEqual(err, target, places=7)
def test_to_pauli_op(self): """ Test to_pauli_op method """ gnarly_op = 3 * (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + \ PrimitiveOp(Operator.from_label('+r0IX').data) mat_op = gnarly_op.to_matrix_op() pauli_op = gnarly_op.to_pauli_op() self.assertIsInstance(pauli_op, SummedOp) for p in pauli_op: self.assertIsInstance(p, PauliOp) np.testing.assert_array_almost_equal(mat_op.to_matrix(), pauli_op.to_matrix())
def test_to_matrix(self): """to matrix text """ np.testing.assert_array_equal(X.to_matrix(), Operator.from_label('X').data) np.testing.assert_array_equal(Y.to_matrix(), Operator.from_label('Y').data) np.testing.assert_array_equal(Z.to_matrix(), Operator.from_label('Z').data) op1 = Y + H np.testing.assert_array_almost_equal(op1.to_matrix(), Y.to_matrix() + H.to_matrix()) op2 = op1 * .5 np.testing.assert_array_almost_equal(op2.to_matrix(), op1.to_matrix() * .5) op3 = (4 - .6j) * op2 np.testing.assert_array_almost_equal(op3.to_matrix(), op2.to_matrix() * (4 - .6j)) op4 = op3.tensor(X) np.testing.assert_array_almost_equal(op4.to_matrix(), np.kron(op3.to_matrix(), X.to_matrix())) op5 = op4.compose(H ^ I) np.testing.assert_array_almost_equal(op5.to_matrix(), np.dot(op4.to_matrix(), (H ^ I).to_matrix())) op6 = op5 + PrimitiveOp(Operator.from_label('+r').data) np.testing.assert_array_almost_equal( op6.to_matrix(), op5.to_matrix() + Operator.from_label('+r').data) param = Parameter("α") m = np.array([[0, -1j], [1j, 0]]) op7 = MatrixOp(m, param) np.testing.assert_array_equal(op7.to_matrix(), m * param) param = Parameter("β") op8 = PauliOp(primitive=Pauli("Y"), coeff=param) np.testing.assert_array_equal(op8.to_matrix(), m * param) param = Parameter("γ") qc = QuantumCircuit(1) qc.h(0) op9 = CircuitOp(qc, coeff=param) m = np.array([[1, 1], [1, -1]]) / np.sqrt(2) np.testing.assert_array_equal(op9.to_matrix(), m * param)
def test_controlled_standard_gates(self, num_ctrl_qubits): """Test controlled versions of all standard gates.""" gate_classes = [ cls for cls in allGates.__dict__.values() if isinstance(cls, type) ] theta = pi / 2 for cls in gate_classes: with self.subTest(i=cls): numargs = len(_get_free_params(cls)) args = [theta] * numargs if cls in [MSGate, Barrier]: args[0] = 2 elif cls in [MCU1Gate]: args[1] = 2 elif issubclass(cls, MCXGate): args = [5] gate = cls(*args) if hasattr( gate, 'num_ancilla_qubits') and gate.num_ancilla_qubits > 0: # skip matrices that include ancilla qubits continue try: cgate = gate.control(num_ctrl_qubits) except (AttributeError, QiskitError): # 'object has no attribute "control"' # skipping Id and Barrier continue if gate.name == 'rz': iden = Operator.from_label('I') zgen = Operator.from_label('Z') base_mat = (np.cos(0.5 * theta) * iden - 1j * np.sin(0.5 * theta) * zgen).data else: base_mat = Operator(gate).data target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertTrue( matrix_equal(Operator(cgate).data, target_mat, ignore_phase=True))
def test_controlled_standard_gates(self, num_ctrl_qubits): """ Test controlled versions of all standard gates. """ gate_classes = [ cls for name, cls in allGates.__dict__.items() if isinstance(cls, type) ] theta = pi / 2 for cls in gate_classes: with self.subTest(i=cls): sig = signature(cls) numargs = len([ param for param in sig.parameters.values() if param.kind == param.POSITIONAL_ONLY or ( param.kind == param.POSITIONAL_OR_KEYWORD and param.default is param.empty) ]) args = [theta] * numargs if cls in [MSGate, Barrier]: args[0] = 2 gate = cls(*args) try: cgate = gate.control(num_ctrl_qubits) except (AttributeError, QiskitError): # 'object has no attribute "control"' # skipping Id and Barrier continue if gate.name == 'rz': iden = Operator.from_label('I') zgen = Operator.from_label('Z') base_mat = (np.cos(0.5 * theta) * iden - 1j * np.sin(0.5 * theta) * zgen).data else: base_mat = Operator(gate).data target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertTrue( matrix_equal(Operator(cgate).data, target_mat, ignore_phase=True))
def test_io_consistency(self): """consistency test""" new_op = X ^ Y ^ I label = "XYI" # label = new_op.primitive.to_label() self.assertEqual(str(new_op.primitive), label) np.testing.assert_array_almost_equal(new_op.primitive.to_matrix(), Operator.from_label(label).data) self.assertEqual(new_op.primitive, Pauli(label)) x_mat = X.primitive.to_matrix() y_mat = Y.primitive.to_matrix() i_mat = np.eye(2, 2) np.testing.assert_array_almost_equal( new_op.primitive.to_matrix(), np.kron(np.kron(x_mat, y_mat), i_mat)) hi = np.kron(H.to_matrix(), I.to_matrix()) hi2 = Operator.from_label("HI").data hi3 = (H ^ I).to_matrix() np.testing.assert_array_almost_equal(hi, hi2) np.testing.assert_array_almost_equal(hi2, hi3) xy = np.kron(X.to_matrix(), Y.to_matrix()) xy2 = Operator.from_label("XY").data xy3 = (X ^ Y).to_matrix() np.testing.assert_array_almost_equal(xy, xy2) np.testing.assert_array_almost_equal(xy2, xy3) # Check if numpy array instantiation is the same as from Operator matrix_op = Operator.from_label("+r") np.testing.assert_array_almost_equal( PrimitiveOp(matrix_op).to_matrix(), PrimitiveOp(matrix_op.data).to_matrix()) # Ditto list of lists np.testing.assert_array_almost_equal( PrimitiveOp(matrix_op.data.tolist()).to_matrix(), PrimitiveOp(matrix_op.data).to_matrix(), )
def test_qobj_with_hamiltonian(self): """test qobj output with hamiltonian""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.rx(np.pi / 4, qr[0]) matrix = Operator.from_label('XIZ') theta = Parameter('theta') uni = HamiltonianGate(matrix, theta, label='XIZ') qc.append(uni, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) qc = qc.bind_parameters({theta: np.pi / 2}) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[1] self.assertEqual(instr.name, 'hamiltonian') # Also test label self.assertEqual(instr.label, 'XIZ') np.testing.assert_array_almost_equal( np.array(instr.params[0]).astype(np.complex64), matrix.data)
def test_3q_hamiltonian(self): """test 3 qubit hamiltonian on non-consecutive bits""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.x(qr[0]) matrix = Operator.from_label("XZY") theta = Parameter("theta") uni3q = HamiltonianGate(matrix, theta) qc.append(uni3q, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) # test of text drawer self.log.info(qc) qc = qc.bind_parameters({theta: -np.pi / 2}) dag = circuit_to_dag(qc) nodes = dag.multi_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, [qr[0], qr[1], qr[3]]) np.testing.assert_almost_equal(dnode.op.to_matrix(), 1j * matrix.data)
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, creg0, creg1) circ.x(qreg0[1]) circ.x(qreg1[0]) meas = QuantumCircuit(qreg0, qreg1, creg0, creg1) meas.measure(qreg0, creg0) meas.measure(qreg1, creg1) qc = circ.compose(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 = Operator(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_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_diamond_norm(self, num_qubits): """Test the diamond_norm for {num_qubits}-qubit pauli channel.""" try: import cvxpy except ImportError: # Skip test if CVXPY not installed self.skipTest("CVXPY not installed.") # Pauli channels have an analytic expression for the # diamond norm so we can easily test it op = Choi(np.zeros((4 ** num_qubits, 4 ** num_qubits))) labels = [num_qubits * i for i in ['I', 'X', 'Y', 'Z']] coeffs = [-1.0, 0.5, 2.5, -0.1] for coeff, label in zip(coeffs, labels): op = op + coeff * Choi(Operator.from_label(label)) target = np.sum(np.abs(coeffs)) try: value = diamond_norm(op) self.assertAlmostEqual(value, target, places=4) except cvxpy.SolverError: self.skipTest("CVXPY solver failed.")
def test_2q_hamiltonian(self): """test 2 qubit hamiltonian""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) matrix = Operator.from_label("XY") qc.x(qr[0]) theta = Parameter("theta") uni2q = HamiltonianGate(matrix, theta) qc.append(uni2q, [qr[0], qr[1]]) qc2 = qc.bind_parameters({theta: -np.pi / 2}) dag = circuit_to_dag(qc2) nodes = dag.two_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, [qr[0], qr[1]]) # Equality based on Pauli exponential identity np.testing.assert_array_almost_equal(dnode.op.to_matrix(), 1j * matrix.data) qc3 = dag_to_circuit(dag) self.assertEqual(qc2, qc3)
def test_rotation_gates(self): """Test controlled rotation gates""" import qiskit.extensions.standard.u1 as u1 import qiskit.extensions.standard.rx as rx import qiskit.extensions.standard.ry as ry import qiskit.extensions.standard.rz as rz num_ctrl = 2 num_target = 1 qreg = QuantumRegister(num_ctrl + num_target) theta = pi / 2 gu1 = u1.U1Gate(theta) grx = rx.RXGate(theta) gry = ry.RYGate(theta) grz = rz.RZGate(theta) ugu1 = ac._unroll_gate(gu1, ['u1', 'u3', 'cx']) ugrx = ac._unroll_gate(grx, ['u1', 'u3', 'cx']) ugry = ac._unroll_gate(gry, ['u1', 'u3', 'cx']) ugrz = ac._unroll_gate(grz, ['u1', 'u3', 'cx']) ugrz.params = grz.params cgu1 = ugu1.control(num_ctrl) cgrx = ugrx.control(num_ctrl) cgry = ugry.control(num_ctrl) cgrz = ugrz.control(num_ctrl) for gate, cgate in zip([gu1, grx, gry, grz], [cgu1, cgrx, cgry, cgrz]): with self.subTest(i=gate.name): if gate.name == 'rz': iden = Operator.from_label('I') zgen = Operator.from_label('Z') op_mat = (np.cos(0.5 * theta) * iden - 1j * np.sin(0.5 * theta) * zgen).data else: op_mat = Operator(gate).data ref_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, num_ctrl) self.assertTrue( matrix_equal(cop_mat, ref_mat, ignore_phase=True)) cqc = QuantumCircuit(num_ctrl + num_target) cqc.append(cgate, cqc.qregs[0]) dag = circuit_to_dag(cqc) unroller = Unroller(['u3', 'cx']) uqc = dag_to_circuit(unroller.run(dag)) self.log.info('%s gate count: %d', cgate.name, uqc.size()) self.log.info('\n%s', str(uqc)) # these limits could be changed if gate.name == 'ry': self.assertTrue(uqc.size() <= 32) elif gate.name == 'rz': self.assertTrue(uqc.size() <= 40) else: self.assertTrue(uqc.size() <= 20) qc = QuantumCircuit(qreg, name='composite') qc.append(grx.control(num_ctrl), qreg) qc.append(gry.control(num_ctrl), qreg) qc.append(gry, qreg[0:gry.num_qubits]) qc.append(grz.control(num_ctrl), qreg) dag = circuit_to_dag(qc) unroller = Unroller(['u3', 'cx']) uqc = dag_to_circuit(unroller.run(dag)) print(uqc.size()) self.log.info('%s gate count: %d', uqc.name, uqc.size()) self.assertTrue(uqc.size() <= 93) # this limit could be changed
def apply_gate(self, gate): self.state = self.state.evolve(Operator.from_label(gate)) self.operations.append(gate)
def new_state(self, n=5): for i in range(n): self.state = self.state.evolve(Operator.from_label(State.operators[random.randint(0, len(State.operators)-1)])) self.original = self.state
def test_nontp_process_fidelity(self): """Test process_fidelity for non-TP channel""" chan = 0.99 * Choi(Operator.from_label('X')) fid = process_fidelity(chan) self.assertLogs('qiskit.quantum_info.operators.measures', level='WARNING') self.assertAlmostEqual(fid, 0, places=15)