def test_mcsolve_bad_e_ops(): H = qutip.sigmaz() c_ops = [qutip.sigmax()] psi0 = qutip.basis(2, 0) tlist = np.linspace(0, 20, 200) with pytest.raises(TypeError) as exc: qutip.mcsolve(H, psi0, tlist=tlist, c_ops=c_ops, e_ops=[qutip.qeye(3)])
def test_seeds_can_be_reused(self): args = (self.H, self.state, self.times) kwargs = {'c_ops': self.c_ops, 'ntraj': self.ntraj} first = qutip.mcsolve(*args, **kwargs) options = qutip.Options(seeds=first.seeds) second = qutip.mcsolve(*args, options=options, **kwargs) for first_t, second_t in zip(first.col_times, second.col_times): np.testing.assert_equal(first_t, second_t) for first_w, second_w in zip(first.col_which, second.col_which): np.testing.assert_equal(first_w, second_w)
def test_seeds_are_not_reused_by_default(self): args = (self.H, self.state, self.times) kwargs = {'c_ops': self.c_ops, 'ntraj': self.ntraj} first = qutip.mcsolve(*args, **kwargs) second = qutip.mcsolve(*args, **kwargs) assert not all( np.array_equal(first_t, second_t) for first_t, second_t in zip(first.col_times, second.col_times)) assert not all( np.array_equal(first_w, second_w) for first_w, second_w in zip(first.col_which, second.col_which))
def run(neq=10, ntraj=100, solver='both', ncpus=1): # sparse initial state # psi0 = basis(neq,neq-1) # dense initial state psi0 = qt.Qobj(np.ones((neq, 1))).unit() a = qt.destroy(neq) ad = a.dag() H = ad * a # c_ops = [gamma*a] c_ops = [qt.qeye(neq)] e_ops = [ad * a] # Times T = 10.0 dt = 0.1 nstep = int(T / dt) tlist = np.linspace(0, T, nstep) # set options opts = qt.Options() opts.num_cpus = ncpus opts.gui = False mcf90_time = 0. mc_time = 0. if (solver == 'mcf90' or solver == 'both'): start_time = time.time() mcf90.mcsolve_f90(H, psi0, tlist, c_ops, e_ops, ntraj=ntraj, options=opts) mcf90_time = time.time() - start_time print("mcsolve_f90 solutiton took", mcf90_time, "s") if (solver == 'mc' or solver == 'both'): start_time = time.time() qt.mcsolve(H, psi0, tlist, c_ops, e_ops, ntraj=ntraj, options=opts, progress_bar=False) mc_time = time.time() - start_time print("mcsolve solutiton took", mc_time, "s") return mcf90_time, mc_time
def solve(Data, ntraj): #run monte-carlo solver print "running Monte Carlo Solver..." raw = qt.mcsolve( Data.H, Data.psi0, Data.tlist, Data.slist, [], ntraj ) #This runs the solver with whichever collapse operators and hamiltonian are chosen Data.entire_raw = raw raw = raw.states Data.rawq = raw #Since the analysis always bogs down, and the raw.states data structure can be very large, #This will turn it into a numpy array rather than a qobj for purposes of speed. u = raw.shape rawarray = np.zeros([u[0], u[1]], dtype=np.ndarray) for i in range(u[0]): #Each Trajectory for j in range(u[1]): #Each Timestep rawij = raw[ i, j] #Calls the i,jth element of the state vector structure xary = np.zeros( [8, 1], dtype=complex) #Defines the new array for the state vectors for q in range(8): xary[q, 0] = rawij[q, 0] #Turns the qobj to a numpy array rawarray[i, j] = xary #Writes the element to the array Data.raw = rawarray #Removes the old data structure. return
def trajectory(self, exps=None, initial_state=None, draw=False): '''for convenience. Calculates the trajectory of an observable for one montecarlo run. Default expectation is cavity amplitude, default initial state is bipartite vacuum. todo: draw: draw trajectory on bloch sphere. Write in terms of mcsolve??''' if exps is None or draw is True: exps = [] if initial_state is None: initial_state = qt.tensor(qt.basis(self.N_field_levels, 0), qt.basis(2, 0)) self.one_traj_soln = qt.mcsolve(self.hamiltonian(), initial_state, self.tlist, self._c_ops(), exps, ntraj=1) if self.noisy: print(self.one_traj_soln.states[0][2].ptrace(1)) if not draw: return self.one_traj_soln else: self.b_sphere = qt.Bloch() self.b_sphere.add_states( [state.ptrace(1) for state in self.one_traj_soln.states[0]], 'point') self.b_sphere.point_markers = ['o'] self.b_sphere.size = (10, 10) self.b_sphere.show()
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 time_evolution_mc(psi, H, t, c_op): """ Monte-Carlo evolution in the case of a noisy system. Parameters ---------- psi: qutip.Qobj() quantum state under evolution H: qutip.Qobj() Hamiltonian t: scalar time during which H is applied to psi c_op: list single collapse operator or a list of collapse operators. Returns ------ psi2: qutip.Qobj() final state """ tlist = np.linspace(0, t, 50) psi2 = qutip.mcsolve(H, psi, tlist, c_ops=c_op, ntraj=100, progress_bar=None).states[0][-1] return psi2
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 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 test_states_and_expect(self, hamiltonian, args, c_ops, expected, tol): options = qutip.Options(average_states=True, store_states=True) result = qutip.mcsolve(hamiltonian, self.state, self.times, args=args, c_ops=c_ops, e_ops=self.e_ops, ntraj=self.ntraj, options=options) self._assert_expect(result, expected, tol) self._assert_states(result, expected, tol)
def test_mc_seed_noreuse(): "Monte-carlo: check not reusing seeds" N0 = 6 N1 = 6 N2 = 6 # damping rates gamma0 = 0.1 gamma1 = 0.4 gamma2 = 0.1 alpha = np.sqrt(2) # initial coherent state param for mode 0 tlist = np.linspace(0, 10, 2) ntraj = 500 # number of trajectories # define operators a0 = tensor(destroy(N0), qeye(N1), qeye(N2)) a1 = tensor(qeye(N0), destroy(N1), qeye(N2)) a2 = tensor(qeye(N0), qeye(N1), destroy(N2)) # number operators for each mode num0 = a0.dag() * a0 num1 = a1.dag() * a1 num2 = a2.dag() * a2 # dissipative operators for zero-temp. baths C0 = np.sqrt(2.0 * gamma0) * a0 C1 = np.sqrt(2.0 * gamma1) * a1 C2 = np.sqrt(2.0 * gamma2) * a2 # initial state: coherent mode 0 & vacuum for modes #1 & #2 psi0 = tensor(coherent(N0, alpha), basis(N1, 0), basis(N2, 0)) # trilinear Hamiltonian H = 1j * (a0 * a1.dag() * a2.dag() - a0.dag() * a1 * a2) # run Monte-Carlo data1 = mcsolve(H, psi0, tlist, [C0, C1, C2], [num0, num1, num2], ntraj=ntraj) data2 = mcsolve(H, psi0, tlist, [C0, C1, C2], [num0, num1, num2], ntraj=ntraj) diff_flag = False for k in range(ntraj): if len(data1.col_times[k]) != len(data2.col_times[k]): diff_flag = 1 break else: if not np.allclose(data1.col_which[k], data2.col_which[k]): diff_flag = 1 break assert_equal(diff_flag, 1)
def evolution_mcsolve_microwave(system, H_drive, initial_state, c_ops, e_ops, num_cpus=0, nsteps=2000, ntraj=1000, t_points=None, **kwargs): """ Calculates the expectation values vs time for a dissipative system for the gate activated by a microwave drive. Parameters ---------- system : :class:`coupobj.CoupledObjects` or similar An object of a quantum system supporting system.H() method for the Hamiltonian. H_drive : :class:`qutip.Qobj` The time-independent part of the driving term. Example: f * (a + a.dag()) or f * qubit.n() Normalization: see `H_drive_coeff_gate` function. initial_state : :class:`qutip.Qobj` Initial state of the system. c_ops : *list* of :class:`qutip.Qobj` The list of collaps operators for MC solver. e_ops : *list* of :class:`qutip.Qobj` The list of operators to calculate expectation values. num_cpus, nsteps, ntraj : int Parameters for MC solver t_points : *array* of float (optional) Times at which the evolution operator is returned. If None, it is generated from `kwargs['T_gate']`. **kwargs: Contains gate parameters such as pulse shape and gate time. Returns ------- *array* result.expect of mcsolve (time-dependent expectation values) result.expect[0] for the expectation value of the first operator """ if t_points is None: T_gate = kwargs['T_gate'] t_points = np.linspace(0, T_gate, 2 * int(T_gate) + 1) H_nodrive = system.H() H = [2 * np.pi * H_nodrive, [H_drive, H_drive_coeff_gate]] options = qt.Options(num_cpus=num_cpus, nsteps=nsteps) result = qt.mcsolve(H, initial_state, t_points, c_ops=c_ops, e_ops=e_ops, args=kwargs, ntraj=ntraj, options=options) return result.expect
def do_qt_mcsolve(state,H,lindblads,steps,tau,**kwargs): progress = kwargs.pop('progress_bar',None) times = kwargs.pop('times',None) if times is None: times = np.linspace(0,steps*tau,steps,dtype=np.float_) return qt.mcsolve(H,state,times,lindblads,[], options=qt.Options(**kwargs), progress_bar=progress).states
def test_expect_only(self, hamiltonian, args, c_ops, expected, tol): result = qutip.mcsolve(hamiltonian, self.state, self.times, args=args, c_ops=c_ops, e_ops=self.e_ops, ntraj=self.ntraj) self._assert_expect(result, expected, tol)
def correlation_ss_mc(H, tlist, c_op_list, a_op, b_op, rho0=None): """ Internal function for calculating correlation functions using the Monte Carlo solver. See :func:`correlation_ss` usage. """ if rho0 == None: rho0 = steadystate(H, co_op_list) return mcsolve(H, b_op * rho0, tlist, c_op_list, [a_op]).expect[0]
def test_mc_seed_noreuse(): "Monte-carlo: check not reusing seeds" N0 = 6 N1 = 6 N2 = 6 # damping rates gamma0 = 0.1 gamma1 = 0.4 gamma2 = 0.1 alpha = np.sqrt(2) # initial coherent state param for mode 0 tlist = np.linspace(0, 10, 2) ntraj = 500 # number of trajectories # define operators a0 = tensor(destroy(N0), qeye(N1), qeye(N2)) a1 = tensor(qeye(N0), destroy(N1), qeye(N2)) a2 = tensor(qeye(N0), qeye(N1), destroy(N2)) # number operators for each mode num0 = a0.dag() * a0 num1 = a1.dag() * a1 num2 = a2.dag() * a2 # dissipative operators for zero-temp. baths C0 = np.sqrt(2.0 * gamma0) * a0 C1 = np.sqrt(2.0 * gamma1) * a1 C2 = np.sqrt(2.0 * gamma2) * a2 # initial state: coherent mode 0 & vacuum for modes #1 & #2 psi0 = tensor(coherent(N0, alpha), basis(N1, 0), basis(N2, 0)) # trilinear Hamiltonian H = 1j * (a0 * a1.dag() * a2.dag() - a0.dag() * a1 * a2) # run Monte-Carlo data1 = mcsolve(H, psi0, tlist, [C0, C1, C2], [num0, num1, num2], ntraj=ntraj) data2 = mcsolve(H, psi0, tlist, [C0, C1, C2], [num0, num1, num2], ntraj=ntraj) diff_flag = False for k in range(ntraj): if len(data1.col_times[k]) != len(data2.col_times[k]): diff_flag = 1 break else: if not np.allclose(data1.col_which[k],data2.col_which[k]): diff_flag = 1 break assert_equal(diff_flag, 1)
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 do_qt_mcsolve(state, H, lindblads, steps, tau, **kwargs): progress = kwargs.pop('progress_bar', None) times = kwargs.pop('times', None) if times is None: times = np.linspace(0, steps * tau, steps, dtype=np.float_) return qt.mcsolve(H, state, times, lindblads, [], options=qt.Options(**kwargs), progress_bar=progress).states
def test_dynamic_arguments(): """Test dynamically updated arguments are usable.""" size = 5 a = qutip.destroy(size) H = qutip.num(size) times = np.linspace(0, 1, 11) state = qutip.basis(size, 2) c_ops = [[a, _dynamic], [a.dag(), _dynamic]] mc = qutip.mcsolve(H, state, times, c_ops, ntraj=25, args={"collapse": []}) assert all(len(collapses) <= 1 for collapses in mc.col_which)
def run(neq=10, ntraj=100, solver='both', ncpus=1): # sparse initial state # psi0 = basis(neq,neq-1) # dense initial state psi0 = qt.Qobj(np.ones((neq, 1))).unit() a = qt.destroy(neq) ad = a.dag() H = ad*a # c_ops = [gamma*a] c_ops = [qt.qeye(neq)] e_ops = [ad*a] # Times T = 10.0 dt = 0.1 nstep = int(T/dt) tlist = np.linspace(0, T, nstep) # set options opts = qt.Options() opts.num_cpus = ncpus opts.gui = False mcf90_time = 0. mc_time = 0. if (solver == 'mcf90' or solver == 'both'): start_time = time.time() mcf90.mcsolve_f90(H, psi0, tlist, c_ops, e_ops, ntraj=ntraj, options=opts) mcf90_time = time.time()-start_time print("mcsolve_f90 solutiton took", mcf90_time, "s") if (solver == 'mc' or solver == 'both'): start_time = time.time() qt.mcsolve(H, psi0, tlist, c_ops, e_ops, ntraj=ntraj, options=opts, progress_bar=False) mc_time = time.time()-start_time print("mcsolve solutiton took", mc_time, "s") return mcf90_time, mc_time
def mcsolve(self, ntrajs=500, exps=[], initial_state=None): """mcsolve Interface to qutip mcsolve for the system :param ntrajs: number of quantum trajectories to average. Default is QuTiP default of 500 :param exps: List of expectation values to calculate at each timestep """ if initial_state is None: initial_state = qt.tensor(qt.basis(self.N_field_levels, 0), qt.basis(2, 0)) return qt.mcsolve(self.hamiltonian()[0], initial_state, self.tlist, self._c_ops(), exps, ntraj=ntrajs)
def test_MCCollapseTimesOperators(): "Monte-carlo: Check for stored collapse operators and times" N = 10 kappa = 5.0 times = np.linspace(0, 10, 100) a = destroy(N) H = a.dag() * a psi0 = basis(N, 9) c_ops = [np.sqrt(kappa) * a, np.sqrt(kappa) * a] result = mcsolve(H, psi0, times, c_ops, [], ntraj=1) assert_(len(result.col_times[0]) > 0) assert_(len(result.col_which) == len(result.col_times)) assert_(set(result.col_which[0]) == {0, 1})
def correlation_mc(H, psi0, tlist, taulist, c_op_list, a_op, b_op): """ Internal function for calculating correlation functions using the Monte Carlo solver. See :func:`correlation` usage. """ C_mat = zeros([size(tlist),size(taulist)],dtype=complex) ntraj = 100 mc_opt = Mcoptions() mc_opt.progressbar = False psi_t = mcsolve(H, psi0, tlist, ntraj, c_op_list, [], mc_opt).states for t_idx in range(len(tlist)): psi0_t = psi_t[0][t_idx] C_mat[t_idx, :] = mcsolve(H, b_op * psi0_t, tlist, ntraj, c_op_list, [a_op], mc_opt).expect[0] return C_mat
def test_MCSimpleSingleExpect(): """Monte-carlo: Constant H with single expect operator""" N = 10 # number of basis states to consider a = destroy(N) H = a.dag() * a psi0 = basis(N, 9) # initial state kappa = 0.2 # coupling to oscillator c_op_list = [np.sqrt(kappa) * a] tlist = np.linspace(0, 10, 100) mcdata = mcsolve(H, psi0, tlist, c_op_list, a.dag() * a, ntraj=ntraj) expt = mcdata.expect[0] actual_answer = 9.0 * np.exp(-kappa * tlist) avg_diff = np.mean(abs(actual_answer - expt) / actual_answer) assert_equal(avg_diff < mc_error, True)
def test_MCSimpleConstFunc(): "Monte-carlo: Collapse terms constant (func format)" N = 10 # number of basis states to consider a = destroy(N) H = a.dag() * a psi0 = basis(N, 9) # initial state kappa = 0.2 # coupling to oscillator c_op_list = [[a, sqrt_kappa]] tlist = np.linspace(0, 10, 100) mcdata = mcsolve(H, psi0, tlist, c_op_list, [a.dag() * a], ntraj=ntraj) expt = mcdata.expect[0] actual_answer = 9.0 * np.exp(-kappa * tlist) avg_diff = np.mean(abs(actual_answer - expt) / actual_answer) assert_equal(avg_diff < mc_error, True)
def correlation_mc(H, psi0, tlist, taulist, c_op_list, a_op, b_op): """ Internal function for calculating correlation functions using the Monte Carlo solver. See :func:`correlation` usage. """ C_mat = zeros([size(tlist), size(taulist)], dtype=complex) ntraj = 100 mc_opt = Mcoptions() mc_opt.progressbar = False psi_t = mcsolve(H, psi0, tlist, ntraj, c_op_list, [], mc_opt).states for t_idx in range(len(tlist)): psi0_t = psi_t[0][t_idx] C_mat[t_idx, :] = mcsolve(H, b_op * psi0_t, tlist, ntraj, c_op_list, [a_op], mc_opt).expect[0] return C_mat
def test_MCNoCollExpt(): "Monte-carlo: Constant H with no collapse ops (expect)" error = 1e-8 N = 10 # number of basis states to consider a = destroy(N) H = a.dag() * a psi0 = basis(N, 9) # initial state c_op_list = [] tlist = np.linspace(0, 10, 100) mcdata = mcsolve(H, psi0, tlist, c_op_list, [a.dag() * a], ntraj=ntraj) expt = mcdata.expect[0] actual_answer = 9.0 * np.ones(len(tlist)) diff = np.mean(abs(actual_answer - expt) / actual_answer) assert_equal(diff < error, True)
def test_MCTDFunc(): "Monte-carlo: Time-dependent H (func format)" error = 5e-2 N = 10 # number of basis states to consider a = destroy(N) H = a.dag() * a psi0 = basis(N, 9) # initial state kappa = 0.2 # coupling to oscillator c_op_list = [[a, sqrt_kappa2]] tlist = np.linspace(0, 10, 100) mcdata = mcsolve(H, psi0, tlist, c_op_list, [a.dag() * a], ntraj=ntraj) expt = mcdata.expect[0] actual_answer = 9.0 * np.exp(-kappa * (1.0 - np.exp(-tlist))) diff = np.mean(abs(actual_answer - expt) / actual_answer) assert_equal(diff < error, True)
def test_MCNoCollFuncStates(): "Monte-carlo: Constant H (func format) with no collapse ops (states)" error = 1e-8 N = 10 # number of basis states to consider a = destroy(N) H = [a.dag() * a, [a.dag() * a, const_H1_coeff]] psi0 = basis(N, 9) # initial state c_op_list = [] tlist = np.linspace(0, 10, 100) mcdata = mcsolve(H, psi0, tlist, c_op_list, [], ntraj=ntraj) states = mcdata.states expt = expect(a.dag() * a, states) actual_answer = 9.0 * np.ones(len(tlist)) diff = np.mean(abs(actual_answer - expt) / actual_answer) assert_equal(diff < error, True)
def test_stored_collapse_operators_and_times(): """ Test that the output contains information on which collapses happened and at what times, and make sure that this information makes sense. """ size = 10 a = qutip.destroy(size) H = qutip.num(size) state = qutip.basis(size, size - 1) times = np.linspace(0, 10, 100) c_ops = [a, a] result = qutip.mcsolve(H, state, times, c_ops, ntraj=1) assert len(result.col_times[0]) > 0 assert len(result.col_which) == len(result.col_times) assert all(col in [0, 1] for col in result.col_which[0])
def test_mc_ntraj_list(): "Monte-carlo: list of trajectories" N = 5 a = destroy(N) H = a.dag() * a # Simple oscillator Hamiltonian psi0 = basis(N, 1) # Initial Fock state with one photon kappa = 1.0 / 0.129 # Coupling rate to heat bath nth = 0.063 # Temperature with <n>=0.063 # Build collapse operators for the thermal bath c_ops = [] c_ops.append(np.sqrt(kappa * (1 + nth)) * a) c_ops.append(np.sqrt(kappa * nth) * a.dag()) ntraj = [1, 5, 15, 904] # number of MC trajectories tlist = np.linspace(0, 0.8, 100) mc = mcsolve(H, psi0, tlist, c_ops, [a.dag() * a], ntraj) assert_equal(len(mc.expect), 4)
def test_mc_ntraj_list(): "Monte-carlo: list of trajectories" N = 5 a = destroy(N) H = a.dag()*a # Simple oscillator Hamiltonian psi0 = basis(N, 1) # Initial Fock state with one photon kappa = 1.0/0.129 # Coupling rate to heat bath nth = 0.063 # Temperature with <n>=0.063 # Build collapse operators for the thermal bath c_ops = [] c_ops.append(np.sqrt(kappa * (1 + nth)) * a) c_ops.append(np.sqrt(kappa * nth) * a.dag()) ntraj = [1, 5, 15, 904] # number of MC trajectories tlist = np.linspace(0, 0.8, 100) mc = mcsolve(H, psi0, tlist, c_ops, [a.dag()*a], ntraj) assert_equal(len(mc.expect), 4)
def test_list_ntraj(): """Test that `ntraj` can be a list.""" size = 5 a = qutip.destroy(size) H = qutip.num(size) state = qutip.basis(size, 1) times = np.linspace(0, 0.8, 100) # Arbitrary coupling and bath temperature. coupling = 1 / 0.129 n_th = 0.063 c_ops = [np.sqrt(coupling * (n_th + 1)) * a, np.sqrt(coupling * n_th) * a.dag()] e_ops = [qutip.num(size)] ntraj = [1, 5, 15, 100] mc = qutip.mcsolve(H, state, times, c_ops, e_ops, ntraj=ntraj) assert len(ntraj) == len(mc.expect)
def test_MCSimpleConstStates(): "Monte-carlo: Constant H with constant collapse (states)" N = 10 # number of basis states to consider a = destroy(N) H = a.dag() * a psi0 = basis(N, 9) # initial state kappa = 0.2 # coupling to oscillator c_op_list = [np.sqrt(kappa) * a] tlist = np.linspace(0, 10, 100) mcdata = mcsolve(H, psi0, tlist, c_op_list, [], ntraj=ntraj, options=Options(average_states=True)) assert_(len(mcdata.states) == len(tlist)) assert_(isinstance(mcdata.states[0], Qobj)) expt = expect(a.dag() * a, mcdata.states) actual_answer = 9.0 * np.exp(-kappa * tlist) avg_diff = np.mean(abs(actual_answer - expt) / actual_answer) assert_equal(avg_diff < mc_error, True)
def test_TDStr(): "Monte-carlo: Time-dependent H (str format)" error = 5e-2 N = 10 # number of basis states to consider a = destroy(N) H = a.dag() * a psi0 = basis(N, 9) # initial state kappa = 0.2 # coupling to oscillator c_op_list = [[a, 'sqrt(k*exp(-t))']] args = {'k': kappa} tlist = np.linspace(0, 10, 100) mcdata = mcsolve(H, psi0, tlist, c_op_list, [a.dag() * a], args=args, ntraj=ntraj) expt = mcdata.expect[0] actual = 9.0 * np.exp(-kappa * (1.0 - np.exp(-tlist))) diff = np.mean(abs(actual - expt) / actual) assert_equal(diff < error, True)
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 steady_state_mc(Ej, Ec, ng, g, wr, kappa, gamma, gamma_phi, N, J, xi, wd, ntraj, ti, tf, tsteps, cpus=None): values = locals() p = SimpleNamespace() p.__dict__.update(values) times = np.linspace(p.ti, p.tf, p.tsteps) ham = jaynes_cummings(p) psi0 = jaynes_cummings(p, driven=False).groundstate()[1] opts = qt.Odeoptions() if cpus: opts.num_cpus = cpus actualstdout = sys.stdout sys.stdout = cStringIO.StringIO() # avoids prints to stdout t_evol = qt.mcsolve(ham, psi0, times, decoherence(p), op_list(p), p.ntraj, options=opts) sys.stdout = actualstdout # reactivates stdout result = np.array([i[-1] for i in t_evol.expect]) result[-1] = np.abs(result[-1]) return tuple(np.real(result))
def test_MCNoCollExpectStates(): "Monte-carlo: Constant H with no collapse ops (expect and states)" error = 1e-8 N = 10 # number of basis states to consider a = destroy(N) H = a.dag() * a psi0 = basis(N, 9) # initial state c_op_list = [] tlist = np.linspace(0, 10, 100) mcdata = mcsolve(H, psi0, tlist, c_op_list, [a.dag() * a], ntraj=ntraj, options=Options(store_states=True)) actual_answer = 9.0 * np.ones(len(tlist)) expt = mcdata.expect[0] diff = np.mean(abs(actual_answer - expt) / actual_answer) assert_equal(diff < error, True) assert_(len(mcdata.states) == len(tlist)) assert_(isinstance(mcdata.states[0], Qobj)) expt = expect(a.dag() * a, mcdata.states) diff = np.mean(abs(actual_answer - expt) / actual_answer) assert_equal(diff < error, True)
def solve_lindblad(gamma1, gamma2, nbar_omega, nbar_delta, kappa, rho0, tlist, is_mc=False, opts=None): # define system adag = qutip.create(N) a = adag.dag() H = hbar * omega * adag * a nbar2_omega = nbar_omega ** 2 / (1 + 2 * nbar_omega) # define collapse operators C_arr = [] C_arr.append(gamma1 * (1 + nbar_omega) * a) C_arr.append(gamma2 * (1 + nbar2_omega) * a * a) C_arr.append(kappa * (1 + nbar_delta) * adag) if nbar_omega > 0: C_arr.append(gamma1 * nbar_omega * adag) C_arr.append(gamma2 * nbar2_omega * adag * adag) if nbar_delta > 0: C_arr.append(kappa * nbar_delta * a) # solve master eq. if is_mc: return qutip.mcsolve(H, rho0, tlist, C_arr, []) else: return qutip.mesolve(H, rho0, tlist, C_arr, [], options=opts)
def trajectory(self, exps=None, initial_state=None, draw=False): """for convenience. Calculates the trajectory of an observable for one montecarlo run. Default expectation is cavity amplitude, default initial state is bipartite vacuum. todo: draw: draw trajectory on bloch sphere. Write in terms of mcsolve??""" if exps is None or draw is True: exps = [] if initial_state is None: initial_state = qt.tensor(qt.basis(self.N_field_levels, 0), qt.basis(2, 0)) self.one_traj_soln = qt.mcsolve(self.hamiltonian(), initial_state, self.tlist, self._c_ops(), exps, ntraj=1) if self.noisy: print(self.one_traj_soln.states[0][2].ptrace(1)) if not draw: return self.one_traj_soln else: self.b_sphere = qt.Bloch() self.b_sphere.add_states([state.ptrace(1) for state in self.one_traj_soln.states[0]], "point") self.b_sphere.point_markers = ["o"] self.b_sphere.size = (10, 10) self.b_sphere.show()
def test(): gamma = 1. neq = 2 psi0 = qt.basis(neq,neq-1) #a = qt.destroy(neq) #ad = a.dag() #H = ad*a #c_ops = [gamma*a] #e_ops = [ad*a] H = qt.sigmax() c_ops = [np.sqrt(gamma)*qt.sigmax()] #c_ops = [] e_ops = [qt.sigmam()*qt.sigmap(),qt.sigmap()*qt.sigmam()] #e_ops = [] # Times T = 2.0 dt = 0.1 nstep = int(T/dt) tlist = np.linspace(0,T,nstep) ntraj=100 # set options opts = qt.Odeoptions() opts.num_cpus=2 #opts.mc_avg = True #opts.gui=False #opts.max_step=1000 #opts.atol = #opts.rtol = sol_f90 = qt.Odedata() start_time = time.time() sol_f90 = mcf90.mcsolve_f90(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,options=opts) print "mcsolve_f90 solutiton took", time.time()-start_time, "s" sol_me = qt.Odedata() start_time = time.time() sol_me = qt.mesolve(H,psi0,tlist,c_ops,e_ops,options=opts) print "mesolve solutiton took", time.time()-start_time, "s" sol_mc = qt.Odedata() start_time = time.time() sol_mc = qt.mcsolve(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,options=opts) print "mcsolve solutiton took", time.time()-start_time, "s" if (e_ops == []): e_ops = [qt.sigmam()*qt.sigmap(),qt.sigmap()*qt.sigmam()] sol_f90expect = [np.array([0.+0.j]*nstep)]*len(e_ops) sol_mcexpect = [np.array([0.+0.j]*nstep)]*len(e_ops) sol_meexpect = [np.array([0.+0.j]*nstep)]*len(e_ops) for i in range(len(e_ops)): if (not opts.mc_avg): sol_f90expect[i] = sum([qt.expect(e_ops[i], sol_f90.states[j]) for j in range(ntraj)])/ntraj sol_mcexpect[i] = sum([qt.expect(e_ops[i], sol_mc.states[j]) for j in range(ntraj)])/ntraj else: sol_f90expect[i] = qt.expect(e_ops[i],sol_f90.states) sol_mcexpect[i] = qt.expect(e_ops[i],sol_mc.states) sol_meexpect[i] = qt.expect(e_ops[i],sol_me.states) elif (not opts.mc_avg): sol_f90expect = sum(sol_f90.expect,0)/ntraj sol_mcexpect = sum(sol_f90.expect,0)/ntraj sol_meexpect = sol_me.expect else: sol_f90expect = sol_f90.expect sol_mcexpect = sol_mc.expect sol_meexpect = sol_me.expect plt.figure() for i in range(len(e_ops)): plt.plot(tlist,sol_f90expect[i],'b') plt.plot(tlist,sol_mcexpect[i],'g') plt.plot(tlist,sol_meexpect[i],'k') return sol_f90, sol_mc