def test_spectrum_esfft(): """ correlation: comparing spectrum from es and fft methods """ # use JC model N = 4 wc = wa = 1.0 * 2 * np.pi g = 0.1 * 2 * np.pi kappa = 0.75 gamma = 0.25 n_th = 0.01 a = tensor(destroy(N), qeye(2)) sm = tensor(qeye(N), destroy(2)) H = wc * a.dag() * a + wa * sm.dag() * sm + \ g * (a.dag() * sm + a * sm.dag()) c_ops = [np.sqrt(kappa * (1 + n_th)) * a, np.sqrt(kappa * n_th) * a.dag(), np.sqrt(gamma) * sm] with warnings.catch_warnings(): warnings.simplefilter("ignore") tlist = np.linspace(0, 100, 2500) corr = correlation_ss(H, tlist, c_ops, a.dag(), a) wlist1, spec1 = spectrum_correlation_fft(tlist, corr) spec2 = spectrum_ss(H, wlist1, c_ops, a.dag(), a) assert_(max(abs(spec1 - spec2)) < 1e-3)
def rsb_flop(rho0, W, eta, delta, theta, phi, c_op_list = [], return_op_list = []): ''' Return values of atom and motion populations during red sideband Rabi flop for rotation angles theta. Calls numerical solution of master equation for the Jaynes-Cummings Hamiltonian. @ var rho0: initial density matrix @ var W: bare Rabi frequency @ var delta: detuning between atom and motion @ var theta: list of Rabi rotation angle (i.e. theta, or g*time) @ var phi: phase of the input laser pulse @ var c_op_list: list of collapse operators for the master equation treatment @ var return_op_list: list of population operators the values of which will be returned returns: time, populations of motional mode and atom ''' N = shape(rho0.data)[0]/2 # assume N Fock states and two atom states a = tensor(destroy(N), qeye(2)) sm = tensor( qeye(N), destroy(2)) Wrsb = destroy(N) one_then_zero = ([float(x<1) for x in range(N)]) Wrsb.data = csr_matrix( destroy(N).data.dot( np.diag( rabi_coupling(N,-1,eta) / np.sqrt(one_then_zero+np.linspace(0,N-1,N)) ) ) ) Arsb = tensor(Wrsb, qeye(2)) # use the rotating wave approxiation # Note that the regular a, a.dag() is used for the time evolution of the oscillator # Arsb is the destruction operator including the state dependent coupling strength H = delta * a.dag() * a + \ (1./2.) * W * (Arsb.dag() * sm * exp(1j*phi) + Arsb * sm.dag() * exp(-1j*phi)) if hasattr(theta, '__len__'): if len(theta)>1: # I need to be able to pass a list of length zero and not get an error time = theta/(eta*W) else: time = theta/(eta*W) output = mesolve(H, rho0, time, c_op_list, return_op_list) return time, output
def test_spectrum_espi(): """ correlation: comparing spectrum from es and pi methods """ # use JC model N = 4 wc = wa = 1.0 * 2 * np.pi g = 0.1 * 2 * np.pi kappa = 0.75 gamma = 0.25 n_th = 0.01 a = tensor(destroy(N), qeye(2)) sm = tensor(qeye(N), destroy(2)) H = wc * a.dag() * a + wa * sm.dag() * sm + \ g * (a.dag() * sm + a * sm.dag()) c_ops = [np.sqrt(kappa * (1 + n_th)) * a, np.sqrt(kappa * n_th) * a.dag(), np.sqrt(gamma) * sm] wlist = 2 * pi * np.linspace(0.5, 1.5, 100) spec1 = spectrum(H, wlist, c_ops, a.dag(), a, solver='es') spec2 = spectrum(H, wlist, c_ops, a.dag(), a, solver='pi') assert_(max(abs(spec1 - spec2)) < 1e-3)
def test_spectrum_espi_legacy(): """ correlation: legacy spectrum from es and pi methods """ # use JC model N = 4 wc = wa = 1.0 * 2 * np.pi g = 0.1 * 2 * np.pi kappa = 0.75 gamma = 0.25 n_th = 0.01 a = tensor(destroy(N), qeye(2)) sm = tensor(qeye(N), destroy(2)) H = wc * a.dag() * a + wa * sm.dag() * sm + \ g * (a.dag() * sm + a * sm.dag()) c_ops = [np.sqrt(kappa * (1 + n_th)) * a, np.sqrt(kappa * n_th) * a.dag(), np.sqrt(gamma) * sm] wlist = 2 * np.pi * np.linspace(0.5, 1.5, 100) with warnings.catch_warnings(): warnings.simplefilter("ignore") spec1 = spectrum_ss(H, wlist, c_ops, a.dag(), a) spec2 = spectrum_pi(H, wlist, c_ops, a.dag(), a) assert_(max(abs(spec1 - spec2)) < 1e-3)
def test_mc_dtypes2(): "Monte-carlo: check for correct dtypes (average_states=False)" # set system parameters kappa = 2.0 # mirror coupling gamma = 0.2 # spontaneous emission rate g = 1 # atom/cavity coupling strength wc = 0 # cavity frequency w0 = 0 # atom frequency wl = 0 # driving frequency E = 0.5 # driving amplitude N = 5 # number of cavity energy levels (0->3 Fock states) tlist = np.linspace(0, 10, 5) # times for expectation values # construct Hamiltonian ida = qeye(N) idatom = qeye(2) a = tensor(destroy(N), idatom) sm = tensor(ida, sigmam()) H = (w0 - wl) * sm.dag() * sm + (wc - wl) * a.dag() * a + \ 1j * g * (a.dag() * sm - sm.dag() * a) + E * (a.dag() + a) # collapse operators C1 = np.sqrt(2 * kappa) * a C2 = np.sqrt(gamma) * sm C1dC1 = C1.dag() * C1 C2dC2 = C2.dag() * C2 # intial state psi0 = tensor(basis(N, 0), basis(2, 1)) opts = Options(average_expect=False) data = mcsolve( H, psi0, tlist, [C1, C2], [C1dC1, C2dC2, a], ntraj=5, options=opts) assert_equal(isinstance(data.expect[0][0][1], float), True) assert_equal(isinstance(data.expect[0][1][1], float), True) assert_equal(isinstance(data.expect[0][2][1], complex), True)
def collapse_operators(N, n_th_a, gamma_motion, gamma_motion_phi, gamma_atom): '''Collapse operators for the master equation of a single atom and a harmonic oscillator @ var N: size of the harmonic oscillator Hilbert space @ var n_th: temperature of the noise bath in quanta @ var gamma_motion: heating rate of the motion @ var gamma_motion_phi: dephasing rate of the motion @ var gamma_atom: decay rate of the atom returns: list of collapse operators for master equation solution of atom + harmonic oscillator ''' a = tensor(destroy(N), qeye(2)) sm = tensor(qeye(N), destroy(2)) c_op_list = [] rate = gamma_motion * (1 + n_th_a) if rate > 0.0: c_op_list.append(sqrt(rate) * a) rate = gamma_motion * n_th_a if rate > 0.0: c_op_list.append(sqrt(rate) * a.dag()) rate = gamma_motion_phi if rate > 0.0: c_op_list.append(sqrt(rate) * a.dag() * a) rate = gamma_atom if rate > 0.0: c_op_list.append(sqrt(rate) * sm) return c_op_list
def compute(N, wc, wa, glist, use_rwa): # Pre-compute operators for the hamiltonian a = tensor(destroy(N), qeye(2)) sm = tensor(qeye(N), destroy(2)) nc = a.dag() * a na = sm.dag() * sm idx = 0 na_expt = zeros(shape(glist)) nc_expt = zeros(shape(glist)) for g in glist: # recalculate the hamiltonian for each value of g if use_rwa: H = wc * nc + wa * na + g * (a.dag() * sm + a * sm.dag()) else: H = wc * nc + wa * na + g * (a.dag() + a) * (sm + sm.dag()) # find the groundstate of the composite system evals, ekets = H.eigenstates() psi_gnd = ekets[0] na_expt[idx] = expect(na, psi_gnd) nc_expt[idx] = expect(nc, psi_gnd) idx += 1 return nc_expt, na_expt, ket2dm(psi_gnd)
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 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 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 carrier_flop(rho0, W, eta, delta, theta, phi, c_op_list = [], return_op_list = []): ''' Return values of atom and motion populations during carrier Rabi flop for rotation angles theta. Calls numerical solution of master equation. @ var rho0: initial density matrix @ var W: bare Rabi frequency @ var eta: Lamb-Dicke parameter @ var delta: detuning between atom and motion @ var theta: list of Rabi rotation angles (i.e. theta, or g*time) @ var phi: phase of the input laser pulse @ var c_op_list: list of collapse operators for the master equation treatment @ var return_op_list: list of population operators the values of which will be returned returns: time, populations of motional mode and atom ''' N = shape(rho0.data)[0]/2 # assume N Fock states and two atom states a = tensor(destroy(N), qeye(2)) Wc = qeye(N) Wc.data = csr_matrix( qeye(N).data.dot( np.diag(rabi_coupling(N,0,eta) ) ) ) sm = tensor( Wc, destroy(2)) # use the rotating wave approxiation H = delta * a.dag() * a + \ (1./2.)* W * (sm.dag()*exp(1j*phi) + sm*exp(-1j*phi)) if hasattr(theta, '__len__'): if len(theta)>1: # I need to be able to pass a list of length zero and not get an error time = theta/W else: time = theta/W output = mesolve(H, rho0, time, c_op_list, return_op_list) return time, output
def __init__(self): N = 3 self.t1 = QobjEvo([qeye(N)*(1.+0.1j),[create(N)*(1.-0.1j),f]]) self.t2 = QobjEvo([destroy(N)*(1.-0.2j)]) self.t3 = QobjEvo([[destroy(N)*create(N)*(1.+0.2j),f]]) self.q1 = qeye(N)*(1.+0.3j) self.q2 = destroy(N)*(1.-0.3j) self.q3 = destroy(N)*create(N)*(1.+0.4j)
def population_operators(N): '''Population operators for the master equation @ var N: size of the oscillator Hilbert space returns: list of population operators for the harmonic oscillator and the atom ''' a = tensor(destroy(N), qeye(2)) sm = tensor( qeye(N), destroy(2)) return [a.dag()*a, sm.dag()*sm]
def full_approx(cav_dim, w_1, w_2, w_c, g_factor): a = qt.destroy(cav_dim) num = a.dag() * a return ( g_factor * qt.tensor(qt.qeye(cav_dim), SMinus, SPlus) + g_factor * qt.tensor(qt.qeye(cav_dim), SPlus, SMinus) + w_c * qt.tensor(num, I, I) + 0.5 * w_1 * qt.tensor(qt.qeye(cav_dim), SZ, I) + 0.5 * w_2 * qt.tensor(qt.qeye(cav_dim), I, SZ))
def relaxation(rate, dims, qubit=1): qubit_indices,cav_index = parse_dims(dims) if cav_index is not None: cav_dim = dims[cav_index] ops = [0]*len(dims) ops[cav_index] = qt.qeye(cav_dim) ops[qubit_indices[qubit-1]] = SMinus else: ops = [0,0] ops[qubit-1] = SMinus ops = [qt.qeye(2) if op == 0 else op for op in ops] return np.sqrt(rate) * qt.tensor(ops)
def find_projectors(generating_sets): n_qubits = len(generating_sets[0]) Id= qeye(pow(2, n_qubits)) dims = [[2]*n_qubits, [2]*n_qubits] Id.dims = dims projectors = [] for genset in generating_sets: res = qeye(pow(2, n_qubits)) res.dims = dims for g in genset: res *= (Id+g)/2 projectors.append(res) return projectors
def full_hamiltonian(cav_dim, w_1, w_2, w_c, g_1, g_2): """Return a QObj denoting the full Hamiltonian including cavity and two qubits""" a = qt.destroy(cav_dim) num = a.dag() * a return ( g_1 * qt.tensor(qt.create(cav_dim), SMinus, I) + g_1 * qt.tensor(qt.destroy(cav_dim), SPlus, I) + g_2 * qt.tensor(qt.create(cav_dim), I, SMinus) + g_2 * qt.tensor(qt.destroy(cav_dim), I, SPlus) + w_c * qt.tensor(num, I, I) + 0.5 * w_1 * qt.tensor(qt.qeye(cav_dim), SZ, I) + 0.5 * w_2 * qt.tensor(qt.qeye(cav_dim), I, SZ))
def compute_multiqubit_hamil(template, nb_qubits, index_template, dim_I=2): """ Compute a Hamiltonian of the form IxIx...xHxIx...xI, where there in total nb_qubits elements in the tensor product, and the index of the one that is not I is given by index_template. """ if index_template == 0: H = template else: H = qt.qeye(dim_I) for i in range(1, nb_qubits): if i == index_template: H = qt.tensor(H, template) else: H = qt.tensor(H, qt.qeye(dim_I)) return np.array(list(H))[:, 0]
def __init__(self, fiducial_distribution, mean): super(GADFLIDistribution, self).__init__(fiducial_distribution.basis) self._fid = fiducial_distribution mean = ( qt.to_choi(mean).unit() if mean.type == 'super' and not mean.superrep == 'choi' else mean ) self._mean = mean alpha = 1 lambda_min = min(mean.eigenenergies()) if lambda_min < 0: raise ValueError("Negative eigenvalue {} in informative mean.".format(lambda_min)) d = self.dim beta = ( 1 / (d * lambda_min - 1) - 1 ) if lambda_min > 0.5 else ( (d * lambda_min) / (1 - d * lambda_min) ) if beta < 0: raise ValueError("Beta < 0 for informative mean.") self._alpha = alpha self._beta = beta eye = qt.qeye(self._dim).unit() eye.dims = mean.dims self._rho_star = (alpha + beta) / alpha * ( mean - (beta) / (alpha + beta) * eye.unit() )
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_rand_unitary(func): """ Random Qobjs: Tests that unitaries are actually unitary. """ random_qobj = func(5) I = qeye(5) assert random_qobj * random_qobj.dag() == I
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 __init__(self, H_S, L1, L2, S_matrix=None, c_ops_markov=None, options=None): if options is None: self.options = qt.Options() else: self.options = options self.H_S = H_S self.sysdims = H_S.dims if isinstance(L1, qt.Qobj): self.L1 = [L1] else: self.L1 = L1 if isinstance(L2, qt.Qobj): self.L2 = [L2] else: self.L2 = L2 if not len(self.L1) == len(self.L2): raise ValueError('L1 and L2 has to be of equal length.') if isinstance(c_ops_markov, qt.Qobj): self.c_ops_markov = [c_ops_markov] else: self.c_ops_markov = c_ops_markov if S_matrix is None: self.S_matrix = np.identity(len(self.L1)) else: self.S_matrix = S_matrix # create system identity superoperator self.Id = qt.qeye(H_S.shape[0]) self.Id.dims = self.sysdims self.Id = qt.sprepost(self.Id, self.Id) self.store_states = self.options.store_states
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 compute_multiqubit_target_unitary(angles, axes): """ Computes the target unitary of the operation that rotates qubit i by the angle defined by the i-th element of angles, around the axis defined by the i-th element of axes. Parameters ---------- angles: array containing the values of the rotation angle of each qubit axes : array of tuples defining the rotation axes of the rotation of each qubit. Each rotation axis is defined using thecartesian X, Y and Z axes (e.g. the X and Z axis are represented by (1,0,0) and (0,0,1) respectively) Returns ------- target: unitary matrix (numpy array) taht represented the ideal operation """ target = qt.qeye(2) i_qubit = 0 for angle in angles: tmp = compute_single_qubit_target_unitary(angle, axes[i_qubit]) # if target == qt.qeye(2): if i_qubit == 0: target = qt.Qobj(tmp) else: target = qt.tensor(target, qt.Qobj(tmp)) i_qubit += 1 return target
def adc_choi(x): kraus = [ np.sqrt(1 - x) * qeye(2), np.sqrt(x) * destroy(2), np.sqrt(x) * fock_dm(2, 0), ] return kraus_to_choi(kraus)
def single_hamiltonian(cav_dim, w_1, w_c, g_factor): """Return a QObj denoting a hamiltonian for one qubit coupled to a cavity.""" return (w_c * qt.tensor(qt.num(cav_dim), I) + 0.5 * w_1 * qt.tensor(qt.qeye(cav_dim), I) + g_factor * qt.tensor(qt.create(cav_dim), SMinus) + g_factor * qt.tensor(qt.destroy(cav_dim), SPlus))
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 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 test_rand_unitary_haar_unitarity(): """ Random Qobjs: Tests that unitaries are actually unitary. """ U = rand_unitary_haar(5) I = qeye(5) assert U * U.dag() == I
def do_anneal(**kwargs): beta = kwargs.pop('beta_init', 1) beta_max = kwargs.pop('beta_max', 4000) anneal_steps = kwargs.pop('M', 1000) b_diff = (beta_max-beta)/anneal_steps walk_steps = kwargs.pop('steps', 100) n_qubits = kwargs.pop('n_qubits') target = kwargs.pop('target') chi = kwargs.pop('chi') states = gen_random_stabilisers(n_qubits, chi) identity = qeye(pow(2,n_qubits)) identity.dims = [[2]*n_qubits, [2]*n_qubits] while beta <= beta_max: for i in range(walk_steps): projector = OrthoProjector([s.full() for s in states]) projection = np.linalg.norm(projector*target.full(), 2) if np.allclose(projection, 1.): return success_string.format(chi=chi, states=states) a = randrange(0,len(states)) p_string = bin(randrange(0,pow(2,2*n_qubits)))[2:] p_bits = bitarray(2*n_qubits - len(p_string)) p_bits.extend(p_string) pauli = string_to_pauli(p_bits) new_states = deepcopy(states) new_states[a] = ((identity + pauli).unit() * states[a]) new_proj = OrthoProjector([s.full() for s in new_states]) new_projection = np.linalg.norm(new_proj*target.full(), 2) if new_projection > projection: states = new_states else: p_accept = exp(-beta * (projection-new_projection)) if random() > p_accept: states = new_states beta += b_diff return 'No decomposition found for chi={}\n'.format(chi)
def setUp(self): TestRotatingFrame.setUp(self) self.times_to_calc = np.array([0, np.pi/2]) self.expected_result =np.array( np.cos(self.frequency * self.times_to_calc) * q.qeye(2) + \ 1j* np.sin(self.frequency * self.times_to_calc) * q.sigmay() )
def get_M0(H,lindblads,tau): _dims = H.dims[0] J = qt.Qobj(np.zeros_like(H.data.todense()),dims=[_dims,_dims]) for Op in lindblads: J += Op.dag()*Op J *= 0.5 return qt.tensor([qt.qeye(dim) for dim in _dims]) - tau*(1j*H - J)
def make_target(nf, nq, ptype, n_bit, n_bits): id_list = lambda: [qutip.qeye(2) for _ in range(n_bits + 1)] x_ops = [id_list() for _ in range(n_bits)] z_ops = [id_list() for _ in range(n_bits)] h_ops = [id_list() for _ in range(n_bits)] ih_ops = [id_list() for _ in range(n_bits)] cx_ops = [] m_cz_ops = [] m_cx_ops = [] m_cy_ops = [] for i in range(n_bits): z_ops[i][i + 1] = qutip.sigmaz() x_ops[i][i + 1] = qutip.sigmax() h_ops[i][i + 1] = qutip.hadamard_transform() ih_ops[i][i + 1] = qutip.Qobj([[-1, 1], [-1j, -1j]]) / sqrt(2) z_ops[i] = qutip.tensor(*z_ops[i]) x_ops[i] = qutip.tensor(*x_ops[i]) h_ops[i] = qutip.tensor(*h_ops[i]) ih_ops[i] = qutip.tensor(*ih_ops[i]) cx_ops.append( qutip.controlled_gate(qutip.hadamard_transform(), n_bits + 1, i + 1, 0)) m_cz_ops.append( qutip.controlled_gate(qutip.sigmax(), n_bits + 1, i + 1, 0)) m_cx_ops.append(h_ops[i] * m_cz_ops[i] * h_ops[i]) m_cy_ops.append(ih_ops[i] * m_cz_ops[i] * ih_ops[i]) for ops in (x_ops, z_ops, h_ops, m_cz_ops, m_cx_ops, m_cy_ops): ops.reverse() bits_n = 2**n_bits flip_target = id_list() flip_target[0] = qutip.sigmax() flip_target = qutip.tensor(*flip_target) if ptype == 'i': targ = qutip.tensor(*id_list()) elif ptype == 'mz': targ = m_cz_ops[n_bit - 1] * flip_target elif ptype == 'mx': targ = m_cx_ops[n_bit - 1] elif ptype == 'my': targ = m_cy_ops[n_bit - 1] elif ptype == 'x': targ = x_ops[n_bit - 1] elif ptype == 'z': targ = z_ops[n_bit - 1] U = np.zeros((nq * nf, nq * nf), dtype=np.complex) U[:bits_n, :bits_n] = targ[:bits_n, :bits_n] U[nf:nf + bits_n, :bits_n] = targ[bits_n:, :bits_n] U[:bits_n, nf:nf + bits_n] = targ[:bits_n, bits_n:] U[nf:nf + bits_n, nf:nf + bits_n] = targ[bits_n:, bits_n:] mask_c = np.zeros(nf) mask_c[:bits_n] = 1 mask_q = np.zeros(nq) mask_q[:2] = 1 mask = np.kron(mask_q, mask_c) mask = np.arange(len(mask))[mask == 1] return U, mask
class Test_fidelity: def test_mixed_state_inequality(self, dimension): tol = 1e-7 rho1 = rand_dm(dimension, 0.25) rho2 = rand_dm(dimension, 0.25) F = fidelity(rho1, rho2) assert 1 - F <= np.sqrt(1 - F * F) + tol @pytest.mark.parametrize('right_dm', [True, False], ids=['mixed', 'pure']) @pytest.mark.parametrize('left_dm', [True, False], ids=['mixed', 'pure']) def test_orthogonal(self, left_dm, right_dm, dimension): left = basis(dimension, 0) right = basis(dimension, dimension // 2) if left_dm: left = left.proj() if right_dm: right = right.proj() assert fidelity(left, right) == pytest.approx(0, abs=1e-6) def test_invariant_under_unitary_transformation(self, dimension): rho1 = rand_dm(dimension, 0.25) rho2 = rand_dm(dimension, 0.25) U = rand_unitary(dimension, 0.25) F = fidelity(rho1, rho2) FU = fidelity(U * rho1 * U.dag(), U * rho2 * U.dag()) assert F == pytest.approx(FU, rel=1e-5) def test_state_with_itself(self, state): assert fidelity(state, state) == pytest.approx(1, abs=1e-6) def test_bounded(self, left, right, dimension): """Test that fidelity is bounded on [0, 1].""" tol = 1e-7 assert -tol <= fidelity(left, right) <= 1 + tol def test_pure_state_equivalent_to_overlap(self, dimension): """Check fidelity against pure-state overlap, see gh-361.""" psi = rand_ket_haar(dimension) phi = rand_ket_haar(dimension) overlap = np.abs(psi.overlap(phi)) assert fidelity(psi, phi) == pytest.approx(overlap, abs=1e-7) ket_0 = basis(2, 0) ket_1 = basis(2, 1) ket_p = (ket_0 + ket_1).unit() ket_py = (ket_0 + np.exp(0.25j * np.pi) * ket_1).unit() max_mixed = qeye(2).unit() @pytest.mark.parametrize(['left', 'right', 'expected'], [ pytest.param(ket_0, ket_p, np.sqrt(0.5), id="|0>,|+>"), pytest.param(ket_0, ket_1, 0, id="|0>,|1>"), pytest.param(ket_0, max_mixed, np.sqrt(0.5), id="|0>,id/2"), pytest.param(ket_p, ket_py, np.sqrt(0.125 + (0.5 + np.sqrt(0.125))**2), id="|+>,|+'>"), ]) def test_known_cases(self, left, right, expected): assert fidelity(left, right) == pytest.approx(expected, abs=1e-7)
def test1(): U0 = np.array(qeye(2).full()) sx = np.array(sigmax().full()) def Ht(t): return sx T = np.pi U = getUnitary(U0, Ht, T) print(U)
def __init__(self, dim): self.dim = dim self.a = qutip.destroy(dim) self.adag = qutip.create(dim) self.x = (self.a + self.adag) / np.sqrt(2) self.p = -1.j * (self.a - self.adag) / np.sqrt(2) self.H = qutip.num(dim) self.id = qutip.qeye(dim)
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_decoherence_noise(self): """ Test for the decoherence noise """ tlist = np.array([0, 1, 2, 3, 4, 5, 6]) coeff = np.array([1, 1, 1, 1, 1, 1, 1]) # Time-dependent decnoise = DecoherenceNoise(sigmaz(), coeff=coeff, tlist=tlist, targets=[1]) dims = [2] * 2 systematic_noise = Pulse(None, None, label="systematic_noise", spline_kind="step_func") pulses, systematic_noise = decnoise.get_noisy_pulses( systematic_noise=systematic_noise, dims=dims) noisy_qu, c_ops = systematic_noise.get_noisy_qobjevo(dims=dims) assert_allclose(c_ops[0](0).full(), tensor(qeye(2), sigmaz()).full()) # Time-independent and all qubits decnoise = DecoherenceNoise(sigmax(), all_qubits=True) pulses, systematic_noise = decnoise.get_noisy_pulses(dims=dims) noisy_qu, c_ops = systematic_noise.get_noisy_qobjevo(dims=dims) c_ops = [qu(0) for qu in c_ops] assert_(tensor([qeye(2), sigmax()]) in c_ops) assert_(tensor([sigmax(), qeye(2)]) in c_ops) # Time-denpendent and all qubits decnoise = DecoherenceNoise(sigmax(), all_qubits=True, coeff=coeff * 2, tlist=tlist) systematic_noise = Pulse(None, None, label="systematic_noise", spline_kind="step_func") pulses, systematic_noise = decnoise.get_noisy_pulses( systematic_noise=systematic_noise, dims=dims) noisy_qu, c_ops = systematic_noise.get_noisy_qobjevo(dims=dims) assert_allclose(c_ops[0](0).full(), tensor(sigmax(), qeye(2)).full() * 2) assert_allclose(c_ops[1](0).full(), tensor(qeye(2), sigmax()).full() * 2)
def __init__(self, dim, spacing=5, indices=None, max_alpha=3.5, n_pts=100): super(plot_cwigs, self).__init__(spacing) xs = np.linspace(-3.5, 3.5, 100) X, Y = np.meshgrid(xs, xs) disps = (X + 1j*Y).flatten() self.dim = dim self.n_pts = n_pts self.M = wigner_mat(disps, dim) self.paulis = [ qutip.qeye(2), qutip.sigmax(), qutip.sigmay(), qutip.sigmaz() ] self.paulis = [qutip.tensor(p, qutip.qeye(dim)).full() for p in self.paulis] self.indices = indices if indices is None: self.indices = slice(None, None) self.fig = None self.grid = None
def test_set_unset_stats(): # Arbitrary system, just checking that stats can be unset by `configure` args = [qutip.qeye(2), qutip.sigmaz(), 0.1, 0.1, 10, 1, 0.1] hsolver = HSolverDL(*args, stats=True) hsolver.run(qutip.basis(2, 0).proj(), [0, 1]) assert hsolver.stats is not None hsolver.configure(*args, stats=False) assert hsolver.stats is None
def __init__(self, f1, f2): self.f_qubit1 = f1 self.f_qubit2 = f2 # define hamiltonian for two qubits (zeeman on qubit 1, zeeman on qubit 2, exchange between qubits) -- convert from qutip to numpy (brackets) self.B1 = qt.tensor(qt.sigmaz() / 2, qt.qeye(2))[:, :] self.B2 = qt.tensor(qt.qeye(2), qt.sigmaz() / 2)[:, :] self.J = (qt.tensor(qt.sigmax(), qt.sigmax()) + qt.tensor(qt.sigmay(), qt.sigmay()) + qt.tensor(qt.sigmaz(), qt.sigmaz()))[:, :] / 4 self.my_Hamiltonian = 2 * np.pi * (f1 * self.B1 + f2 * self.B2) # Create the solver self.solver_obj = ME.VonNeumann(4) # Add the init hamiltonian self.solver_obj.add_H0(self.my_Hamiltonian)
def __init__(self, init_state, target_state, num_focks, num_steps, alpha_list=[1]): self.init_state = init_state self.target_state = target_state self.num_focks = num_focks Sp = tensor(sigmap(), qeye(num_focks)) Sm = tensor(sigmam(), qeye(num_focks)) a = tensor(qeye(2), destroy(num_focks)) adag = tensor(qeye(2), create(num_focks)) # Control Hamiltonians self._ctrl_hamils = [Sp + Sm, Sp * a + Sm * adag, Sp * adag + Sm * a, 1j * (Sp - Sm), 1j * (Sp * a - Sm * adag), 1j * (Sp * adag - Sm * a)] # Number operator self._adaga = adag * a self.num_steps = num_steps self.alpha_list = np.array(alpha_list + [0] * (3 - len(alpha_list)))
def _set_paulix(self): if self.paulix is None: self.paulix = [ tensor([ sigmax() if i == j else qeye(2) for j in range(self.num_spins) ]) for i in range(self.num_spins) ]
def project_ancillae(net, ancillae_state): """Project the ancillae over the specified state.""" gate = net.get_current_gate(return_qobj=True) ancillae_proj = qutip.ket2dm(ancillae_state) identity_over_system = qutip.tensor( [qutip.qeye(2) for _ in range(net.num_system_qubits)]) proj = qutip.tensor(identity_over_system, ancillae_proj) return proj * gate * proj
def _cavity(self, cavity): N = cavity.N self.Ic = qu.qeye(N) # astates = [qu.tensor(astate,qu.qeye(N)) for astate in self.astates] # self.astates = astates for key in self.projectors.keys(): self.projectors[key] = [ qu.tensor(proj, qu.qeye(N)) for proj in self.projectors[key] ] for key in self.Aops.keys(): self.Aops[key] = [ qu.tensor(Aop, qu.qeye(N)) for Aop in self.Aops[key] ] # cstates = [qu.tensor(qu.qeye(self.Nat),cstate) for cstate in cavity.states] # self.cstates=cstates self.a = qu.tensor(self.Iat, qu.destroy(N)) self.ad = self.a.dag()
def test_graph_rcm_qutip(): "Graph: Reverse Cuthill-McKee Ordering (qutip)" kappa = 1 gamma = 0.01 g = 1 wc = w0 = wl = 0 N = 2 E = 1.5 a = tensor(destroy(N), qeye(2)) sm = tensor(qeye(N), sigmam()) H = (w0-wl)*sm.dag( )*sm+(wc-wl)*a.dag()*a+1j*g*(a.dag()*sm-sm.dag()*a)+E*(a.dag()+a) c_ops = [np.sqrt(2*kappa)*a, np.sqrt(gamma)*sm] L = liouvillian(H, c_ops) perm = reverse_cuthill_mckee(L.data) ans = np.array([12, 14, 4, 6, 10, 8, 2, 15, 0, 13, 7, 5, 9, 11, 1, 3]) assert_equal(perm, ans)
def test_expectation_dtype(options): # We're just testing the output value, so it's important whether certain # things are complex or real, but not what the magnitudes of constants are. focks = 5 a = qutip.tensor(qutip.destroy(focks), qutip.qeye(2)) sm = qutip.tensor(qutip.qeye(focks), qutip.sigmam()) H = 1j*a.dag()*sm + a H = H + H.dag() state = qutip.basis([focks, 2], [0, 1]) times = np.linspace(0, 10, 5) c_ops = [a, sm] e_ops = [a.dag()*a, sm.dag()*sm, a] data = qutip.mcsolve(H, state, times, c_ops, e_ops, ntraj=5, options=options) assert isinstance(data.expect[0][1], float) assert isinstance(data.expect[1][1], float) assert isinstance(data.expect[2][1], complex)
def testMETDDecayAsArray(self): "mesolve: time-dependence as array with super as init cond" me_error = 1e-5 N = 10 a = destroy(N) H = a.dag() * a psi0 = basis(N, 9) rho0vec = operator_to_vector(psi0 * psi0.dag()) E0 = sprepost(qeye(N), qeye(N)) kappa = 0.2 tlist = np.linspace(0, 10, 1000) c_op_list = [[a, np.sqrt(kappa * np.exp(-tlist))]] out1 = mesolve(H, psi0, tlist, c_op_list, []) out2 = mesolve(H, E0, tlist, c_op_list, []) fid = self.fidelitycheck(out1, out2, rho0vec) assert_(max(abs(1.0 - fid)) < me_error, True)
def _convert_superoperator_to_qutip(expr, full_space, mapping): if full_space != expr.space: all_spaces = full_space.local_factors own_space_index = all_spaces.index(expr.space) return qutip.tensor( *([qutip.qeye(s.dimension) for s in all_spaces[:own_space_index]] + convert_to_qutip(expr, expr.space, mapping=mapping) + [ qutip.qeye(s.dimension) for s in all_spaces[own_space_index + 1:] ])) if isinstance(expr, IdentitySuperOperator): return qutip.spre( qutip.tensor( *[qutip.qeye(s.dimension) for s in full_space.local_factors])) elif isinstance(expr, SuperOperatorPlus): return sum( (convert_to_qutip(op, full_space, mapping=mapping) for op in expr.operands), 0, ) elif isinstance(expr, SuperOperatorTimes): ops_qutip = [ convert_to_qutip(o, full_space, mapping=mapping) for o in expr.operands ] return reduce(lambda a, b: a * b, ops_qutip, 1) elif isinstance(expr, ScalarTimesSuperOperator): return complex(expr.coeff) * convert_to_qutip( expr.term, full_space, mapping=mapping) elif isinstance(expr, SPre): return qutip.spre( convert_to_qutip(expr.operands[0], full_space, mapping)) elif isinstance(expr, SPost): return qutip.spost( convert_to_qutip(expr.operands[0], full_space, mapping)) elif isinstance(expr, SuperOperatorTimesOperator): sop, op = expr.operands return convert_to_qutip(sop, full_space, mapping=mapping) * convert_to_qutip( op, full_space, mapping=mapping) elif isinstance(expr, ZeroSuperOperator): return qutip.spre( convert_to_qutip(ZeroOperator, full_space, mapping=mapping)) else: raise ValueError("Cannot convert '%s' of type %s" % (str(expr), type(expr)))
def _convert_local_operator_to_qutip(expr, full_space, mapping): """Convert a LocalOperator instance to qutip.""" n = full_space.dimension if full_space != expr.space: all_spaces = full_space.local_factors own_space_index = all_spaces.index(expr.space) return qutip.tensor( *([qutip.qeye(s.dimension) for s in all_spaces[:own_space_index]] + [convert_to_qutip(expr, expr.space, mapping=mapping)] + [ qutip.qeye(s.dimension) for s in all_spaces[own_space_index + 1:] ])) if isinstance(expr, Create): return qutip.create(n) elif isinstance(expr, Jz): return qutip.jmat((expr.space.dimension - 1) / 2.0, "z") elif isinstance(expr, Jplus): return qutip.jmat((expr.space.dimension - 1) / 2.0, "+") elif isinstance(expr, Jminus): return qutip.jmat((expr.space.dimension - 1) / 2.0, "-") elif isinstance(expr, Destroy): return qutip.destroy(n) elif isinstance(expr, Phase): arg = complex(expr.operands[1]) * arange(n) d = np_cos(arg) + 1j * np_sin(arg) return qutip.Qobj(np_diag(d)) elif isinstance(expr, Displace): alpha = expr.operands[1] return qutip.displace(n, alpha) elif isinstance(expr, Squeeze): eta = expr.operands[1] return qutip.displace(n, eta) elif isinstance(expr, LocalSigma): j = expr.j k = expr.k if isinstance(j, str): j = expr.space.basis_labels.index(j) if isinstance(k, str): k = expr.space.basis_labels.index(k) ket = qutip.basis(n, j) bra = qutip.basis(n, k).dag() return ket * bra else: raise ValueError("Cannot convert '%s' of type %s" % (str(expr), type(expr)))
def test_operator_at_cells(self): p_2222 = qutip.Lattice1d(num_cell=2, boundary="periodic", cell_num_site=2, cell_site_dof=[2, 2]) op_0 = qutip.projection(2, 0, 1) op_c = qutip.tensor(op_0, qutip.qeye([2, 2])) OP = p_2222.operator_between_cells(op_c, 1, 0) T = qutip.projection(2, 1, 0) QP = qutip.tensor(T, op_c) assert OP == QP
def test_distribute_operator(self): lattice_412 = qutip.Lattice1d(num_cell=4, boundary="periodic", cell_num_site=1, cell_site_dof=[2]) op = qutip.Qobj(np.array([[0, 1], [1, 0]])) op_all = lattice_412.distribute_operator(op) sv_op_all = qutip.tensor(qutip.qeye(4), qutip.sigmax()) assert op_all == sv_op_all
def __init__(self, f1, f2): self.f_qubit1 = f1 self.f_qubit2 = f2 self.H_mw_qubit_1 = np.array(list(basis(4,0)*basis(4,2).dag() + basis(4,1)*basis(4,3).dag()))[:,0] self.H_mw_qubit_2 = np.array(list(basis(4,0)*basis(4,1).dag() + basis(4,2)*basis(4,3).dag()))[:,0] # define hamiltonian for two qubits (zeeman on qubit 1, zeeman on qubit 2, exchange between qubits) -- convert from qutip to numpy (brackets) self.B1 = qt.tensor(qt.sigmaz()/2, qt.qeye(2))[:,:] self.B2 = qt.tensor(qt.qeye(2), qt.sigmaz()/2)[:,:] # transformed into rotating frame, so energy is 0 self.my_Hamiltonian = 0*self.B1 # Create the solver self.solver_obj = ME.VonNeumann(4) # Add the init hamiltonian self.solver_obj.add_H0(self.my_Hamiltonian)
def _get_probabilities_measurement(self, rho, N_ghz): # Compute the probabilites of getting a even or a odd measurement result # Size of the state that is not the GHZ N = len(rho.dims[0]) - N_ghz # Get the sum of ven and odd projectors P_even = proj.even_projectors(N_ghz) P_odd = proj.odd_projectors(N_ghz) # Tensor with corresponding identity # Remember GHZ state is at the end of the state if N != 0: P_even = qt.tensor(qt.qeye([2]*N), P_even) P_odd = qt.tensor(qt.qeye([2]*N), P_odd) # Compute probabilites p_even = (P_even * rho * P_even.dag()).tr() p_odd = (P_odd * rho * P_odd.dag()).tr() return [p_even, p_odd]
def pauli(spin=0.5): '''Define pauli spin matrices''' ## Spin 1/2 if spin == 0.5: identity = qutip.qeye(2) sx = qutip.sigmax() / 2 sy = qutip.sigmay() / 2 sz = qutip.sigmaz() / 2 ## Spin 1 if spin == 1: identity = qutip.qeye(3) sx = qutip.jmat(1, 'x') sy = qutip.jmat(1, 'y') sz = qutip.jmat(1, 'z') return identity, sx, sy, sz
def eye(self): """Identity operator in the qubit eigenbasis. Returns ------- :class:`qutip.Qobj` The identity operator. """ return qt.qeye(self.nlev)
def step_op(n_steps, theta, xi): space_dims = n_steps + 1 shift_left = qutip.qeye(space_dims) shift_right = np.zeros((space_dims, space_dims)) for idx in range(len(shift_right) - 1): shift_right[idx + 1, idx] = 1. shift_right = qutip.Qobj(shift_right) proj_uu = qutip.Qobj([[1., 0.], [0., 0.]]) proj_dd = qutip.Qobj([[0., 0.], [0., 1.]]) c_shift = (qutip.tensor(shift_left, proj_uu) + qutip.tensor(shift_right, proj_dd)) big_coin_op = qutip.tensor(qutip.qeye(space_dims), coin_op(theta, xi)) return c_shift * big_coin_op