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 _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 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 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 __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 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)
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 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 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 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 construct_hamiltonian(self, number_of_spins, alpha): """ following example http://qutip.googlecode.com/svn/doc/2.0.0/html/examples/me/ex-24.html returns H0 - hamiltonian without the B field and y_list - list of sigma_y operators """ N = number_of_spins si = qeye(2) sx = sigmax() sy = sigmay() # constructing a list of operators sx_list and sy_list where # the operator sx_list[i] applies sigma_x on the ith particle and # identity to the rest sx_list = [] sy_list = [] for n in range(N): op_list = [] for m in range(N): op_list.append(si) op_list[n] = sx sx_list.append(tensor(op_list)) op_list[n] = sy sy_list.append(tensor(op_list)) # construct the hamiltonian H0 = 0 # ising coupling term, time independent for i in range(N): for j in range(N): if i < j: H0 -= abs(i - j) ** -alpha * sx_list[i] * sx_list[j] H1 = 0 for i in range(N): H1 -= sy_list[i] return H0, H1
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_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_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 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_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 construct_hamiltonian(self, number_of_spins, alpha, B): ''' following example http://qutip.googlecode.com/svn/doc/2.0.0/html/examples/me/ex-24.html ''' N = number_of_spins si = qeye(2) sx = sigmax() sy = sigmay() #constructing a list of operators sx_list and sy_list where #the operator sx_list[i] applies sigma_x on the ith particle and #identity to the rest sx_list = [] sy_list = [] for n in range(N): op_list = [] for m in range(N): op_list.append(si) op_list[n] = sx sx_list.append(tensor(op_list)) op_list[n] = sy sy_list.append(tensor(op_list)) #construct the hamiltonian H = 0 #magnetic field term, hamiltonian is in units of J0 for i in range(N): H-= B * sy_list[i] #ising coupling term for i in range(N): for j in range(N): if i < j: H+= abs(i - j)**-alpha * sx_list[i] * sx_list[j] return H
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 __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_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 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 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 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 test_operator_between_cells(self): lattice_412 = qutip.Lattice1d(num_cell=4, boundary="periodic", cell_num_site=1, cell_site_dof=[2]) op = qutip.sigmax() op_sp = lattice_412.operator_at_cells(op, cells=[1, 2]) aop_sp = np.zeros((8, 8), dtype=complex) aop_sp[2:4, 2:4] = aop_sp[4:6, 4:6] = op.full() sv_op_sp = qutip.Qobj(aop_sp, dims=[[4, 2], [4, 2]]) assert op_sp == sv_op_sp
def rotate_player(self, who, rot, dt=0.01, inverse=False): x, y, z = rot unitary = (2*math.pi*1j*dt*(x*qt.sigmax() + y*qt.sigmay() + z*qt.sigmaz())).expm() total_unitary = upgrade_tensor(unitary, who, self.n_players) if inverse: total_unitary = total_unitary.dag() total_unitary.dims = [[total_unitary.shape[0]], [total_unitary.shape[0]]] copy = self.current_state.copy() if total_unitary.dims[0] == self.current_state.dims[0]: self.current_state = total_unitary*self.current_state
def test_01_1_state_with_const_H(self): "sesolve: state with const H" delta = 1.0 * 2*np.pi # atom frequency psi0 = basis(2, 0) # initial state H1 = 0.5*delta*sigmax() # Hamiltonian operator tlist = np.linspace(0, 20, 200) analytic_func = lambda t, args: t self.check_evolution(H1, delta, psi0, tlist, analytic_func)
def test_cyclic_permutation(self): operators = [qutip.sigmax(), qutip.sigmaz()] test = gates.expand_operator(qutip.tensor(*operators), N=3, targets=[0, 1], cyclic_permutation=True) base_expected = qutip.tensor(*operators, qutip.qeye(2)) expected = [base_expected.permute(x) for x in [[0, 1, 2], [1, 2, 0], [2, 0, 1]]] assert len(expected) == len(test) for element in expected: assert element in test
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 test_combine(self): exp_ix = BathExponent("I", None, Q=sigmax(), ck=2.0, vk=0.5) exp_rx = BathExponent("R", None, Q=sigmax(), ck=1.0, vk=0.5) exp_rix = BathExponent("RI", None, Q=sigmax(), ck=0.1, vk=0.5, ck2=0.2) exp_rz = BathExponent("R", None, Q=sigmaz(), ck=1.0, vk=0.5) [exp] = BosonicBath.combine([exp_rx, exp_rx]) check_exponent(exp, "R", dim=None, Q=sigmax(), ck=2.0, vk=0.5) [exp] = BosonicBath.combine([exp_ix, exp_ix]) check_exponent(exp, "I", dim=None, Q=sigmax(), ck=4.0, vk=0.5) [exp] = BosonicBath.combine([exp_rix, exp_rix]) check_exponent( exp, "RI", dim=None, Q=sigmax(), ck=0.2, vk=0.5, ck2=0.4, ) [exp1, exp2] = BosonicBath.combine([exp_rx, exp_rz]) check_exponent(exp1, "R", dim=None, Q=sigmax(), ck=1.0, vk=0.5) check_exponent(exp2, "R", dim=None, Q=sigmaz(), ck=1.0, vk=0.5) [exp] = BosonicBath.combine([exp_rx, exp_ix]) check_exponent( exp, "RI", dim=None, Q=sigmax(), ck=1.0, vk=0.5, ck2=2.0, ) [exp] = BosonicBath.combine([exp_rx, exp_ix, exp_rix]) check_exponent( exp, "RI", dim=None, Q=sigmax(), ck=1.1, vk=0.5, ck2=2.2, )
def test_qsave_qload(): ops_in = [ qutip.sigmax(), qutip.num(_dimension), qutip.coherent_dm(_dimension, 1j) ] filename = _random_file_name() qutip.qsave(ops_in, filename) ops_out = qutip.qload(filename) assert ops_in == ops_out
def keyboard(event): global selected global alice global bob global touched key = event.key if key == "a": if selected == "Bob": bob = apply(qutip.sigmax(), bob, inverse=True) else: alice = apply(qutip.sigmax(), alice, inverse=True) elif key == "d": if selected == "Bob": bob = apply(qutip.sigmax(), bob, inverse=False) else: alice = apply(qutip.sigmax(), alice, inverse=False) elif key == "s": if selected == "Bob": bob = apply(qutip.sigmaz(), bob, inverse=True) else: alice = apply(qutip.sigmaz(), alice, inverse=True) elif key == "w": if selected == "Bob": bob = apply(qutip.sigmaz(), bob, inverse=False) else: alice = apply(qutip.sigmaz(), alice, inverse=False) elif key == "z": if selected == "Bob": bob = apply(qutip.sigmay(), bob, inverse=True) else: alice = apply(qutip.sigmay(), alice, inverse=True) elif key == "x": if selected == "Bob": bob = apply(qutip.sigmay(), bob, inverse=False) else: alice = apply(qutip.sigmay(), alice, inverse=False) elif key == "p": if selected == "Bob": selected = "Alice" else: selected = "Bob" touched = True
def keyboard(event): global dt global a global b key = event.key operator = None if key == "a": #-x for A operator = qutip.Qobj(scipy.linalg.expm(-2*math.pi*complex(0,1)*qutip.sigmax().full()*dt)) a = operator.dag()*a elif key == "d": #+x for A operator = qutip.Qobj(scipy.linalg.expm(-2*math.pi*complex(0,1)*qutip.sigmax().full()*dt)) a = operator*a elif key == "s": #-z for A operator = qutip.Qobj(scipy.linalg.expm(-2*math.pi*complex(0,1)*qutip.sigmaz().full()*dt)) a = operator.dag()*a elif key == "w": #+z for A operator = qutip.Qobj(scipy.linalg.expm(-2*math.pi*complex(0,1)*qutip.sigmaz().full()*dt)) a = operator*a elif key == "z": #-y for A operator = qutip.Qobj(scipy.linalg.expm(-2*math.pi*complex(0,1)*qutip.sigmay().full()*dt)) a = operator.dag()*a elif key == "x": #+y for A operator = qutip.Qobj(scipy.linalg.expm(-2*math.pi*complex(0,1)*qutip.sigmay().full()*dt)) a = operator*a elif key == "j": #-x for B operator = qutip.Qobj(scipy.linalg.expm(-2*math.pi*complex(0,1)*qutip.sigmax().full()*dt)) b = operator.dag()*b elif key == "l": #+x for B operator = qutip.Qobj(scipy.linalg.expm(-2*math.pi*complex(0,1)*qutip.sigmax().full()*dt)) b = operator*b elif key == "k": #-z for B operator = qutip.Qobj(scipy.linalg.expm(-2*math.pi*complex(0,1)*qutip.sigmaz().full()*dt)) b = operator.dag()*b elif key == "i": #+z for B operator = qutip.Qobj(scipy.linalg.expm(-2*math.pi*complex(0,1)*qutip.sigmaz().full()*dt)) b = operator*b elif key == "m": #-y for B operator = qutip.Qobj(scipy.linalg.expm(-2*math.pi*complex(0,1)*qutip.sigmay().full()*dt)) b = operator.dag()*b elif key == ",": #+y for B operator = qutip.Qobj(scipy.linalg.expm(-2*math.pi*complex(0,1)*qutip.sigmay().full()*dt)) b = operator*b
def test_bigreal_conversion(self): test_vec1 = np.array([1, 2]) test_vec2 = np.array([1j, 1 - 2j]) test_matrix1 = np.array([[0.2, 0.1], [1., -3.]]) test_matrix2 = qutip.sigmax() target_bigreal_vec = np.array([[1], [2], [0], [0]]) assert_array_equal( utils.complex2bigreal(test_vec1), target_bigreal_vec) assert_array_equal( utils.complex2bigreal(qutip.sigmax()), np.array([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) ) assert_array_equal( utils.complex2bigreal(qutip.sigmay()), np.array([[0, 0, 0, 1], [0, 0, -1, 0], [0, -1, 0, 0], [1, 0, 0, 0]]) ) # test back and forth between complex and bigreal form assert_array_equal( utils.bigreal2complex(utils.complex2bigreal(test_vec1)), test_vec1.reshape((len(test_vec1), 1)) ) assert_array_equal( utils.bigreal2complex(utils.complex2bigreal(test_vec2)), test_vec2.reshape((len(test_vec2), 1)) ) assert_array_equal( utils.bigreal2complex(utils.complex2bigreal(test_matrix1)), test_matrix1 ) assert_array_equal( utils.bigreal2complex(utils.complex2bigreal(test_matrix2)), test_matrix2.data.toarray() )
def test_regression_490(): """Test for regression of gh-490.""" h = [qutip.sigmax(), [qutip.sigmay(), _regression_490_f1], [qutip.sigmaz(), _regression_490_f2]] state = (qutip.basis(2, 0) + qutip.basis(2, 1)).unit() times = np.linspace(0, 3, 10) result_me = qutip.mesolve(h, state, times) result_mc = qutip.mcsolve(h, state, times, ntraj=1) for state_me, state_mc in zip(result_me.states, result_mc.states): np.testing.assert_allclose(state_me.full(), state_mc.full(), atol=1e-8)
def __init__(self, omega_0, td_protocol=None): self.name = 'lz' self.model_parameters = dict(omega_0=omega_0) self.critical_value = 0. if td_protocol is not None and isinstance(td_protocol, str): self._parse_td_protocol(td_protocol) else: self.td_protocol = td_protocol self.H0 = omega_0 * qutip.sigmax() self.H1 = qutip.sigmaz()
def set_up_ops(self, num_qubits): """ Generate the Hamiltonians for the spinchain model and save them in the attribute `ctrls`. Parameters ---------- num_qubits: int The number of qubits in the system. """ # sx_ops for m in range(num_qubits): self.add_control(sigmax(), m, label="sx" + str(m)) # sz_ops for m in range(num_qubits): self.add_control(sigmaz(), m, label="sz" + str(m)) # sxsy_ops operator = tensor([sigmax(), sigmax()]) + tensor([sigmay(), sigmay()]) for n in range(num_qubits - 1): self.add_control(operator, [n, n+1], label="g" + str(n))
def R_k_pulse(k, theta, phi, N: int = 4, tau: float = 1): Id = qt.qeye(2) if N == 1: X = qt.sigmax() Y = qt.sigmay() else: X = [Id]*(N - 1) Y = [Id]*(N - 1) X.insert(k, qt.sigmax()) Y.insert(k, qt.sigmay()) X = qt.tensor(X) Y = qt.tensor(Y) H_c = [[X, [theta/2/tau*np.cos(phi)], 'I'*k + 'X' + 'I'*(N - k - 1)], [Y, [theta/2/tau*np.sin(phi)], 'I'*k + 'Y' + 'I'*(N - k - 1)]] H_n = [[X/np.sqrt(X.shape[0]), [1], 'I'*k + 'X' + 'I'*(N - k - 1)], [Y/np.sqrt(Y.shape[0]), [1], 'I'*k + 'Y' + 'I'*(N - k - 1)]] dt = [tau] return ff.PulseSequence(H_c, H_n, dt)
def test_commutator(): A = qutip.qeye(N) B = qutip.destroy(N) assert qutip.commutator(A, B) == qutip.qzero(N) sx = qutip.sigmax() sy = qutip.sigmay() assert qutip.commutator(sx, sy) / 2 == (qutip.sigmaz() * 1j) A = qutip.qeye(N) B = qutip.destroy(N) assert qutip.commutator(A, B, 'anti') == qutip.destroy(N) * 2 sx = qutip.sigmax() sy = qutip.sigmay() assert qutip.commutator(sx, sy, 'anti') == qutip.qzero(2) with pytest.raises(TypeError) as e: qutip.commutator(sx, sy, 'something') assert str(e.value).startswith("Unknown commutator kind")
def test_makeBlochEqSyms(): H0 = toDense(q.sigmaz() * q.sigmaz().dag()) H1 = toDense(q.sigmax()) c_opL = [toDense(q.destroy(2))] delt = sm.symbols('Delta', real=True) Ef = sm.symbols("Ef") return makeBlochEqSymbs(H0, Hfield_L=[[Ef, H1]], Hother_L=[], c_opL=[], rhoS=None)
def as_qobj(self): if self == Pauli.I: return qt.qeye(2) elif self == Pauli.X: return qt.sigmax() elif self == Pauli.Y: return qt.sigmay() elif self == Pauli.Z: return qt.sigmaz() else: raise ValueError(f"Unrecognized Pauli value {self}.")
def _model(self, amps, phis, r, theta, phi, A, offset): tomo_z_data = [] rho_0 = self._dm_from_sph_coords(r, theta, phi) for amp in amps: phi_data = [] for phi in phis: gate = (-1j * amp * pi / 2 * (cos(phi) * sigmax() + sin(phi) * sigmay())).expm() rho_1 = gate * rho_0 * gate.dag() phi_data.append(expect(sigmaz(), rho_1)) tomo_z_data.append(phi_data) return (array(tomo_z_data) + 1) / 2 * A + offset
def test_lindblad_no_dissipation(self): """ Use the previous test to verify the Lindblad master equation in absence of decoherence terms. """ h_drift = [ matrix.DenseOperator(np.zeros((2, 2), dtype=complex)) for _ in range(4) ] h_control = [ .5 * matrix.DenseOperator(qutip.sigmax()), .5 * matrix.DenseOperator(qutip.sigmaz()) ] ctrl_amps = np.asarray([[.5, 0, .25, .25], [0, .5, 0, 0] ]).T * 2 * math.pi tau = [1, 1, 1, 1] dissipation_sup_op = [matrix.DenseOperator(np.zeros((4, 4)))] initial_state = matrix.DenseOperator(np.eye(4)) lindblad_tslot_obj = solver_algorithms.LindbladSolver( h_ctrl=h_control, h_drift=h_drift, tau=tau, initial_state=initial_state, ctrl_amps=ctrl_amps, initial_diss_super_op=dissipation_sup_op, calculate_unitary_derivatives=True) propagators = lindblad_tslot_obj.propagators # test the propagators # use the exponential identity for pauli operators for verification correct_props = [[[0. + 0.j, 0. - 1.j], [0. - 1.j, 0. + 0.j]], [[0. - 1.j, 0. + 0.j], [0. + 0.j, 0. + 1.j]], [[0.70710678 + 0.j, 0. - 0.70710678j], [0. - 0.70710678j, 0.70710678 + 0.j]], [[0.70710678 + 0.j, 0. - 0.70710678j], [0. - 0.70710678j, 0.70710678 + 0.j]]] correct_props = list(map(np.asarray, correct_props)) correct_props = [np.kron(cp.conj(), cp) for cp in correct_props] for i in range(4): np.testing.assert_array_almost_equal(correct_props[i], propagators[i].data) analytic_reference = -.5j * np.eye(2, dtype=complex) sx = np.asarray([[0, 1], [1, 0]]) * (1 + 0j) analytic_reference = np.kron(sx, analytic_reference) \ - np.kron(analytic_reference, sx) np.testing.assert_array_almost_equal( analytic_reference, lindblad_tslot_obj.frechet_deriv_propagators[0][0].data)
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 keyboard(event): global qubits global active_qubit key = event.key if key.isdigit(): i = int(key) if i < n_qubits: active_qubit = i elif key == "a": qubits[active_qubit].evolve(qutip.sigmax(), inverse=True) elif key == "d": qubits[active_qubit].evolve(qutip.sigmax(), inverse=False) elif key == "s": qubits[active_qubit].evolve(qutip.sigmaz(), inverse=True) elif key == "w": qubits[active_qubit].evolve(qutip.sigmaz(), inverse=False) elif key == "z": qubits[active_qubit].evolve(qutip.sigmay(), inverse=True) elif key == "x": qubits[active_qubit].evolve(qutip.sigmay(), inverse=False)
def test_random_noise(self): """ Test for the white noise """ tlist = np.array([1, 2, 3, 4, 5, 6]) coeff = np.array([1, 1, 1, 1, 1, 1]) dummy_qobjevo = QobjEvo(sigmaz(), tlist=tlist) mean = 0. std = 0.5 pulses = [Pulse(sigmaz(), 0, tlist, coeff), Pulse(sigmax(), 0, tlist, coeff*2), Pulse(sigmay(), 0, tlist, coeff*3)] # random noise with operators from proc_qobjevo gaussnoise = RandomNoise( dt=0.1, rand_gen=np.random.normal, loc=mean, scale=std) noisy_pulses, systematic_noise = \ gaussnoise.get_noisy_dynamics(pulses=pulses) assert_allclose(noisy_pulses[2].qobj, sigmay()) assert_allclose(noisy_pulses[1].coherent_noise[0].qobj, sigmax()) assert_allclose( len(noisy_pulses[0].coherent_noise[0].tlist), len(noisy_pulses[0].coherent_noise[0].coeff)) # random noise with dt and other random number generator pulses = [Pulse(sigmaz(), 0, tlist, coeff), Pulse(sigmax(), 0, tlist, coeff*2), Pulse(sigmay(), 0, tlist, coeff*3)] gaussnoise = RandomNoise(lam=0.1, dt=0.2, rand_gen=np.random.poisson) assert_(gaussnoise.rand_gen is np.random.poisson) noisy_pulses, systematic_noise = \ gaussnoise.get_noisy_dynamics(pulses=pulses) assert_allclose( noisy_pulses[0].coherent_noise[0].tlist, np.linspace(1, 6, int(5/0.2) + 1)) assert_allclose( noisy_pulses[1].coherent_noise[0].tlist, np.linspace(1, 6, int(5/0.2) + 1)) assert_allclose( noisy_pulses[2].coherent_noise[0].tlist, np.linspace(1, 6, int(5/0.2) + 1))
def hermitian_txyz(hermitian): def scalarProduct(m, n): return 0.5 * np.trace(np.dot(np.conjugate(m).T, n)) t = scalarProduct(hermitian, np.eye(2)).real x = scalarProduct(hermitian, qutip.sigmax().full()).real y = scalarProduct(hermitian, qutip.sigmay().full()).real z = scalarProduct( hermitian, qutip.sigmaz().full(), ).real return np.array([t, x, y, z])
def test_user_defined_noise(self): """ Test for the user-defined noise object """ dr_noise = DriftNoise(sigmax()) proc = Processor(1) proc.add_noise(dr_noise) tlist = np.array([0, np.pi/2.]) proc.add_pulse(Pulse(identity(2), 0, tlist, False)) result = proc.run_state(init_state=basis(2, 0)) assert_allclose( fidelity(result.states[-1], basis(2, 1)), 1, rtol=1.0e-6)
def test_simple_qubit_system(me_c_ops, brme_c_ops, brme_a_ops): delta = 0.0 * 2 * np.pi epsilon = 0.5 * 2 * np.pi e_ops = pauli_spin_operators() H = delta * 0.5 * qutip.sigmax() + epsilon * 0.5 * qutip.sigmaz() psi0 = (2 * qutip.basis(2, 0) + qutip.basis(2, 1)).unit() times = np.linspace(0, 10, 100) me = qutip.mesolve(H, psi0, times, c_ops=me_c_ops, e_ops=e_ops).expect brme = qutip.brmesolve([[H, '1']], psi0, times, brme_a_ops, e_ops, brme_c_ops).expect for me_expectation, brme_expectation in zip(me, brme): assert np.allclose(me_expectation, brme_expectation, atol=1e-2)
def viz_update(): global state, G, basis, vpts n = len(state.dims[0]) for i in range(n): pov_state = take_pov(state, 0, i, G, basis=basis) for k in range(n): partial = pov_state.ptrace(k) xyz = np.array([qt.expect(qt.sigmax(), partial),\ qt.expect(qt.sigmay(), partial),\ qt.expect(qt.sigmaz(), partial)]) vpts[(i, k)].axis = vp.vector(*xyz) vpts[(i, k)].visible = not np.isclose(np.linalg.norm(xyz), 0)
def test_02_1_qft(self): """ control.pulseoptim: QFT gate with linear initial pulses assert that goal is achieved and fidelity error is below threshold """ 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, init_pulse_type='LIN', gen_stats=True) assert_(result.goal_achieved, msg="QFT goal not achieved. " "Terminated due to: {}, with infidelity: {}".format( result.termination_reason, result.fid_err)) assert_almost_equal(result.fid_err, 0.0, decimal=7, err_msg="QFT infidelity too high") # check bounds result2 = 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_((result2.final_amps >= -1.0).all() and (result2.final_amps <= 1.0).all(), msg="Amplitude bounds exceeded for QFT")
def test_pulse_mode(self): processor = Processor(2) processor.add_control(sigmax(), targets=0, label="sx") processor.set_coeffs({"sx": np.array([1., 2., 3.])}) processor.set_tlist({"sx": np.array([0., 1., 2., 3.])}) processor.pulse_mode = "continuous" assert (processor.pulse_mode == "continuous") assert (processor.pulses[0].spline_kind == "cubic") processor.pulse_mode = "discrete" assert (processor.pulse_mode == "discrete") assert (processor.pulses[0].spline_kind == "step_func")
def test_distribute_operator(self): """ lattice: Test the method Lattice1d.distribute_operator(). """ lattice_412 = Lattice1d(num_cell=4, boundary="periodic", cell_num_site=1, cell_site_dof=[2]) op = Qobj(np.array([[0, 1], [1, 0]])) op_all = lattice_412.distribute_operator(op) sv_op_all = tensor(qeye(4), sigmax()) assert_(op_all == sv_op_all)
def test_hamiltonian_order_unimportant(): # Testing for regression on issue 1048. sp = qutip.sigmap() H = [[qutip.sigmax(), lambda t, _: _step(t-2)], [qutip.qeye(2), lambda t, _: _step(-(t-2))]] start = qutip.basis(2, 0) times = np.linspace(0, 5, 6) forwards = qutip.correlation_2op_2t(H, start, times, times, [sp], sp.dag(), sp) backwards = qutip.correlation_2op_2t(H[::-1], start, times, times, [sp], sp.dag(), sp) np.testing.assert_allclose(forwards, backwards, atol=1e-6)
def excitation(args): H0 = args['parity']*args['vFermi']*(args['kpoint'][0]*qp.sigmax() + args['kpoint'][1]*qp.sigmay()) H1 = qp.sigmax() H2 = qp.sigmay() Hamiltonian = [H0,[H1,HCoeff]] states = H0.eigenstates() psi0 = states[1][0] psi1 = states[1][1] import hashlib label = hashlib.sha224(str(args)).hexdigest() import os if os.path.exists('Data/'+label+'.qu'): result = qp.qload('Data/'+label) print 'Loading' else: result = qp.mesolve(Hamiltonian, psi0, args['times'], [], [], args=args) print 'Recalculate' qp.qsave(result, 'Data/'+ label) proj0 = np.array([(state.dag()*psi0).norm() for state in result.states]) proj1 = np.array([(state.dag()*psi1).norm() for state in result.states]) return result, proj0, proj1
def _crow_lattice(coupling, phase_delay, cells=4, boundary="periodic", sites_per_cell=1, freedom=[2]): r""" Return a `qutip.Lattice1d` of a "Coupled Resonator Optical Waveguide" (CROW) with the given coupling strength and phase delay. See for example: https://www.doi.org/10.1103/PhysRevB.99.224201 where `coupling` is $J$ and `phase_delay` is $\eta$. """ cell_hamiltonian = coupling * np.sin(phase_delay) * qutip.sigmax() phase_term = np.exp(1j * phase_delay) hopping = [ 0.5 * coupling * qutip.qdiags([phase_term, phase_term.conj()], 0), 0.5 * coupling * qutip.sigmax(), ] return qutip.Lattice1d(num_cell=cells, boundary=boundary, cell_num_site=sites_per_cell, cell_site_dof=freedom, Hamiltonian_of_cell=cell_hamiltonian, inter_hop=hopping)
def run(): from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() print "Process number", rank, "of", size, "total." neq = 2 gamma = 1.0 psi0 = qt.basis(neq,neq-1) H = qt.sigmax() c_ops = [np.sqrt(gamma)*qt.sigmax()] e_ops = [qt.sigmam()*qt.sigmap()] tlist = np.linspace(0,10,100) ntraj=100 # One CPU per MPI process opts = qt.Odeoptions() opts.num_cpus = 1 # Solve sols = mcf90.mcsolve_f90(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,options=opts) #sols = qt.mcsolve(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,options=opts) # Gather data sols = comm.gather(sols,root=0) if (rank==0): sol = sols[0] sol.expect = np.array(sols[0].expect) plt.figure() plt.plot(tlist,sols[0].expect[0],'r',label='proc '+str(0)) for i in range(1,size): plt.plot(tlist,sols[i].expect[0],'r',label='proc '+str(i)) sol.expect += np.array(sols[i].expect) sol.expect = sol.expect/size plt.plot(tlist,sol.expect[0],'b',label='average') plt.legend() plt.show()
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))