def _qubit_integrate(tlist, psi0, epsilon, delta, g1, g2, solver): H = epsilon / 2.0 * sigmaz() + delta / 2.0 * sigmax() c_op_list = [] rate = g1 if rate > 0.0: c_op_list.append(np.sqrt(rate) * sigmam()) rate = g2 if rate > 0.0: c_op_list.append(np.sqrt(rate) * sigmaz()) e_ops = [sigmax(), sigmay(), sigmaz()] if solver == "me": output = mesolve(H, psi0, tlist, c_op_list, e_ops) elif solver == "es": output = essolve(H, psi0, tlist, c_op_list, e_ops) elif solver == "mc": output = mcsolve(H, psi0, tlist, c_op_list, e_ops, ntraj=750) else: raise ValueError("unknown solver") return output.expect[0], output.expect[1], output.expect[2]
def test_diagHamiltonian2(): """ Diagonalization of composite systems """ H1 = scipy.rand() * sigmax() + scipy.rand() * sigmay() +\ scipy.rand() * sigmaz() H2 = scipy.rand() * sigmax() + scipy.rand() * sigmay() +\ scipy.rand() * sigmaz() H = tensor(H1, H2) evals, ekets = H.eigenstates() for n in range(len(evals)): # assert that max(H * ket - e * ket) is small assert_equal(amax( abs((H * ekets[n] - evals[n] * ekets[n]).full())) < 1e-10, True) N1 = 10 N2 = 2 a1 = tensor(destroy(N1), qeye(N2)) a2 = tensor(qeye(N1), destroy(N2)) H = scipy.rand() * a1.dag() * a1 + scipy.rand() * a2.dag() * a2 + \ scipy.rand() * (a1 + a1.dag()) * (a2 + a2.dag()) evals, ekets = H.eigenstates() for n in range(len(evals)): # assert that max(H * ket - e * ket) is small assert_equal(amax( abs((H * ekets[n] - evals[n] * ekets[n]).full())) < 1e-10, True)
def __init__(self, N_field_levels, coupling=None, N_qubits=1): # basic parameters self.N_field_levels = N_field_levels self.N_qubits = N_qubits if coupling is None: self.g = 0 else: self.g = coupling # bare operators self.idcavity = qt.qeye(self.N_field_levels) self.idqubit = qt.qeye(2) self.a_bare = qt.destroy(self.N_field_levels) self.sm_bare = qt.sigmam() self.sz_bare = qt.sigmaz() self.sx_bare = qt.sigmax() self.sy_bare = qt.sigmay() # 1 atom 1 cavity operators self.jc_a = qt.tensor(self.a_bare, self.idqubit) self.jc_sm = qt.tensor(self.idcavity, self.sm_bare) self.jc_sx = qt.tensor(self.idcavity, self.sx_bare) self.jc_sy = qt.tensor(self.idcavity, self.sy_bare) self.jc_sz = qt.tensor(self.idcavity, self.sz_bare)
def set_H(self, args): """ setup the parametrized Hamiltonian """ self.args = args alpha = args[0] beta = args[1] self.H = alpha * beta * sigmaz() + sigmay() * alpha * np.sqrt( 1. - np.square(beta))
def get_exact_operator(mol): blist = [] for i, ph1 in enumerate(mol.dmrg_phs): basis = [qutip.identity(2)] for j, ph2 in enumerate(mol.dmrg_phs): if j == i: state = qutip.destroy(ph1.n_phys_dim) else: state = qutip.identity(ph2.n_phys_dim) basis.append(state) blist.append(qutip.tensor(basis)) ph_iden = [qutip.identity(ph.n_phys_dim) for ph in mol.dmrg_phs] sigmax = qutip.tensor([qutip.sigmax()] + ph_iden) sigmaz = qutip.tensor([qutip.sigmaz()] + ph_iden) delta = mol.tunnel epsilon = mol.elocalex terms = [-delta * sigmax, epsilon * sigmaz] for i, ph in enumerate(mol.dmrg_phs): g = ph.coupling_constant terms.append(ph.omega[0] * blist[i].dag() * blist[i]) terms.append(ph.omega[0] * g * sigmaz * (blist[i].dag() + blist[i])) H = sum(terms) return H, sigmax, sigmaz
def test_crab(self): """ Optimise pulse for Hadamard gate using CRAB algorithm Apply guess and ramping pulse assert that goal is achieved and fidelity error is below threshold assert that starting amplitude is zero """ # Hadamard H_d = sigmaz() H_c = [sigmax()] U_0 = identity(2) U_targ = hadamard_transform(1) n_ts = 12 evo_time = 10 # Run the optimisation result = cpo.opt_pulse_crab_unitary(H_d, H_c, U_0, U_targ, n_ts, evo_time, fid_err_targ=1e-5, alg_params={'crab_pulse_params':{'randomize_coeffs':False, 'randomize_freqs':False}}, init_coeff_scaling=0.5, guess_pulse_type='GAUSSIAN', guess_pulse_params={'variance':0.1*evo_time}, guess_pulse_scaling=1.0, guess_pulse_offset=1.0, amp_lbound=None, amp_ubound=None, ramping_pulse_type='GAUSSIAN_EDGE', ramping_pulse_params={'decay_time':evo_time/100.0}, gen_stats=True) assert_(result.goal_achieved, msg="Hadamard goal not achieved") assert_almost_equal(result.fid_err, 0.0, decimal=3, err_msg="Hadamard infidelity too high") assert_almost_equal(result.final_amps[0, 0], 0.0, decimal=3, err_msg="lead in amplitude not zero")
def prep_rot_qutip(n, a): q = qutip.basis(2) nNorm = np.linalg.norm(n) R = (-1j * a / (2 * nNorm) * (n[0] * qutip.sigmax() + n[1] * qutip.sigmay() + n[2] * qutip.sigmaz())).expm() return R * q
def testFloquetUnitary(self): """ Floquet: test unitary evolution of time-dependent two-level system """ delta = 1.0 * 2 * np.pi eps0 = 1.0 * 2 * np.pi A = 0.5 * 2 * np.pi omega = np.sqrt(delta ** 2 + eps0 ** 2) T = (2 * np.pi) / omega tlist = np.linspace(0.0, 2 * T, 101) psi0 = rand_ket(2) H0 = - eps0 / 2.0 * sigmaz() - delta / 2.0 * sigmax() H1 = A / 2.0 * sigmax() args = {'w': omega} H = [H0, [H1, lambda t, args: np.sin(args['w'] * t)]] e_ops = [num(2)] # solve schrodinger equation with floquet solver sol = fsesolve(H, psi0, tlist, e_ops, T, args) # compare with results from standard schrodinger equation sol_ref = mesolve(H, psi0, tlist, [], e_ops, args) assert_(max(abs(sol.expect[0] - sol_ref.expect[0])) < 1e-4)
def test_qubit_power(): "Steady state: Thermal qubit - power solver" # thermal steadystate of a qubit: compare numerics with analytical formula sz = sigmaz() sm = destroy(2) H = 0.5 * 2 * np.pi * sz gamma1 = 0.05 wth_vec = np.linspace(0.1, 3, 20) p_ss = np.zeros(np.shape(wth_vec)) for idx, wth in enumerate(wth_vec): n_th = 1.0 / (np.exp(1.0 / wth) - 1) # bath temperature c_op_list = [] rate = gamma1 * (1 + n_th) c_op_list.append(np.sqrt(rate) * sm) rate = gamma1 * n_th c_op_list.append(np.sqrt(rate) * sm.dag()) rho_ss = steadystate(H, c_op_list, method='power', mtol=1e-5) p_ss[idx] = expect(sm.dag() * sm, rho_ss) p_ss_analytic = np.exp(-1.0 / wth_vec) / (1 + np.exp(-1.0 / wth_vec)) delta = sum(abs(p_ss_analytic - p_ss)) assert_equal(delta < 1e-5, True)
def test_qubit(method, kwargs): # thermal steadystate of a qubit: compare numerics with analytical formula sz = qutip.sigmaz() sm = qutip.destroy(2) H = 0.5 * 2 * np.pi * sz gamma1 = 0.05 wth_vec = np.linspace(0.1, 3, 20) p_ss = np.zeros(np.shape(wth_vec)) with warnings.catch_warnings(): if 'use_wbm' in kwargs: # The deprecation has been fixed in dev.major warnings.simplefilter("ignore", category=DeprecationWarning) for idx, wth in enumerate(wth_vec): n_th = 1.0 / (np.exp(1.0 / wth) - 1) # bath temperature c_op_list = [] rate = gamma1 * (1 + n_th) c_op_list.append(np.sqrt(rate) * sm) rate = gamma1 * n_th c_op_list.append(np.sqrt(rate) * sm.dag()) rho_ss = qutip.steadystate(H, c_op_list, method=method, **kwargs) if 'return_info' in kwargs: rho_ss, info = rho_ss assert isinstance(info, dict) p_ss[idx] = qutip.expect(sm.dag() * sm, rho_ss) p_ss_analytic = np.exp(-1.0 / wth_vec) / (1 + np.exp(-1.0 / wth_vec)) np.testing.assert_allclose(p_ss_analytic, p_ss, atol=1e-5)
def test_multi_qubits(self): """ Test for multi-qubits system. """ N = 3 H_d = tensor([sigmaz()] * 3) H_c = [] # test empty ctrls num_tslots = 30 evo_time = 10 test = OptPulseProcessor(N) test.add_drift(H_d, [0, 1, 2]) test.add_control(tensor([sigmax(), sigmax()]), cyclic_permutation=True) # test periodically adding ctrls sx = sigmax() iden = identity(2) assert (len(test.get_control_labels()) == 3) test.add_control(sigmax(), cyclic_permutation=True) test.add_control(sigmay(), cyclic_permutation=True) # test pulse genration for cnot gate, with kwargs qc = [tensor([identity(2), cnot()])] test.load_circuit(qc, num_tslots=num_tslots, evo_time=evo_time, min_fid_err=1.0e-6) rho0 = qubit_states(3, [1, 1, 1]) rho1 = qubit_states(3, [1, 1, 0]) result = test.run_state(rho0, options=SolverOptions(store_states=True)) assert_(fidelity(result.states[-1], rho1) > 1 - 1.0e-6)
def test_simple_hadamard(self): """ Test for optimizing a simple hadamard gate """ N = 1 H_d = sigmaz() H_c = sigmax() qc = QubitCircuit(N) qc.add_gate("SNOT", 0) # test load_circuit, with verbose info num_tslots = 10 evo_time = 10 test = OptPulseProcessor(N, drift=H_d) test.add_control(H_c, targets=0) tlist, coeffs = test.load_circuit(qc, num_tslots=num_tslots, evo_time=evo_time, verbose=True) # test run_state rho0 = qubit_states(1, [0]) plus = (qubit_states(1, [0]) + qubit_states(1, [1])).unit() result = test.run_state(rho0) assert_allclose(fidelity(result.states[-1], plus), 1, rtol=1.0e-6)
def test_multi_gates(self): N = 2 H_d = tensor([sigmaz()]*2) H_c = [] test = OptPulseProcessor(N) test.add_drift(H_d, [0, 1]) test.add_control(sigmax(), cyclic_permutation=True) test.add_control(sigmay(), cyclic_permutation=True) test.add_control(tensor([sigmay(), sigmay()])) # qubits circuit with 3 gates setting_args = {"SNOT": {"num_tslots": 10, "evo_time": 1}, "SWAP": {"num_tslots": 30, "evo_time": 3}, "CNOT": {"num_tslots": 30, "evo_time": 3}} qc = QubitCircuit(N) qc.add_gate("SNOT", 0) qc.add_gate("SWAP", targets=[0, 1]) qc.add_gate('CNOT', controls=1, targets=[0]) test.load_circuit(qc, setting_args=setting_args, merge_gates=False) rho0 = rand_ket(4) # use random generated ket state rho0.dims = [[2, 2], [1, 1]] U = gate_sequence_product(qc.propagators()) rho1 = U * rho0 result = test.run_state(rho0) assert_(fidelity(result.states[-1], rho1) > 1-1.0e-6)
def count_waves(n_ts, evo_time, ptype, freq=None, num_waves=None): # Any dyn config will do #Hadamard H_d = sigmaz() H_c = [sigmax()] U_0 = identity(2) U_targ = hadamard_transform(1) pulse_params = {} if freq is not None: pulse_params['freq'] = freq if num_waves is not None: pulse_params['num_waves'] = num_waves optim = cpo.create_pulse_optimizer(H_d, H_c, U_0, U_targ, n_ts, evo_time, dyn_type='UNIT', init_pulse_type=ptype, init_pulse_params=pulse_params, gen_stats=False) pgen = optim.pulse_generator pulse = pgen.gen_pulse() # count number of waves zero_cross = pulse[0:-2]*pulse[1:-1] < 0 return (sum(zero_cross) + 1) / 2
def pauli(): '''Define pauli spin matrices''' identity = qutip.qeye(2) sx = qutip.sigmax()/2 sy = qutip.sigmay()/2 sz = qutip.sigmaz()/2 return identity, sx, sy, sz
def test_01_1_unitary_hadamard(self): """ control.pulseoptim: Hadamard gate with linear initial pulses assert that goal is achieved and fidelity error is below threshold """ # Hadamard H_d = sigmaz() H_c = [sigmax()] U_0 = identity(2) U_targ = hadamard_transform(1) n_ts = 10 evo_time = 10 # Run the optimisation result = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ, n_ts, evo_time, fid_err_targ=1e-10, init_pulse_type='LIN', gen_stats=True) assert_(result.goal_achieved, msg="Hadamard goal not achieved. " "Terminated due to: {}, with infidelity: {}".format( result.termination_reason, result.fid_err)) assert_almost_equal(result.fid_err, 0.0, decimal=10, err_msg="Hadamard infidelity too high")
def test_02_2_qft_bounds(self): """ control.pulseoptim: QFT gate with linear initial pulses (bounds) assert that amplitudes remain in bounds """ Sx = sigmax() Sy = sigmay() Sz = sigmaz() Si = 0.5*identity(2) H_d = 0.5*(tensor(Sx, Sx) + tensor(Sy, Sy) + tensor(Sz, Sz)) H_c = [tensor(Sx, Si), tensor(Sy, Si), tensor(Si, Sx), tensor(Si, Sy)] U_0 = identity(4) # Target for the gate evolution - Quantum Fourier Transform gate U_targ = qft.qft(2) n_ts = 10 evo_time = 10 result = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ, n_ts, evo_time, fid_err_targ=1e-9, amp_lbound=-1.0, amp_ubound=1.0, init_pulse_type='LIN', gen_stats=True) assert_((result.final_amps >= -1.0).all() and (result.final_amps <= 1.0).all(), msg="Amplitude bounds exceeded for QFT")
def test_jmat_12(): spinhalf = qutip.jmat(1 / 2.) paulix = np.array([[0. + 0.j, 1. + 0.j], [1. + 0.j, 0. + 0.j]]) pauliy = np.array([[0. + 0.j, 0. - 1.j], [0. + 1.j, 0. + 0.j]]) pauliz = np.array([[1. + 0.j, 0. + 0.j], [0. + 0.j, -1. + 0.j]]) sigmap = np.array([[0. + 0.j, 1. + 0.j], [0. + 0.j, 0. + 0.j]]) sigmam = np.array([[0. + 0.j, 0. + 0.j], [1. + 0.j, 0. + 0.j]]) np.testing.assert_allclose(spinhalf[0].full() * 2, paulix) np.testing.assert_allclose(spinhalf[1].full() * 2, pauliy) np.testing.assert_allclose(spinhalf[2].full() * 2, pauliz) np.testing.assert_allclose(qutip.jmat(1 / 2., '+').full(), sigmap) np.testing.assert_allclose(qutip.jmat(1 / 2., '-').full(), sigmam) np.testing.assert_allclose(qutip.spin_Jx(1 / 2.).full() * 2, paulix) np.testing.assert_allclose(qutip.spin_Jy(1 / 2.).full() * 2, pauliy) np.testing.assert_allclose(qutip.spin_Jz(1 / 2.).full() * 2, pauliz) np.testing.assert_allclose(qutip.spin_Jp(1 / 2.).full(), sigmap) np.testing.assert_allclose(qutip.spin_Jm(1 / 2.).full(), sigmam) np.testing.assert_allclose(qutip.sigmax().full(), paulix) np.testing.assert_allclose(qutip.sigmay().full(), pauliy) np.testing.assert_allclose(qutip.sigmaz().full(), pauliz) np.testing.assert_allclose(qutip.sigmap().full(), sigmap) np.testing.assert_allclose(qutip.sigmam().full(), sigmam) spin_set = qutip.spin_J_set(0.5) for i in range(3): assert spinhalf[i] == spin_set[i]
def test_summarize_component_direct(): krotov.objectives.Objective.reset_symbol_counters() H = ['H0', ['H1', 2j]] res = krotov.objectives._summarize_component(H, 'op') expected = '[H0, [H1, 2j]]' assert res == expected with pytest.raises(ValueError): krotov.objectives._summarize_component(H, 'invalid') ket0 = qutip.ket('0') ket1 = qutip.ket('1') ket2 = copy.deepcopy(ket0) assert krotov.objectives._summarize_component(ket0, 'state') == '|Ψ₀(2)⟩' assert krotov.objectives._summarize_component(ket1, 'state') == '|Ψ₁(2)⟩' assert krotov.objectives._summarize_component(ket2, 'state') == '|Ψ₂(2)⟩' krotov.objectives.Objective.reset_symbol_counters() assert krotov.objectives._summarize_component(ket2, 'state') == '|Ψ₀(2)⟩' H = qutip.sigmaz() assert krotov.objectives._summarize_component(H, 'op') == 'H₀[2,2]' assert krotov.objectives._summarize_component(H, 'lindblad') == 'L₀[2,2]' krotov.objectives.Objective.reset_symbol_counters()
def test_01_4_unitary_hadamard_qobj(self): """ control.pulseoptim: Hadamard gate with linear initial pulses (Qobj) assert that goal is achieved """ # Hadamard H_d = sigmaz() H_c = [sigmax()] U_0 = identity(2) U_targ = hadamard_transform(1) n_ts = 10 evo_time = 10 # Run the optimisation #Try with Qobj propagation result = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ, n_ts, evo_time, fid_err_targ=1e-10, init_pulse_type='LIN', dyn_params={'oper_dtype':Qobj}, gen_stats=True) assert_(result.goal_achieved, msg="Hadamard goal not achieved " "(Qobj propagation). " "Terminated due to: {}, with infidelity: {}".format( result.termination_reason, result.fid_err))
def test_06_3_compare_state_and_unitary_list_func(self): "sesolve: compare state and unitary operator evo - list func td" eps = 0.2 * 2 * np.pi delta = 1.0 * 2 * np.pi # atom frequency w0 = 0.5 * eps w1 = 0.5 * delta H0 = w0 * sigmaz() H1 = w1 * sigmax() a = 0.1 w_a = w0 td_args = {'a': a, 'w_a': w_a} h0_func = lambda t, args: a * t h1_func = lambda t, args: np.cos(w_a * t) H = [[H0, h0_func], [H1, h1_func]] psi0 = basis(2, 0) # initial state tlist = np.linspace(0, 20, 200) self.compare_evolution(H, psi0, tlist, normalize=False, td_args=td_args, tol=5e-5) self.compare_evolution(H, psi0, tlist, normalize=True, td_args=td_args, tol=5e-5)
def to_matrix(self, fd): n = num(fd) a = destroy(fd) ic = qeye(fd) sz = sigmaz() sm = sigmam() iq = qeye(2) ms = { "id": tensor(iq, ic), "a*ad" : tensor(iq, n), "a+hc" : tensor(iq, a), "sz" : tensor(sz, ic), "sm+hc" : tensor(sm, ic) } H0 = 0 H1s = [] for (p1, p2), v in self.coefs.items(): h = ms[p1] * ms[p2] try: term = float(v) * h if not term.isherm: term += term.dag() H0 += term except ValueError: H1s.append([h, v]) if not h.isherm: replacement = lambda m: '(-' + m.group() + ')' conj_v = re.sub('[1-9]+j', replacement, v) H1s.append([h.dag(), conj_v]) if H1s: return [H0] + H1s else: return H0
def pauli(): '''Return the Pauli spin matrices for S=1/2''' identity = qutip.qeye(2) sx = qutip.sigmax()/2 sy = qutip.sigmay()/2 sz = qutip.sigmaz()/2 return identity, sx, sy, sz
def __init__(self, n): paulis = [qt.identity(2), qt.sigmax(), qt.sigmay(), qt.sigmaz()] names = ["".join(s) for s in product(["I", "X", "Y", "Z"], repeat=n)] P = [qt.tensor(*s) for s in product(paulis, repeat=n)] d = dict(zip(names, P)) sizes = dict([(name, name.count("I")) for name in names]) snames = sorted(zip(names, list(range(len(names)))), key=lambda x: x[0].count("I"), reverse=True) P2 = [P[sn[1]] for sn in snames] names2 = [sn[0] for sn in snames] starts = [0] now = names2[0].count("I") for i in range(len(names2)): if names2[i].count("I") != now: starts.append(i) now = names2[i].count("I") self.dim = len(names2) self.names = names2 self.ops = P2 self.basis = d self.starts = dict(zip(list(range(len(starts))), starts)) self.adjacency = qt.Qobj( np.array([[ 1 if diff_by_one(self.names[i], self.names[j]) else 0 for j in range(self.dim) ] for i in range(self.dim)])) self.degree = qt.Qobj( np.diag( np.array([sum(self.adjacency[i][0]) for i in range(self.dim)]))) self.laplacian = self.degree - self.adjacency self.ilaplacian = qt.Qobj(np.linalg.inv(self.laplacian.full())) self.L, self.V = self.laplacian.eigenstates() self.iL, self.iV = self.ilaplacian.eigenstates()
def mixed_stars(self): copy = self.current_state.copy() copy.dims = [[2]*self.n_players, [1]*self.n_players] mixed = [copy.ptrace(i) for i in range(self.n_players)] return [[qt.expect(qt.identity(2), mix)*qt.expect(qt.sigmax(), mix),\ qt.expect(qt.identity(2), mix)*qt.expect(qt.sigmay(), mix),\ qt.expect(qt.identity(2), mix)*qt.expect(qt.sigmaz(), mix)] for mix in mixed]
def symmetrical_collapse(self, direction, i): sym = self.symmetrical() op = None if direction == "x": op = 0.5 * qt.sigmax() elif direction == "y": op = 0.5 * qt.sigmay() elif direction == "z": op = 0.5 * qt.sigmaz() elif direction == "h": return None elif direction == "r": op = qt.rand_herm(2) total_op = op if i == 0 else qt.identity(2) for j in range(1, self.n() - 1): if j == i: total_op = qt.tensor(total_op, op) else: total_op = qt.tensor(total_op, qt.identity(2)) total_op.dims = [[(2**(self.n() - 1))], [2**(self.n() - 1)]] L, V = total_op.eigenstates() amplitudes = [sym.overlap(v) for v in V] probabilities = np.array([(a * np.conjugate(a)).real for a in amplitudes]) probabilities = probabilities / probabilities.sum() pick = np.random.choice(list(range(len(V))), 1, p=probabilities)[0] vec = V[pick].full().T[0] projector = qt.Qobj(np.outer(vec, np.conjugate(vec))) sym = (projector * sym).unit() self.state = unsymmeterize(sym) self.refresh() return L[pick], L, probabilities
def sym_arrows(self): symmeterized = self.symmetrical().copy() symmeterized.dims = [[2] * (self.n() - 1), [1] * (self.n() - 1)] sym_bits = [symmeterized.ptrace(i) for i in range(self.n() - 1)] return [xyz_radial([qt.expect(qt.sigmax(), bit),\ -1*qt.expect(qt.sigmay(), bit),\ -1*qt.expect(qt.sigmaz(), bit)]) for bit in sym_bits]
def test_create(self): Q = sigmaz() bath = BosonicBath(Q, [1.], [0.5], [2.], [0.6]) exp_r, exp_i = bath.exponents check_exponent(exp_r, "R", dim=None, Q=Q, ck=1.0, vk=0.5) check_exponent(exp_i, "I", dim=None, Q=Q, ck=2.0, vk=0.6) bath = BosonicBath(Q, [1.], [0.5], [2.], [0.5]) [exp_ri] = bath.exponents check_exponent(exp_ri, "RI", dim=None, Q=Q, ck=1.0, vk=0.5, ck2=2.0) bath = BosonicBath(Q, [1.], [0.5], [2.], [0.6], tag="bath1") exp_r, exp_i = bath.exponents check_exponent(exp_r, "R", dim=None, Q=Q, ck=1.0, vk=0.5, tag="bath1") check_exponent(exp_i, "I", dim=None, Q=Q, ck=2.0, vk=0.6, tag="bath1") with pytest.raises(ValueError) as err: BosonicBath("not-a-qobj", [1.], [0.5], [2.], [0.6]) assert str(err.value) == "The coupling operator Q must be a Qobj." with pytest.raises(ValueError) as err: BosonicBath(Q, [1.], [], [2.], [0.6]) assert str(err.value) == ( "The bath exponent lists ck_real and vk_real, and ck_imag and" " vk_imag must be the same length.") with pytest.raises(ValueError) as err: BosonicBath(Q, [1.], [0.5], [2.], []) assert str(err.value) == ( "The bath exponent lists ck_real and vk_real, and ck_imag and" " vk_imag must be the same length.")
def test_11_time_dependent_drift(self): """ control.pulseoptim: Hadamard gate with fixed and time varying drift assert that goal is achieved for both and that different control pulses are produced (only) when they should be """ # Hadamard H_0 = sigmaz() H_c = [sigmax()] U_0 = identity(2) U_targ = hadamard_transform(1) n_ts = 20 evo_time = 10 drift_amps_flat = np.ones([n_ts], dtype=float) dript_amps_step = [np.round(float(k)/n_ts) for k in range(n_ts)] # Run the optimisations result_fixed = cpo.optimize_pulse_unitary(H_0, H_c, U_0, U_targ, n_ts, evo_time, fid_err_targ=1e-10, init_pulse_type='LIN', gen_stats=True) assert_(result_fixed.goal_achieved, msg="Fixed drift goal not achieved. " "Terminated due to: {}, with infidelity: {}".format( result_fixed.termination_reason, result_fixed.fid_err)) H_d = [drift_amps_flat[k]*H_0 for k in range(n_ts)] result_flat = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ, n_ts, evo_time, fid_err_targ=1e-10, init_pulse_type='LIN', gen_stats=True) assert_(result_flat.goal_achieved, msg="Flat drift goal not achieved. " "Terminated due to: {}, with infidelity: {}".format( result_flat.termination_reason, result_flat.fid_err)) # Check fixed and flat produced the same pulse assert_almost_equal(result_fixed.final_amps, result_flat.final_amps, decimal=9, err_msg="Flat and fixed drift result in " "different control pules") H_d = [dript_amps_step[k]*H_0 for k in range(n_ts)] result_step = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ, n_ts, evo_time, fid_err_targ=1e-10, init_pulse_type='LIN', gen_stats=True) assert_(result_step.goal_achieved, msg="Step drift goal not achieved. " "Terminated due to: {}, with infidelity: {}".format( result_step.termination_reason, result_step.fid_err)) # Check step and flat produced different results assert_(np.any( np.abs(result_flat.final_amps - result_step.final_amps) > 1e-3), msg="Flat and step drift result in " "the same control pules")
def test_9_time_dependent_drift(self): """ control.pulseoptim: Hadamard gate with fixed and time varying drift assert that goal is achieved for both and that different control pulses are produced (only) when they should be """ # Hadamard H_0 = sigmaz() H_c = [sigmax()] U_0 = identity(2) U_targ = hadamard_transform(1) n_ts = 20 evo_time = 10 drift_amps_flat = np.ones([n_ts], dtype=float) dript_amps_step = [np.round(float(k)/n_ts) for k in range(n_ts)] # Run the optimisations result_fixed = cpo.optimize_pulse_unitary(H_0, H_c, U_0, U_targ, n_ts, evo_time, fid_err_targ=1e-10, init_pulse_type='LIN', gen_stats=True) assert_(result_fixed.goal_achieved, msg="Fixed drift goal not achieved. " "Terminated due to: {}, with infidelity: {}".format( result_fixed.termination_reason, result_fixed.fid_err)) H_d = [drift_amps_flat[k]*H_0 for k in range(n_ts)] result_flat = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ, n_ts, evo_time, fid_err_targ=1e-10, init_pulse_type='LIN', gen_stats=True) assert_(result_flat.goal_achieved, msg="Flat drift goal not achieved. " "Terminated due to: {}, with infidelity: {}".format( result_flat.termination_reason, result_flat.fid_err)) # Check fixed and flat produced the same pulse assert_almost_equal(result_fixed.final_amps, result_flat.final_amps, decimal=9, err_msg="Flat and fixed drift result in " "different control pules") H_d = [dript_amps_step[k]*H_0 for k in range(n_ts)] result_step = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ, n_ts, evo_time, fid_err_targ=1e-10, init_pulse_type='LIN', gen_stats=True) assert_(result_step.goal_achieved, msg="Step drift goal not achieved. " "Terminated due to: {}, with infidelity: {}".format( result_step.termination_reason, result_step.fid_err)) # Check step and flat produced different results assert_(np.any( np.abs(result_flat.final_amps - result_step.final_amps) > 1e-3), msg="Flat and step drift result in " "the same control pules")
def test_06_2_compare_state_and_unitary_func(self): "sesolve: compare state and unitary operator evo - func td" eps = 0.2 * 2 * np.pi delta = 1.0 * 2 * np.pi # atom frequency w0 = 0.5 * eps w1 = 0.5 * delta H0 = w0 * sigmaz() H1 = w1 * sigmax() a = 0.1 alpha = 0.1 td_args = {'a': a, 'alpha': alpha} H_func = lambda t, args: a * t * H0 + H1 * np.exp(-alpha * t) H = H_func psi0 = basis(2, 0) # initial state tlist = np.linspace(0, 20, 200) self.compare_evolution(H, psi0, tlist, normalize=False, td_args=td_args, tol=5e-5) self.compare_evolution(H, psi0, tlist, normalize=True, td_args=td_args, tol=5e-5)
def test_create_bath_errors(self): Q = sigmaz() H = sigmax() mixed_types = [ BathExponent("+", 2, Q=Q, ck=1.1, vk=2.1, sigma_bar_k_offset=1), BathExponent("-", 2, Q=Q, ck=1.2, vk=2.2, sigma_bar_k_offset=-1), BathExponent("R", 2, Q=Q, ck=1.2, vk=2.2), ] mixed_q_dims = [ BathExponent("I", 2, Q=tensor(Q, Q), ck=1.2, vk=2.2), BathExponent("R", 2, Q=Q, ck=1.2, vk=2.2), ] with pytest.raises(ValueError) as err: HEOMSolver(H, Bath(mixed_types), 2) assert str(err.value) == ( "Bath exponents are currently restricted to being either all" " bosonic or all fermionic, but a mixture of bath exponents was" " given.") with pytest.raises(ValueError) as err: HEOMSolver(H, Bath(mixed_q_dims), 2) assert str(err.value) == ( "All bath exponents must have system coupling operators with the" " same dimensions but a mixture of dimensions was given.")
def test_06_4_compare_state_and_unitary_list_str(self): "sesolve: compare state and unitary operator evo - list str td" eps = 0.2 * 2 * np.pi delta = 1.0 * 2 * np.pi # atom frequency w0 = 0.5 * eps w1 = 0.5 * delta H0 = w0 * sigmaz() H1 = w1 * sigmax() w_a = w0 td_args = {'w_a': w_a} H = [H0, [H1, 'cos(w_a*t)']] psi0 = basis(2, 0) # initial state tlist = np.linspace(0, 20, 200) self.compare_evolution(H, psi0, tlist, normalize=False, td_args=td_args, tol=5e-5) self.compare_evolution(H, psi0, tlist, normalize=True, td_args=td_args, tol=5e-5)
def test_01_3_unitary_hadamard_tau(self): """ control.pulseoptim: Hadamard gate with linear initial pulses (tau) assert that goal is achieved """ # Hadamard H_d = sigmaz() H_c = [sigmax()] U_0 = identity(2) U_targ = hadamard_transform(1) # Run the optimisation #Try setting timeslots with tau array tau = np.arange(1.0, 10.0, 1.0) result = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ, tau=tau, fid_err_targ=1e-10, init_pulse_type='LIN', gen_stats=False) assert_(result.goal_achieved, msg="Hadamard goal not achieved " "(tau as timeslots). " "Terminated due to: {}, with infidelity: {}".format( result.termination_reason, result.fid_err))
def test_01_2_unitary_hadamard_no_stats(self): """ control.pulseoptim: Hadamard gate with linear initial pulses (no stats) assert that goal is achieved """ # Hadamard H_d = sigmaz() H_c = [sigmax()] U_0 = identity(2) U_targ = hadamard_transform(1) n_ts = 10 evo_time = 10 # Run the optimisation #Try without stats result = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ, n_ts, evo_time, fid_err_targ=1e-10, init_pulse_type='LIN', gen_stats=False) assert_(result.goal_achieved, msg="Hadamard goal not achieved " "(no stats). " "Terminated due to: {}, with infidelity: {}".format( result.termination_reason, result.fid_err))
def initialize_parameters(): ''' Initialize all relevant parameters required to run control pulse optimizer ''' # Defining components for initial and target states Drift_Hamiltonian = sigmaz() Control_hamiltonian = [sigmax()] Initial_unitary = identity(2) Target_unitary = hadamard_transform(1) # Define time evolution parameters num_timesteps = 10 evolution_time = 10 # Pulse optimization termination conditions fidelity_error_required = 1e-10 max_iter = 200 max_wall_time = 120 # Minimum gradient. As this tends to 0 -> local minima has been found minimum_gradient = 1e-20 # pulse type alternatives: RND|ZERO|LIN|SINE|SQUARE|SAW|TRIANGLE| p_type = 'SINE' return Drift_Hamiltonian, Control_hamiltonian, Initial_unitary, Target_unitary, \ num_timesteps, evolution_time, fidelity_error_required, max_iter, max_wall_time, minimum_gradient, p_type
def test_01_6_unitary_hadamard_grad(self): """ control.pulseoptim: Hadamard gate gradient check assert that gradient approx and exact gradient match in tolerance """ # Hadamard H_d = sigmaz() H_c = [sigmax()] U_0 = identity(2) U_targ = hadamard_transform(1) n_ts = 10 evo_time = 10 # Create the optim objects optim = cpo.create_pulse_optimizer(H_d, H_c, U_0, U_targ, n_ts, evo_time, fid_err_targ=1e-10, dyn_type='UNIT', init_pulse_type='LIN', gen_stats=True) dyn = optim.dynamics init_amps = optim.pulse_generator.gen_pulse().reshape([-1, 1]) dyn.initialize_controls(init_amps) # Check the exact gradient func = optim.fid_err_func_wrapper grad = optim.fid_err_grad_wrapper x0 = dyn.ctrl_amps.flatten() grad_diff = check_grad(func, grad, x0) assert_almost_equal(grad_diff, 0.0, decimal=6, err_msg="Unitary gradient outside tolerance")
def test_sesolve_bad_H(): H = sigmaz(), psi0 = basis(2, 0) tlist = np.linspace(0, 20, 200) with pytest.raises(TypeError) as exc: sesolve(H, psi0, tlist=tlist, e_ops=[qeye(3)]) assert str(exc.value).startswith("Invalid H:")
def test_qubit_power(): "Steady state: Thermal qubit - power solver" # thermal steadystate of a qubit: compare numerics with analytical formula sz = sigmaz() sm = destroy(2) H = 0.5 * 2 * np.pi * sz gamma1 = 0.05 wth_vec = np.linspace(0.1, 3, 20) p_ss = np.zeros(np.shape(wth_vec)) for idx, wth in enumerate(wth_vec): n_th = 1.0 / (np.exp(1.0 / wth) - 1) # bath temperature c_op_list = [] rate = gamma1 * (1 + n_th) c_op_list.append(np.sqrt(rate) * sm) rate = gamma1 * n_th c_op_list.append(np.sqrt(rate) * sm.dag()) rho_ss = steadystate(H, c_op_list, method='power') p_ss[idx] = expect(sm.dag() * sm, rho_ss) p_ss_analytic = np.exp(-1.0 / wth_vec) / (1 + np.exp(-1.0 / wth_vec)) delta = sum(abs(p_ss_analytic - p_ss)) assert_equal(delta < 1e-5, True)
def test_Transformation6(): "Check diagonalization via eigenbasis transformation" cx, cy, cz = np.random.rand(), np.random.rand(), np.random.rand() H = cx * sigmax() + cy * sigmay() + cz * sigmaz() evals, evecs = H.eigenstates() Heb = H.transform(evecs).tidyup() # Heb should be diagonal assert_(abs(Heb.full() - np.diag(Heb.full().diagonal())).max() < 1e-6)
def __init__(self): super(TestBloch, self).__init__() self.propagator = propagator(sigmaz(), .1, []) self.set_state(qeye(2) + sigmax()) self.timer = QtCore.QTimer() self.timer.setInterval(100) self.timer.timeout.connect(self.propagate) self.timer.start()
def test_Transformation1(): "Transform 2-level to eigenbasis and back" H1 = scipy.rand() * sigmax() + scipy.rand() * sigmay() + \ scipy.rand() * sigmaz() evals, ekets = H1.eigenstates() Heb = H1.transform(ekets) # eigenbasis (should be diagonal) H2 = Heb.transform(ekets, True) # back to original basis assert_equal((H1 - H2).norm() < 1e-6, True)
def main(): t_sequnce = np.linspace(0,160,160) lambda_z =1 lambda_x =1 omega_q =1 # 6.2 # GHZ ---- ns MHx ----- mus Hz--------s #psi0 = (1/np.sqrt(2))*(q.basis(2,0)+q.basis(2,1)) psi0 = q.basis(2,0) H_const = q.sigmaz()# 2 * np.pi *omega_q * 0.5 * q.sigmaz() H_drive = lambda_z * q.sigmaz() +lambda_x * q.sigmax() Omega = lambda t,args:np.cos(t*2 * np.pi *omega_q ) result = q.mesolve([H_const,[H_drive,Omega]],psi0,t_sequnce,[],[]).states bloch = q.Bloch() for state in result: bloch.add_states(state,'point') bloch.show() return 0
def qubit_integrate(self, tlist, psi0, epsilon, delta, g1, g2): H = epsilon / 2.0 * sigmaz() + delta / 2.0 * sigmax() c_op_list = [] rate = g1 if rate > 0.0: c_op_list.append(np.sqrt(rate) * sigmam()) rate = g2 if rate > 0.0: c_op_list.append(np.sqrt(rate) * sigmaz()) output = mesolve(H, psi0, tlist, c_op_list, [sigmax(), sigmay(), sigmaz()]) expt_list = output.expect[0], output.expect[1], output.expect[2] return expt_list[0], expt_list[1], expt_list[2]
def Hfred(x,N) : # A possible Hamiltonian for the Fredkin gate k = 0 H = 0 sx = qt.sigmax()/2 sy = qt.sigmay()/2 sz = qt.sigmaz()/2 Id = qt.qeye(2) for q in [sx, sy, sz] : temp = 0 OpChain = [Id]*N OpChain[2] = q OpChain[1] = q temp += x[k]*qt.tensor(OpChain) H += temp k+=1 for q in [sx,sz]: temp = 0 OpChain = [Id]*N OpChain[2] = q OpChain[0] = q temp += x[k]*qt.tensor(OpChain) OpChain = [Id]*N OpChain[1] = q OpChain[0] = q temp += x[k]*qt.tensor(OpChain) k += 1 H += temp for q in [1,2]: temp = 0 OpChain = [Id]*N OpChain[q] = sx OpChain[3] = sx temp += x[k]*qt.tensor(OpChain) H += temp k+=1 temp = 0 OpChain = [Id]*N OpChain[0] = sz temp += x[k]*qt.tensor(OpChain) H += temp k += 1 temp = 0 OpChain = [Id]*N OpChain[3] = sx temp += x[k]*qt.tensor(OpChain)#last one H += temp return H
def local_hamiltonian(self): field_vector = self.parent_field.field_vector.values() pauli_basis = [qt.sigmax(), qt.sigmay(), qt.sigmaz()] b_field = sum( [field_vector[i] * pauli_basis[i] for i in xrange(0, len(field_vector)) ] ) return self.gyromagnetic_ratio * b_field * const.HBAR / 2
def testTLS(self): "brmesolve: qubit" delta = 0.0 * 2 * np.pi epsilon = 0.5 * 2 * np.pi gamma = 0.25 times = np.linspace(0, 10, 100) H = delta/2 * sigmax() + epsilon/2 * sigmaz() psi0 = (2 * basis(2, 0) + basis(2, 1)).unit() c_ops = [np.sqrt(gamma) * sigmam()] a_ops = [sigmax()] e_ops = [sigmax(), sigmay(), sigmaz()] res_me = mesolve(H, psi0, times, c_ops, e_ops) res_brme = brmesolve(H, psi0, times, a_ops, e_ops, spectra_cb=[lambda w: gamma * (w >= 0)]) for idx, e in enumerate(e_ops): diff = abs(res_me.expect[idx] - res_brme.expect[idx]).max() assert_(diff < 1e-2)
def testCOPS(): """ brmesolve: c_ops alone """ delta = 0.0 * 2 * np.pi epsilon = 0.5 * 2 * np.pi gamma = 0.25 times = np.linspace(0, 10, 100) H = delta/2 * sigmax() + epsilon/2 * sigmaz() psi0 = (2 * basis(2, 0) + basis(2, 1)).unit() c_ops = [np.sqrt(gamma) * sigmam()] e_ops = [sigmax(), sigmay(), sigmaz()] res_me = mesolve(H, psi0, times, c_ops, e_ops) res_brme = brmesolve(H, psi0, times, [], e_ops, spectra_cb=[], c_ops=c_ops) for idx, e in enumerate(e_ops): diff = abs(res_me.expect[idx] - res_brme.expect[idx]).max() assert_(diff < 1e-2)
def test_diagHamiltonian1(): """ Diagonalization of random two-level system """ H = scipy.rand() * sigmax() + scipy.rand() * sigmay() +\ scipy.rand() * sigmaz() evals, ekets = H.eigenstates() for n in range(len(evals)): # assert that max(H * ket - e * ket) is small assert_equal(amax( abs((H * ekets[n] - evals[n] * ekets[n]).full())) < 1e-10, True)
def test_qpt_snot(): "quantum process tomography for snot gate" U_psi = snot() U_rho = spre(U_psi) * spost(U_psi.dag()) N = 1 op_basis = [[qeye(2), sigmax(), 1j * sigmay(), sigmaz()] for i in range(N)] # op_label = [["i", "x", "y", "z"] for i in range(N)] chi1 = qpt(U_rho, op_basis) chi2 = np.zeros((2 ** (2 * N), 2 ** (2 * N)), dtype=complex) chi2[1, 1] = chi2[1, 3] = chi2[3, 1] = chi2[3, 3] = 0.5 assert_(norm(chi2 - chi1) < 1e-8)
def test_state_to_state(self): """ control.pulseoptim: state-to-state transfer linear initial pulse used assert that goal is achieved """ # 2 qubits with Ising interaction # some arbitary coupling constants alpha = [0.9, 0.7] beta = [0.8, 0.9] Sx = sigmax() Sz = sigmaz() H_d = (alpha[0]*tensor(Sx,identity(2)) + alpha[1]*tensor(identity(2),Sx) + beta[0]*tensor(Sz,identity(2)) + beta[1]*tensor(identity(2),Sz)) H_c = [tensor(Sz,Sz)] q1_0 = q2_0 = Qobj([[1], [0]]) q1_T = q2_T = Qobj([[0], [1]]) psi_0 = tensor(q1_0, q2_0) psi_T = tensor(q1_T, q2_T) n_ts = 10 evo_time = 18 # Run the optimisation result = cpo.optimize_pulse_unitary(H_d, H_c, psi_0, psi_T, n_ts, evo_time, fid_err_targ=1e-10, init_pulse_type='LIN', gen_stats=True) assert_(result.goal_achieved, msg="State-to-state goal not achieved. " "Terminated due to: {}, with infidelity: {}".format( result.termination_reason, result.fid_err)) assert_almost_equal(result.fid_err, 0.0, decimal=10, err_msg="Hadamard infidelity too high") #Try with Qobj propagation result = cpo.optimize_pulse_unitary(H_d, H_c, psi_0, psi_T, n_ts, evo_time, fid_err_targ=1e-10, init_pulse_type='LIN', dyn_params={'oper_dtype':Qobj}, gen_stats=True) assert_(result.goal_achieved, msg="State-to-state goal not achieved " "(Qobj propagation)" "Terminated due to: {}, with infidelity: {}".format( result.termination_reason, result.fid_err))
def as_qobj(self): """ Returns a representation of the given Pauli operator as a QuTiP Qobj instance. """ if qt is None: raise RuntimeError("Requires QuTiP.") if self == Pauli.I: return qt.qeye(2) elif self == Pauli.X: return qt.sigmax() elif self == Pauli.Y: return qt.sigmay() else: return qt.sigmaz()
def ptracetest(): gamma = 1. neq = 2 psi0 = qt.basis(neq,neq-1) psi0 = qt.tensor(psi0,psi0) H = qt.tensor(qt.sigmax(),qt.sigmay()) c1 = np.sqrt(gamma)*qt.sigmax() e1 = np.sqrt(gamma)*qt.sigmaz() c_ops = [qt.tensor(c1,c1)] e_ops = [qt.tensor(e1,e1),qt.tensor(c1,c1)] #e_ops = [] tlist = np.linspace(0,10,100) ntraj = 2000 ptrace_sel = [0] sol_f90 = mcf90.mcsolve_f90(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj, ptrace_sel=ptrace_sel,calc_entropy=True)