def test_kraus_to_ptm_qubit(self): p_damp = 0.5 damp_kraus_mat = np.array([[[1, 0], [0, np.sqrt(1 - p_damp)]], [[0, np.sqrt(p_damp)], [0, 0]]]) gm_qubit_basis = (bases.gell_mann(2), ) gm_two_qubit_basis = gm_qubit_basis * 2 damp_op = Operation.from_kraus(damp_kraus_mat, gm_qubit_basis) damp_ptm = damp_op.ptm(gm_qubit_basis) expected_mat = np.array([[1, 0, 0, 0], [0, np.sqrt(1 - p_damp), 0, 0], [0, 0, np.sqrt(1 - p_damp), 0], [p_damp, 0, 0, 1 - p_damp]]) assert np.allclose(damp_ptm, expected_mat) with pytest.raises(ValueError, match=r'.* must be list-like, .*'): damp_op.set_bases(bases.gell_mann(2), bases.gell_mann(2)) cz_kraus_mat = np.diag([1, 1, 1, -1]) cz = Operation.from_kraus(cz_kraus_mat, gm_two_qubit_basis) cz_ptm = cz.ptm(gm_two_qubit_basis) assert cz_ptm.shape == (4, 4, 4, 4) cz_ptm = cz_ptm.reshape((16, 16)) assert np.all(cz_ptm.round(3) <= 1) assert np.all(cz_ptm.round(3) >= -1) assert np.isclose(np.sum(cz_ptm[0, :]), 1) assert np.isclose(np.sum(cz_ptm[:, 0]), 1)
def test_lindblad_singlequbit(self): ham = random_hermitian_matrix(2, seed=56) lindblad_ops = np.array([ [[0, 0.1], [0, 0]], [[0, 0], [0, 0.33]], ]) t1 = 10 t2 = 25 b1 = (bases.general(2), ) b2 = (bases.gell_mann(2), ) op1 = Operation.from_lindblad_form(t1, b1, b2, hamiltonian=ham, lindblad_ops=lindblad_ops) op2 = Operation.from_lindblad_form(t2, b2, b1, hamiltonian=ham, lindblad_ops=lindblad_ops) op = Operation.from_lindblad_form(t1 + t2, b1, hamiltonian=ham, lindblad_ops=lindblad_ops) dm = random_hermitian_matrix(2, seed=3) state1 = PauliVector.from_dm(dm, b1) state2 = PauliVector.from_dm(dm, b1) op1(state1, 0) op2(state1, 0) op(state2, 0) assert np.allclose(state1.to_pv(), state2.to_pv())
def test_kraus_to_ptm_qubit(self): p_damp = 0.5 damp_kraus_mat = np.array( [[[1, 0], [0, np.sqrt(1 - p_damp)]], [[0, np.sqrt(p_damp)], [0, 0]]]) gm_qubit_basis = (bases.gell_mann(2),) gm_two_qubit_basis = gm_qubit_basis + gm_qubit_basis damp_op = Operation.from_kraus(damp_kraus_mat, 2) damp_ptm = damp_op.set_bases(bases_in=gm_qubit_basis, bases_out=gm_qubit_basis).ptm expected_mat = np.array([[1, 0, 0, 0], [0, np.sqrt(1-p_damp), 0, 0], [0, 0, np.sqrt(1-p_damp), 0], [p_damp, 0, 0, 1-p_damp]]) assert np.allclose(damp_ptm, expected_mat) with pytest.raises(ValueError, match=r'.* should be a list, .*'): damp_op.set_bases(bases.gell_mann(2), bases.gell_mann(2)) cz_kraus_mat = np.diag([1, 1, 1, -1]) cz = Operation.from_kraus(cz_kraus_mat, 2).set_bases(gm_two_qubit_basis, gm_two_qubit_basis) assert cz.ptm.shape == (4, 4, 4, 4) cz_ptm = cz.ptm.reshape((16, 16)) assert np.all(cz_ptm.round(3) <= 1) assert np.all(cz_ptm.round(3) >= -1) assert np.isclose(np.sum(cz_ptm[0, :]), 1) assert np.isclose(np.sum(cz_ptm[:, 0]), 1)
def test_lindblad_time_inverse(self): ham = random_hermitian_matrix(2, seed=4) b = (bases.general(2), ) op_plus = Operation.from_lindblad_form(20, b, hamiltonian=ham) op_minus = Operation.from_lindblad_form(20, b, hamiltonian=-ham) dm = random_hermitian_matrix(2, seed=5) state = PauliVector.from_dm(dm, b) op_plus(state, 0) op_minus(state, 0) assert np.allclose(state.to_dm(), dm)
def test_lindblad_two_qubit(self): b = (bases.general(2), ) id = np.array([[1, 0], [0, 1]]) ham1 = random_hermitian_matrix(2, seed=6) ham2 = random_hermitian_matrix(2, seed=7) ham = np.kron(ham1, id).reshape(2, 2, 2, 2) + \ np.kron(id, ham2).reshape(2, 2, 2, 2) dm = random_hermitian_matrix(4, seed=3) op1 = Operation.from_lindblad_form(25, b, hamiltonian=ham1) op2 = Operation.from_lindblad_form(25, b, hamiltonian=ham2) op = Operation.from_lindblad_form(25, b * 2, hamiltonian=ham) state1 = PauliVector.from_dm(dm, b * 2) state2 = PauliVector.from_dm(dm, b * 2) op1(state1, 0) op2(state1, 1) op(state2, 0, 1) assert np.allclose(state1.to_pv(), state2.to_pv()) ops1 = np.array([ [[0, 0.1], [0, 0]], [[0, 0], [0, 0.33]], ]) ops2 = np.array([ [[0, 0.15], [0, 0]], [[0, 0], [0, 0.17]], ]) ops = [np.kron(op, id).reshape(2, 2, 2, 2) for op in ops1] +\ [np.kron(id, op).reshape(2, 2, 2, 2) for op in ops2] op1 = Operation.from_lindblad_form(25, b, lindblad_ops=ops1) op2 = Operation.from_lindblad_form(25, b, lindblad_ops=ops2) op = Operation.from_lindblad_form(25, b * 2, lindblad_ops=ops) state1 = PauliVector.from_dm(dm, b * 2) state2 = PauliVector.from_dm(dm, b * 2) op1(state1, 0) op2(state1, 1) op(state2, 0, 1) assert np.allclose(state1.to_pv(), state2.to_pv()) op1 = Operation.from_lindblad_form(25, b, hamiltonian=ham1, lindblad_ops=ops1) op2 = Operation.from_lindblad_form(25, b, hamiltonian=ham2, lindblad_ops=ops2) op = Operation.from_lindblad_form(25, b * 2, hamiltonian=ham, lindblad_ops=ops) state1 = PauliVector.from_dm(dm, b * 2) state2 = PauliVector.from_dm(dm, b * 2) op1(state1, 0) op2(state1, 1) op(state2, 0, 1) assert np.allclose(state1.to_pv(), state2.to_pv())
def phase_damping(total_rate=None, *, x_deph_rate=None, y_deph_rate=None, z_deph_rate=None): if total_rate is not None: kraus = np.array([[[1, 0], [0, np.sqrt(1 - total_rate)]], [[0, 0], [0, np.sqrt(total_rate)]]]) return Operation.from_kraus(kraus, 2) else: if None in (x_deph_rate, y_deph_rate, z_deph_rate): raise ValueError( "Either the total_rate or the dephasing rates along each of " "the three axis must be provided") ptm = np.diag( [1, 1 - x_deph_rate, 1 - y_deph_rate, 1 - z_deph_rate]) return Operation.from_ptm(ptm, (bases.gell_mann(2),))
def test_kraus_to_ptm_errors(self): qutrit_basis = (bases.general(3), ) cz_kraus_mat = np.diag([1, 1, 1, -1]) kraus_op = Operation.from_kraus(cz_kraus_mat, 2) wrong_dim_kraus = np.random.random((4, 4, 2, 2)) with pytest.raises(ValueError): _ = Operation.from_kraus(wrong_dim_kraus, 2) not_sqr_kraus = np.random.random((4, 2, 3)) with pytest.raises(ValueError): _ = Operation.from_kraus(not_sqr_kraus, 2) with pytest.raises(ValueError): _ = Operation.from_kraus(cz_kraus_mat, 3) with pytest.raises(ValueError): _ = kraus_op.set_bases(qutrit_basis + qutrit_basis)
def amp_damping(total_rate=None, *, exc_rate=None, damp_rate=None): if total_rate is not None: kraus = np.array([[[1, 0], [0, np.sqrt(1 - total_rate)]], [[0, np.sqrt(total_rate)], [0, 0]]]) return Operation.from_kraus(kraus, 2) else: if None in (exc_rate, damp_rate): raise ValueError( "Either the total_rate or both the exc_rate and damp_rate " "must be provided") comb_rate = exc_rate + damp_rate ptm = np.array([[1, 0, 0, 0], [0, np.sqrt((1 - comb_rate)), 0, 0], [0, 0, np.sqrt((1 - comb_rate)), 0], [2 * damp_rate - comb_rate, 0, 0, 1 - comb_rate]]) return Operation.from_ptm(ptm, (bases.gell_mann(2), ))
def test_kraus_to_ptm_errors(self): qutrit_basis = (bases.general(3),) cz_kraus_mat = np.diag([1, 1, 1, -1]) kraus_op = Operation.from_kraus(cz_kraus_mat, 2) wrong_dim_kraus = np.random.random((4, 4, 2, 2)) with pytest.raises(ValueError): _ = Operation.from_kraus(wrong_dim_kraus, 2) not_sqr_kraus = np.random.random((4, 2, 3)) with pytest.raises(ValueError): _ = Operation.from_kraus(not_sqr_kraus, 2) with pytest.raises(ValueError): _ = Operation.from_kraus(cz_kraus_mat, 3) with pytest.raises(ValueError): _ = kraus_op.set_bases(qutrit_basis + qutrit_basis)
def phase_flipping(flip_rate): # This is actually equivalent to the phase damping matrix = np.array([ np.sqrt(flip_rate) * _PAULI["I"], np.sqrt(1 - flip_rate) * _PAULI["Z"] ]) return Operation.from_kraus(matrix, 2)
def phase_damping(total_rate=None, *, x_deph_rate=None, y_deph_rate=None, z_deph_rate=None): if total_rate is not None: kraus = np.array([[[1, 0], [0, np.sqrt(1 - total_rate)]], [[0, 0], [0, np.sqrt(total_rate)]]]) return Operation.from_kraus(kraus, 2) else: if None in (x_deph_rate, y_deph_rate, z_deph_rate): raise ValueError( "Either the total_rate or the dephasing rates along each of " "the three axis must be provided") ptm = np.diag([1, 1 - x_deph_rate, 1 - y_deph_rate, 1 - z_deph_rate]) return Operation.from_ptm(ptm, (bases.gell_mann(2), ))
def test_create_timed_model(): basis = (bases.general(2), ) class SampleModel(Model): dim = 2 @Model.gate(duration=20) def rotate_y(self, qubit): return ( self.wait(qubit, 10), ParametrizedOperation(lib.rotate_y, basis), self.wait(qubit, 10), ) @Model.gate(duration='t_twoqubit') def cphase(self, qubit_static, qubit_fluxed): return ( self.wait(qubit_static, 0.5 * self.p('t_twoqubit')), self.wait(qubit_fluxed, 0.5 * self.p('t_twoqubit')), lib.cphase(pi).at(qubit_static, qubit_fluxed), self.wait(qubit_static, 0.5 * self.p('t_twoqubit')), self.wait(qubit_fluxed, 0.5 * self.p('t_twoqubit')), ) @Model.gate(duration=lambda qubit, setup: 600 if qubit == 'D0' else 400) def strange_duration_gate(self, qubit): return lib.rotate_y(pi) @staticmethod def _filter_wait_placeholders(operation): return Operation.from_sequence([ unit for unit in operation.units() if not isinstance(unit.operation, WaitPlaceholder) ]) def finalize(self, circuit, bases_in=None): return circuit.finalize([self._filter_wait_placeholders], bases_in) sample_setup = Setup(""" setup: - t_twoqubit: 40 """) m = SampleModel(sample_setup) cnot = m.rotate_y('D0', angle=0.5*pi) + m.cphase('D0', 'D1') + \ m.rotate_y('D0', angle=-0.5*pi) cnot = m.finalize(cnot) assert cnot.operation.ptm(basis * 2, basis * 2) == approx( Operation.from_sequence( lib.rotate_y(0.5 * pi).at(0), lib.cphase(pi).at(0, 1), lib.rotate_y(-0.5 * pi).at(0), ).ptm(basis * 2, basis * 2)) gate1 = m.strange_duration_gate('D0') assert gate1.duration == 600 gate2 = m.strange_duration_gate('D1') assert gate2.duration == 400
def rotate_euler(phi, theta, lamda): """A perfect single qubit rotation described by three Euler angles. Unitary operation, that corresponds to this rotation, is: .. math:: U = R_Z(\\phi) \\cdot R_X(\\theta) \\cdot R_Z(\\lambda) Parameters ---------- phi, theta, lamda: float Euler rotation angles in radians. Returns ------- Operation An operation, that corresponds to the rotation. """ exp_phi, exp_lambda = np.exp(1j * phi), np.exp(1j * lamda) sin_theta, cos_theta = np.sin(theta / 2), np.cos(theta / 2) matrix = np.array([ [cos_theta, -1j * exp_lambda * sin_theta, 0], [-1j * exp_phi * sin_theta, exp_phi * exp_lambda * cos_theta, 0], [0, 0, 1]]) return Operation.from_kraus(matrix, 3)
def amp_damping(p0_up, p1_up, p1_down, p2_down): """ A gate, that excites or relaxes a qubit with a certain probability. Parameters ---------- p0_up : float Probability to excite to state 1, being in the state 0 p1_up : float Probability to excite to state 2, being in the state 1 p1_down : float Probability to relax to state 0, being in the state 1 p2_down : float Probability to relax to state 1, being in the state 2 Returns ------- quantumsim.operation._PTMOperation """ ptm = np.identity(9, dtype=float) ptm[:3, :3] = [[1. - p0_up, p1_down, 0.], [p0_up, 1. - p1_down - p1_up, p2_down], [0., p1_up, 1 - p2_down]] basis = (bases.general(3), ) return Operation.from_ptm(ptm, basis, basis)
def rotate_euler(phi, theta, lamda): """A perfect single qubit rotation described by three Euler angles. Unitary operation, that corresponds to this rotation, is: .. math:: U = R_Z(\\phi) \\cdot R_X(\\theta) \\cdot R_Z(\\lambda) Parameters ---------- phi, theta, lamda: float Euler rotation angles in radians. Returns ------- Operation An operation, that corresponds to the rotation. """ exp_phi, exp_lambda = np.exp(1j * phi), np.exp(1j * lamda) sin_theta, cos_theta = np.sin(theta / 2), np.cos(theta / 2) matrix = np.array([ [cos_theta, -1j * exp_lambda * sin_theta], [-1j * exp_phi * sin_theta, exp_phi * exp_lambda * cos_theta]]) return Operation.from_kraus(matrix, 2)
def test_chain_compile_leaking(self): b = bases.general(3) chain0 = Operation.from_sequence( lib3.rotate_x(0.5 * np.pi).at(2), lib3.cphase(leakage_rate=0.1).at(0, 2), lib3.cphase(leakage_rate=0.1).at(1, 2), lib3.rotate_x(-0.75 * np.pi).at(2), lib3.rotate_x(0.25 * np.pi).at(2), ) b0 = b.subbasis([0]) b01 = b.subbasis([0, 1]) b0134 = b.subbasis([0, 1, 3, 4]) chain1 = chain0.compile((b0, b0, b0134), (b, b, b)) assert isinstance(chain1, _Chain) # Ancilla is not leaking here anc_basis = chain1._units[1].operation.bases_out[1] for label in anc_basis.labels: assert '2' not in label chain2 = chain0.compile((b01, b01, b0134), (b, b, b)) # Ancilla is leaking here assert isinstance(chain2, _Chain) anc_basis = chain2._units[1].operation.bases_out[1] for label in '2', 'X20', 'Y20', 'X21', 'Y21': assert label in anc_basis.labels
def test_chain_merge_prev(self, d, lib): b = bases.general(d) rng = np.random.RandomState(4242) dm = rng.randn(d*d, d*d) + 1j * rng.randn(d*d, d*d) dm += dm.conjugate().transpose() dm /= dm.trace() chain = Operation.from_sequence( (lib.cphase(angle=np.pi/7, leakage=0.25) if d == 3 else lib.cphase(3*np.pi / 7)).at(0, 1), lib.rotate_x(4 * np.pi / 7).at(0), ) bases_full = (b, b) chain_c = chain.compile(bases_full, bases_full) assert len(chain.operations) == 2 assert isinstance(chain_c, _PTMOperation) state1 = State.from_dm(dm, bases_full) state2 = State.from_dm(dm, bases_full) chain(state1, 0, 1) chain_c(state2, 0, 1) assert np.allclose(state1.meas_prob(0), state2.meas_prob(0)) assert np.allclose(state1.meas_prob(1), state2.meas_prob(1))
def test_create_untimed_model(): basis = (bases.general(2), ) class SampleModel(Model): dim = 2 @Model.gate() def rotate_y(self, qubit): return (ParametrizedOperation(lib.rotate_y, basis), ) @Model.gate() def cphase(self, qubit_static, qubit_fluxed): return (lib.cphase(pi).at(qubit_static, qubit_fluxed), ) sample_setup = Setup(""" setup: [] """) m = SampleModel(sample_setup) cnot = m.rotate_y('D0', angle=0.5*pi) + m.cphase('D0', 'D1') + \ m.rotate_y('D0', angle=-0.5*pi) assert cnot.finalize().operation.ptm(basis * 2, basis * 2) == approx( Operation.from_sequence( lib.rotate_y(0.5 * pi).at(0), lib.cphase(pi).at(0, 1), lib.rotate_y(-0.5 * pi).at(0), ).ptm(basis * 2, basis * 2))
def idle(duration, t1, t2, anharmonicity=0.): if np.isfinite(t1) and np.isfinite(t2): t_phi = 1. / (1. / t2 - 0.5 / t1) if t_phi < 0: raise ValueError('t2 must be less than 2*t1') elif np.allclose(t_phi, 0): ops_t2 = [] else: ops_t2 = [(8. / (9 * t_phi))**0.5 * np.array([[1, 0, 0], [0, 0, 0], [0, 0, -1]]), (2. / (9 * t_phi))**0.5 * np.array([[1, 0, 0], [0, -1, 0], [0, 0, 0]]), (2. / (9 * t_phi))**0.5 * np.array([[0, 0, 0], [0, 1, 0], [0, 0, -1]])] else: ops_t2 = [] op_t1 = t1**-0.5 * np.array([[0, 1, 0], [0, 0, np.sqrt(2)], [0, 0, 0]]) if not np.allclose(anharmonicity, 0.): ham = np.array([ [0., 0., 0.], [0., 0., 0.], [0., 0., anharmonicity], ]) else: ham = None return Operation.from_lindblad_form(duration, (bases.general(3), ), hamiltonian=ham, lindblad_ops=[op_t1, *ops_t2])
def test_chain_merge_prev(self, d, lib): b = bases.general(d) rng = np.random.RandomState(4242) dm = rng.randn(d * d, d * d) + 1j * rng.randn(d * d, d * d) dm += dm.conjugate().transpose() dm /= dm.trace() chain = Operation.from_sequence( (lib.cphase(angle=np.pi / 7, leakage_rate=0.25) if d == 3 else lib.cphase(3 * np.pi / 7)).at(0, 1), lib.rotate_x(4 * np.pi / 7).at(0), ) bases_full = (b, b) chain_c = chain.compile(bases_full, bases_full) assert len(chain._units) == 2 assert isinstance(chain_c, PTMOperation) pv1 = PauliVector.from_dm(dm, bases_full) pv2 = PauliVector.from_dm(dm, bases_full) chain(pv1, 0, 1) chain_c(pv2, 0, 1) assert np.allclose(pv1.meas_prob(0), pv2.meas_prob(0)) assert np.allclose(pv1.meas_prob(1), pv2.meas_prob(1))
def depolarization(rate): rate = rate / 2 sqrt = np.sqrt(rate) matrix = np.array([ np.sqrt(2 - (3 * rate)) * _PAULI["I"], sqrt * _PAULI["X"], sqrt * _PAULI["Y"], sqrt * _PAULI["Z"] ]) return Operation.from_kraus(matrix, 2)
def depolarization(rate): rate = rate / 2 sqrt = np.sqrt(rate) matrix = np.array([np.sqrt(2 - (3 * rate)) * _PAULI["I"], sqrt * _PAULI["X"], sqrt * _PAULI["Y"], sqrt * _PAULI["Z"]]) return Operation.from_kraus(matrix, 2)
def amp_damping(total_rate=None, *, exc_rate=None, damp_rate=None): if total_rate is not None: kraus = np.array([[[1, 0], [0, np.sqrt(1 - total_rate)]], [[0, np.sqrt(total_rate)], [0, 0]]]) return Operation.from_kraus(kraus, 2) else: if None in (exc_rate, damp_rate): raise ValueError( "Either the total_rate or both the exc_rate and damp_rate " "must be provided") comb_rate = exc_rate + damp_rate ptm = np.array([ [1, 0, 0, 0], [0, np.sqrt((1 - comb_rate)), 0, 0], [0, 0, np.sqrt((1 - comb_rate)), 0], [2*damp_rate - comb_rate, 0, 0, 1 - comb_rate]]) return Operation.from_ptm(ptm, (bases.gell_mann(2),))
def cnot(): dcnot = np.zeros((9, 9)) dcnot[3, 3] = 0.5 dcnot[4, 4] = 0.5 dcnot[3, 4] = -0.5 dcnot[4, 3] = -0.5 unitary = expm(-1j*np.pi*dcnot) return Operation.from_kraus(unitary, 3)
def test_circuits_params(self): dim = 2 basis = (bases.general(dim), ) * 2 orotate = lib.rotate_y ocphase = lib.cphase grotate = Gate('Q0', dim, ParametrizedOperation(orotate, basis[:1])) gcphase = Gate(('Q0', 'Q1'), dim, ParametrizedOperation(ocphase, basis)) with pytest.raises(RuntimeError, match=r".*free parameters.*\n" r".*angle.*\n" r".*allow_param_repeat.*"): _ = gcphase + grotate with allow_param_repeat(): circuit = grotate + gcphase + grotate assert circuit.free_parameters == {sympy.symbols('angle')} assert len(circuit.gates) == 3 angle = 0.736 assert c_op(circuit(angle=angle)).ptm(basis, basis) == \ approx(Operation.from_sequence( orotate(angle).at(0), ocphase(angle).at(0, 1), orotate(angle).at(0) ).ptm(basis, basis)) angle1 = 0.4 * pi angle2 = 1.01 * pi angle3 = -0.6 * pi ptm_ref = Operation.from_sequence( orotate(angle1).at(0), ocphase(angle2).at(0, 1), orotate(angle3).at(0)).ptm(basis, basis) circuit = grotate(angle=angle1) + gcphase(angle=angle2) + \ grotate(angle=angle3) assert circuit.finalize().operation.ptm(basis, basis) == \ approx(ptm_ref) circuit = grotate(angle='angle1') + gcphase(angle='angle2') + \ grotate(angle='angle3') assert c_op(circuit(angle1=angle1, angle2=angle2, angle3=angle3)).ptm(basis, basis) == approx(ptm_ref)
def controlled_unitary(unitary): dim_hilbert = unitary.shape[0] if unitary.shape != (dim_hilbert, dim_hilbert): raise ValueError("Unitary matrix must be square") control_block = np.eye(2) off_diag_block_0 = np.zeros((2, dim_hilbert)) off_diag_block_1 = np.zeros((dim_hilbert, 2)) matrix = np.array([[control_block, off_diag_block_0], [off_diag_block_1, unitary]]) return Operation.from_kraus(matrix, 2)
def hadamard(): """A perfect Hadamard operation. Returns ------- Operation.from_kraus An operation, that corresponds to the rotation. """ matrix = np.sqrt(0.5) * np.array([[1, 1], [1, -1]]) return Operation.from_kraus(matrix, 2)
def hadamard(): """A perfect Hadamard operation. Returns ------- Operation.from_kraus An operation, that corresponds to the rotation. """ matrix = np.sqrt(0.5)*np.array([[1, 1], [1, -1]]) return Operation.from_kraus(matrix, 2)
def test_chain_compile_single_qubit(self, d, lib): b = bases.general(d) dm = random_hermitian_matrix(d, seed=487) bases_full = (b, ) subbases = (b.subbasis([0, 1]), ) angle = np.pi / 5 rx_angle = lib.rotate_x(angle) rx_2angle = lib.rotate_x(2 * angle) chain0 = Operation.from_sequence(rx_angle.at(0), rx_angle.at(0)) pv0 = PauliVector.from_dm(dm, bases_full) chain0(pv0, 0) assert chain0.num_qubits == 1 assert len(chain0._units) == 2 chain0_c = chain0.compile(bases_full, bases_full) assert isinstance(chain0_c, PTMOperation) pv1 = PauliVector.from_dm(dm, bases_full) chain0_c(pv1, 0) assert chain0_c.num_qubits == 1 assert isinstance(chain0_c, PTMOperation) op_angle = chain0_c op_2angle = rx_2angle.compile(bases_full, bases_full) assert isinstance(op_2angle, PTMOperation) assert op_angle.shape == op_2angle.shape assert op_angle.bases_in == op_2angle.bases_in assert op_angle.bases_out == op_2angle.bases_out assert op_angle.ptm(op_angle.bases_in, op_angle.bases_out) == \ approx(op_2angle.ptm(op_2angle.bases_in, op_2angle.bases_out)) assert pv1.to_pv() == approx(pv0.to_pv()) rx_pi = lib.rotate_x(np.pi) chain_2pi = Operation.from_sequence(rx_pi.at(0), rx_pi.at(0)) chain_2pi_c1 = chain_2pi.compile(subbases, bases_full) assert isinstance(chain_2pi_c1, PTMOperation) assert chain_2pi_c1.bases_in == subbases assert chain_2pi_c1.bases_out == subbases chain_2pi_c2 = chain_2pi.compile(bases_full, subbases) assert isinstance(chain_2pi_c2, PTMOperation) assert chain_2pi_c2.bases_in == subbases assert chain_2pi_c2.bases_out == subbases
def hadamard(): """A perfect Hadamard operation. Returns ------- Operation An operation, that corresponds to the rotation. """ s = np.sqrt(0.5) matrix = np.array([[s, s, 0], [s, -s, 0], [0, 0, 1]]) return Operation.from_kraus(matrix, 3)
def test_ptm(self): # Some random gate sequence op_indices = [(lib2.rotate_x(np.pi / 2), (0, )), (lib2.rotate_y(0.3333), (1, )), (lib2.cphase(), (0, 2)), (lib2.cphase(), (1, 2)), (lib2.rotate_x(-np.pi / 2), (0, ))] circuit = Operation.from_sequence(*(op.at(*ix) for op, ix in op_indices)) b = (bases.general(2), ) * 3 ptm = circuit.ptm(b, b) assert isinstance(ptm, np.ndarray) op_3q = Operation.from_ptm(ptm, b) dm = random_hermitian_matrix(8, seed=93) state1 = PauliVector.from_dm(dm, b) state2 = PauliVector.from_dm(dm, b) circuit(state1, 0, 1, 2) op_3q(state2, 0, 1, 2) assert np.allclose(state1.to_pv(), state2.to_pv())
def test_convert_ptm_basis(self): p_damp = 0.5 damp_kraus_mat = np.array([[[1, 0], [0, np.sqrt(1 - p_damp)]], [[0, np.sqrt(p_damp)], [0, 0]]]) gell_mann_basis = (bases.gell_mann(2), ) general_basis = (bases.general(2), ) op1 = Operation.from_kraus(damp_kraus_mat, gell_mann_basis) op2 = op1.set_bases(general_basis, general_basis) \ .set_bases(gell_mann_basis, gell_mann_basis) assert np.allclose(op1.ptm(gell_mann_basis), op2.ptm(gell_mann_basis)) assert op1.bases_in == op2.bases_in assert op1.bases_out == op2.bases_out
def test_circuits_add(self): dim = 2 orplus = lib.rotate_y(0.5 * pi) ocphase = lib.cphase(pi) orminus = lib.rotate_y(-0.5 * pi) grplus = Gate('Q0', dim, orplus) gcphase = Gate(('Q0', 'Q1'), dim, ocphase) grminus = Gate('Q0', dim, orminus) basis = (bases.general(2), ) * 2 circuit = grplus + gcphase assert circuit.qubits == ['Q0', 'Q1'] assert len(circuit.gates) == 2 assert c_op(circuit).ptm(basis, basis) == approx( Operation.from_sequence(orplus.at(0), ocphase.at(0, 1)).ptm(basis, basis)) circuit = circuit + grminus assert circuit.qubits == ['Q0', 'Q1'] assert len(circuit.gates) == 3 assert c_op(circuit).ptm(basis, basis) == approx( Operation.from_sequence(orplus.at(0), ocphase.at(0, 1), orminus.at(0)).ptm(basis, basis)) circuit = grplus + (gcphase + grminus) assert circuit.qubits == ['Q0', 'Q1'] assert len(circuit.gates) == 3 assert c_op(circuit).ptm(basis, basis) == approx( Operation.from_sequence(orplus.at(0), ocphase.at(0, 1), orminus.at(0)).ptm(basis, basis)) grplus = Gate('Q1', dim, orplus) grminus = Gate('Q1', dim, orminus) circuit = grplus + gcphase + grminus assert circuit.qubits == ['Q1', 'Q0'] assert len(circuit.gates) == 3 assert c_op(circuit).ptm(basis, basis) == approx( Operation.from_sequence(orplus.at(0), ocphase.at(0, 1), orminus.at(0)).ptm(basis, basis)) basis = (basis[0], ) * 3 grplus = Gate('Q2', dim, orplus) grminus = Gate('Q0', dim, orminus) circuit = grplus + gcphase + grminus assert circuit.qubits == ['Q2', 'Q0', 'Q1'] assert len(circuit.gates) == 3 assert c_op(circuit).ptm(basis, basis) == approx( Operation.from_sequence(orplus.at(0), ocphase.at(1, 2), orminus.at(1)).ptm(basis, basis)) grplus = Gate('Q0', dim, orplus) grminus = Gate('Q2', dim, orminus) circuit = grplus + gcphase + grminus assert circuit.qubits == ['Q0', 'Q1', 'Q2'] assert len(circuit.gates) == 3 assert c_op(circuit).ptm(basis, basis) == approx( Operation.from_sequence(orplus.at(0), ocphase.at(0, 1), orminus.at(2)).ptm(basis, basis))
def test_chain_compile_single_qubit(self, d, lib): b = bases.general(d) dm = random_density_matrix(d, seed=487) bases_full = (b,) subbases = (b.subbasis([0, 1]),) angle = np.pi/5 rx_angle = lib.rotate_x(angle) rx_2angle = lib.rotate_x(2*angle) chain0 = Operation.from_sequence(rx_angle.at(0), rx_angle.at(0)) state0 = State.from_dm(dm, bases_full) chain0(state0, 0) assert chain0.num_qubits == 1 assert len(chain0.operations) == 2 chain0_c = chain0.compile(bases_full, bases_full) state1 = State.from_dm(dm, bases_full) chain0_c(state1, 0) assert chain0_c.num_qubits == 1 assert isinstance(chain0_c, _PTMOperation) op_angle = chain0_c op_2angle = rx_2angle.compile(bases_full, bases_full) assert op_angle.shape == op_2angle.shape assert op_angle.bases_in == op_2angle.bases_in assert op_angle.bases_out == op_2angle.bases_out assert op_angle.ptm == approx(op_2angle.ptm) assert state1.to_pv() == approx(state0.to_pv()) rx_pi = lib.rotate_x(np.pi) chain_2pi = Operation.from_sequence(rx_pi.at(0), rx_pi.at(0)) chain_2pi_c1 = chain_2pi.compile(subbases, bases_full) assert isinstance(chain_2pi_c1, _PTMOperation) assert chain_2pi_c1.bases_in == subbases assert chain_2pi_c1.bases_out == subbases chain_2pi_c2 = chain_2pi.compile(bases_full, subbases) assert isinstance(chain_2pi_c2, _PTMOperation) assert chain_2pi_c2.bases_in == subbases assert chain_2pi_c2.bases_out == subbases
def test_kraus_to_ptm_qutrits(self): cz_kraus_mat = np.diag([1, 1, 1, 1, -1, 1, -1, 1, 1]) qutrit_basis = (bases.gell_mann(3), ) system_bases = qutrit_basis * 2 cz = Operation.from_kraus(cz_kraus_mat, system_bases) cz_ptm = cz.ptm(system_bases) assert cz_ptm.shape == (9, 9, 9, 9) cz_ptm_flat = cz_ptm.reshape((81, 81)) assert np.all(cz_ptm_flat.round(3) <= 1) and np.all( cz_ptm.round(3) >= -1) assert np.isclose(np.sum(cz_ptm_flat[0, :]), 1) assert np.isclose(np.sum(cz_ptm_flat[:, 0]), 1)
def test_kraus_to_ptm_qutrits(self): cz_kraus_mat = np.diag([1, 1, 1, 1, -1, 1, -1, 1, 1]) qutrit_basis = (bases.gell_mann(3),) system_bases = qutrit_basis * 2 cz = Operation.from_kraus(cz_kraus_mat, 3).set_bases(system_bases, system_bases) assert cz.ptm.shape == (9, 9, 9, 9) cz_ptm_flat = cz.ptm.reshape((81, 81)) assert np.all(cz_ptm_flat.round(3) <= 1) and np.all( cz.ptm.round(3) >= -1) assert np.isclose(np.sum(cz_ptm_flat[0, :]), 1) assert np.isclose(np.sum(cz_ptm_flat[:, 0]), 1)
def cphase(angle=np.pi): """A perfect controlled phase rotation. Parameters ---------- angle: float, optional Rotation angle in radians. Default is :math:`\\pi`. Returns ------- Operation.from_kraus An operation, that corresponds to the rotation. """ matrix = np.diag([1, 1, 1, np.exp(1j * angle)]) return Operation.from_kraus(matrix, 2)
def test_convert_ptm_basis(self): p_damp = 0.5 damp_kraus_mat = np.array( [[[1, 0], [0, np.sqrt(1-p_damp)]], [[0, np.sqrt(p_damp)], [0, 0]]]) gell_mann_basis = (bases.gell_mann(2),) general_basis = (bases.general(2),) damp_op_kraus = Operation.from_kraus(damp_kraus_mat, 2) op1 = damp_op_kraus.set_bases(gell_mann_basis, gell_mann_basis) op2 = damp_op_kraus.set_bases(general_basis, general_basis) \ .set_bases(gell_mann_basis, gell_mann_basis) assert np.allclose(op1.ptm, op2.ptm) assert op1.bases_in == op2.bases_in assert op1.bases_out == op2.bases_out
def rotate_y(angle=np.pi): """A perfect single qubit rotation around :math:`Oy` axis. Parameters ---------- angle: float, optional Rotation angle in radians. Default is :math:`\\pi`. Returns ------- Operation An operation, that corresponds to the rotation. """ sin, cos = np.sin(angle / 2), np.cos(angle / 2) matrix = np.array([[cos, -sin, 0], [sin, cos, 0], [0, 0, 1]]) return Operation.from_kraus(matrix, 3)
def rotate_y(angle=np.pi): """A perfect single qubit rotation around :math:`Oy` axis. Parameters ---------- angle: float, optional Rotation angle in radians. Default is :math:`\\pi`. Returns ------- Operation.from_kraus An operation, that corresponds to the rotation. """ sin, cos = np.sin(angle / 2), np.cos(angle / 2) matrix = np.array([[cos, -sin], [sin, cos]]) return Operation.from_kraus(matrix, 2)
def rotate_z(angle=np.pi): """A perfect single qubit rotation around :math:`Oz` axis. Parameters ---------- angle: float, optional Rotation angle in radians. Default is :math:`\\pi`. Returns ------- Operation.from_kraus An operation, that corresponds to the rotation. """ exp = np.exp(-1j * angle / 2) matrix = np.diag([exp, exp.conj()]) return Operation.from_kraus(matrix, 2)
def rotate_z(angle=np.pi): """A perfect single qubit rotation around :math:`Oz` axis. Parameters ---------- angle: float, optional Rotation angle in radians. Default is :math:`\\pi`. Returns ------- Operation An operation, that corresponds to the rotation. """ exp = np.exp(-1j * angle / 2) matrix = np.diag([exp, exp.conj(), 1]) return Operation.from_kraus(matrix, 3)
def iswap(angle=np.pi/2): """A perfect controlled phase rotation. Parameters ---------- angle: float, optional Rotation angle in radians. Default is :math:`\\pi`. Returns ------- Operation.from_kraus An operation, that corresponds to the rotation. """ sin, cos = np.sin(angle), np.cos(angle) matrix = np.array([[1, 0, 0, 0], [0, cos, 1j*sin, 0], [0, 1j*sin, cos, 0], [0, 0, 0, 1]]) return Operation.from_kraus(matrix, 2)
def test_zz_parity_compilation(self): b_full = bases.general(3) b0 = b_full.subbasis([0]) b01 = b_full.subbasis([0, 1]) b012 = b_full.subbasis([0, 1, 2]) bases_in = (b01, b01, b0) bases_out = (b_full, b_full, b012) zz = Operation.from_sequence( lib3.rotate_x(-np.pi/2).at(2), lib3.cphase(leakage=0.1).at(0, 2), lib3.cphase(leakage=0.25).at(2, 1), lib3.rotate_x(np.pi/2).at(2), lib3.rotate_x(np.pi).at(0), lib3.rotate_x(np.pi).at(1) ) zzc = zz.compile(bases_in=bases_in, bases_out=bases_out) assert len(zzc.operations) == 2 op1, ix1 = zzc.operations[0] op2, ix2 = zzc.operations[1] assert ix1 == (0, 2) assert ix2 == (1, 2) assert op1.bases_in[0] == bases_in[0] assert op2.bases_in[0] == bases_in[1] assert op1.bases_in[1] == bases_in[2] # Qubit 0 did not leak assert op1.bases_out[0] == bases_out[0].subbasis([0, 1, 3, 4]) # Qubit 1 leaked assert op2.bases_out[0] == bases_out[1].subbasis([0, 1, 2, 6]) # Qubit 2 is measured assert op2.bases_out[1] == bases_out[2] dm = random_density_matrix(3**3, seed=85) state1 = State.from_dm(dm, (b01, b01, b0)) state2 = State.from_dm(dm, (b01, b01, b0)) zz(state1, 0, 1, 2) zzc(state2, 0, 1, 2) # Compiled version still needs to be projected, so we can't compare # Pauli vectors, so we can to check only DM diagonals. assert np.allclose(state1.diagonal(), state2.diagonal())
def test_chain_compile_three_qubit(self, d, lib): b = bases.general(d) b0 = b.subbasis([0]) chain0 = Operation.from_sequence( lib.rotate_x(0.5*np.pi).at(2), lib.cphase().at(0, 2), lib.cphase().at(1, 2), lib.rotate_x(-0.75*np.pi).at(2), lib.rotate_x(0.25*np.pi).at(2), ) chain1 = chain0.compile((b, b, b0), (b, b, b)) assert chain1.operations[0].indices == (0, 2) assert chain1.operations[0].operation.bases_in == (b, b0) assert chain1.operations[0].operation.bases_out[0] == b assert chain1.operations[1].indices == (1, 2) assert chain1.operations[1].operation.bases_in[0] == b assert chain1.operations[1].operation.bases_out[0] == b for label in '0', '1', 'X10', 'Y10': assert label in chain1.operations[1].operation.bases_out[1].labels
def test_chain_apply(self): b = (bases.general(2),) * 3 dm = random_density_matrix(8, seed=93) state1 = State.from_dm(dm, b) state2 = State.from_dm(dm, b) # Some random gate sequence op_indices = [(lib2.rotate_x(np.pi/2), (0,)), (lib2.rotate_y(0.3333), (1,)), (lib2.cphase(), (0, 2)), (lib2.cphase(), (1, 2)), (lib2.rotate_x(-np.pi/2), (0,))] for op, indices in op_indices: op(state1, *indices), circuit = Operation.from_sequence( *(op.at(*ix) for op, ix in op_indices)) circuit(state2, 0, 1, 2) assert np.all(state1.to_pv() == state2.to_pv())
def cphase(angle=np.pi, leakage=0.): """A perfect controlled phase rotation. First qubit is low-frequency, second qubit is high-frequency (it leaks). Parameters ---------- angle: float, optional Rotation angle in radians. Default is :math:`\\pi`. leakage: float, optional Leakage rate of a CPhase gate Returns ------- Operation An operation, that corresponds to the rotation. """ dcphase = np.zeros((9, 9)) dcphase[2, 4] = 1 dcphase[4, 2] = 1 angle_frac = 1 - np.arcsin(np.sqrt(leakage)) / np.pi unitary = expm(-1j*angle*angle_frac*dcphase) return Operation.from_kraus(unitary, 3)
def test_chain_compile_leaking(self): b = bases.general(3) chain0 = Operation.from_sequence( lib3.rotate_x(0.5*np.pi).at(2), lib3.cphase(leakage=0.1).at(0, 2), lib3.cphase(leakage=0.1).at(1, 2), lib3.rotate_x(-0.75*np.pi).at(2), lib3.rotate_x(0.25*np.pi).at(2), ) b0 = b.subbasis([0]) b01 = b.subbasis([0, 1]) b0134 = b.subbasis([0, 1, 3, 4]) chain1 = chain0.compile((b0, b0, b0134), (b, b, b)) # Ancilla is not leaking here anc_basis = chain1.operations[1].operation.bases_out[1] for label in anc_basis.labels: assert '2' not in label chain2 = chain0.compile((b01, b01, b0134), (b, b, b)) # Ancilla is leaking here anc_basis = chain2.operations[1].operation.bases_out[1] for label in '2', 'X20', 'Y20', 'X21', 'Y21': assert label in anc_basis.labels
def test_chain_merge_next(self, d, lib): b = bases.general(d) dm = random_density_matrix(d**2, seed=574) chain = Operation.from_sequence( lib.rotate_x(np.pi / 5).at(0), (lib.cphase(angle=3*np.pi/7, leakage=0.1) if d == 3 else lib.cphase(3*np.pi / 7)).at(0, 1), ) bases_full = (b, b) chain_c = chain.compile(bases_full, bases_full) assert len(chain.operations) == 2 assert isinstance(chain_c, _PTMOperation) state1 = State.from_dm(dm, bases_full) state2 = State.from_dm(dm, bases_full) chain(state1, 0, 1) chain_c(state2, 0, 1) assert state1.meas_prob(0) == approx(state2.meas_prob(0)) assert state1.meas_prob(1) == approx(state2.meas_prob(1))
def idle(duration, t1, t2, anharmonicity=0.): t_phi = 1./(1./t2 - 0.5/t1) op_t1 = t1**-0.5 * np.array([ [0, 1, 0], [0, 0, np.sqrt(2)], [0, 0, 0] ]) ops_t2 = [ (8. / (9*t_phi))**0.5 * np.array([ [1, 0, 0], [0, 0, 0], [0, 0, -1] ]), (2. / (9*t_phi))**0.5 * np.array([ [1, 0, 0], [0, -1, 0], [0, 0, 0] ]), (2. / (9*t_phi))**0.5 * np.array([ [0, 0, 0], [0, 1, 0], [0, 0, -1] ]) ] if not np.allclose(anharmonicity, 0.): ham = np.array([ [0., 0., 0.], [0., 0., 0.], [0., 0., anharmonicity], ]) else: ham = None return Operation.from_lindblad_form( duration, bases.general(3), hamiltonian=ham, lindblad_ops=[op_t1, *ops_t2])
def amp_phase_damping(damp_rate, deph_rate): amp_damp = amp_damping(damp_rate) phase_damp = phase_damping(deph_rate) return Operation.from_sequence(amp_damp.at(0), phase_damp.at(0))
def phase_shift(angle=np.pi): matrix = np.diag([1, np.exp(1j * angle)]) return Operation.from_kraus(matrix, 2)
def cnot(): matrix = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) return Operation.from_kraus(matrix, 2)
def bit_phase_flipping(flip_rate): matrix = np.array([np.sqrt(flip_rate) * _PAULI["I"], np.sqrt(1 - flip_rate) * _PAULI["Y"]]) return Operation.from_kraus(matrix, 2)
def phase_flipping(flip_rate): # This is actually equivalent to the phase damping matrix = np.array([np.sqrt(flip_rate) * _PAULI["I"], np.sqrt(1 - flip_rate) * _PAULI["Z"]]) return Operation.from_kraus(matrix, 2)