Ejemplo n.º 1
0
def test_bad_system():
    N = 4
    a = qutip.destroy(N)
    H = (a.dag() + a)
    with pytest.raises(TypeError):
        qutip.steadystate(H, [], method='direct')
    with pytest.raises(TypeError):
        qutip.steadystate(qutip.basis(N, N - 1), [], method='direct')
Ejemplo n.º 2
0
def test_bad_options_steadystate():
    N = 4
    a = qutip.destroy(N)
    H = (a.dag() + a)
    c_ops = [a]
    with pytest.raises(ValueError):
        rho_ss = qutip.steadystate(H, c_ops, method='not a method')
    with pytest.raises(TypeError):
        rho_ss = qutip.steadystate(H, c_ops, method='direct', bad_opt=True)
    with pytest.raises(ValueError):
        rho_ss = qutip.steadystate(H, c_ops, method='direct', solver='Error')
Ejemplo n.º 3
0
def two_tone(vg, listening=False, use_pinv=True):
    phi, wd = vg
    H = make_H(phi, Omega, wd * nvec, 0.0)

    if listening:
        final_state = steadystate(H, c_op_list)
        return expect(a, final_state)
    L = liouvillian(H, c_op_list)
    #tr_mat = tensor([qeye(n) for n in L.dims[0][0]])
    #N = prod(L.dims[0][0])

    A = L.full()

    #tr_vec = transpose(mat2vec(tr_mat.full()))

    rho_ss = steadystate(L)
    rho = transpose(mat2vec(rho_ss.full()))

    #P = kron(transpose(rho), tr_vec)
    #Q = I - P
    w = wp - wd
    if 1:
        D, U = eig(A)
        Uinv = inv(U)
    #spectrum = zeros(len(wlist))

    #for idx, w in enumerate(wlist):
    if 1:
        if use_pinv:
            MMR = pinv(-1.0j * w * I + A)
            #MMR = A*MMR*inv(A)
        elif use_pinv == 1:
            MMR = dot(Q, solve(-1.0j * w * I + A, Q))
        else:
            MMR = diag(1.0 / (1.0j * w * diag(I) + diag(D)))
            Lint = U * MMR * Uinv
            #Chi_temp[i,j] += (1/theta_steps)*1j*trace(reshape(tm_l*Lint*(p_l - p_r)*rho_ss_c,dim,dim))

        #rho_tr=transpose(rho)
        #p1=dot(b_sup, rho_tr)
        #p2=dot(rho_tr, b_sup)

        #s = dot(tr_vec,
        #           dot(a_sup, dot(MMR, p1-p2)))

        s1 = dot(tr_vec, dot(a_sup, dot(MMR, dot(b_sup, transpose(rho)))))
        s2 = dot(tr_vec, dot(b_sup, dot(MMR, dot(a_sup, transpose(rho)))))
        s = s1 - s2
        #spectrum[idx] =
        return -2 * real(s[0, 0])

    return spectrum
Ejemplo n.º 4
0
def test_qubit_power_gmres():
    "Steady state: Thermal qubit - power-gmres solver"
    # thermal steadystate of a qubit: compare numerics with analytical formula
    sz = sigmaz()
    sm = destroy(2)

    H = 0.5 * 2 * np.pi * sz
    gamma1 = 0.05

    wth_vec = np.linspace(0.1, 3, 20)
    p_ss = np.zeros(np.shape(wth_vec))

    for idx, wth in enumerate(wth_vec):
        n_th = 1.0 / (np.exp(1.0 / wth) - 1)  # bath temperature
        c_op_list = []
        rate = gamma1 * (1 + n_th)
        c_op_list.append(np.sqrt(rate) * sm)
        rate = gamma1 * n_th
        c_op_list.append(np.sqrt(rate) * sm.dag())
        rho_ss = steadystate(H, c_op_list, method='power-gmres', mtol=1e-1)
        p_ss[idx] = expect(sm.dag() * sm, rho_ss)

    p_ss_analytic = np.exp(-1.0 / wth_vec) / (1 + np.exp(-1.0 / wth_vec))
    delta = sum(abs(p_ss_analytic - p_ss))
    assert_equal(delta < 1e-5, True)
    def __init__(self, hamiltonian, jump_operators, drive_hamiltonian,
                 angular_frequency):

        if isinstance(hamiltonian, qt.Qobj) and isinstance(
                drive_hamiltonian, qt.Qobj):
            self.hamiltonian = hamiltonian
            self.v = drive_hamiltonian
        else:
            raise TypeError(
                "The system Hamiltonian and drive Hamiltonian must both be a quantum object"
            )

        self.dim = self.hamiltonian.shape[0]
        self.omega = angular_frequency
        self.evals, self.evecs = self.hamiltonian.eigenstates()

        self.jump_ops = jump_operators
        # This initial steady-state is the thermal equilibrium state (bootstrapping)
        self.rho_s = qt.steadystate(self.hamiltonian, self.jump_ops)
        self.density_matrix = [[
            (self.evecs[a].dag() * self.rho_s * self.evecs[b])[0]
            for b in range(self.dim)
        ] for a in range(self.dim)]
        self.density_matrix = np.asarray(self.density_matrix)

        self.integer_list = [0 for k in range(self.dim)]
        self.drive_term_list = []
        self.rotating_frame_hamiltonian = self.hamiltonian
    def find_expect(self, vg, pwr, fd):
        if self.power_plot:
            phi, pwr=vg
        else:
            phi, fd=vg
        pwr_fridge=pwr-self.atten
        lin_pwr=0.001*10**(pwr_fridge/10.0)
        Omega=sqrt(lin_pwr/h*2.0)

        gamma, Delta=self._get_GammaDelta(fd=fd, f0=self.f0, Np=self.Np, gamma=self.gamma)
        g_el=self._get_Gamma_C(fd=fd)
        wTvec=self._get_fTvec(phi=phi, gamma=gamma, Delta=Delta, fd=fd, Psaw=lin_pwr)

        if self.acoustic_plot:
            Om=Omega*sqrt(gamma/fd)
        else:
            Om=Omega*sqrt(g_el/fd)
        wT = wTvec-fd*self.nvec #rotating frame of gate drive \omega_m-m*\omega_\gate
        transmon_levels = Qobj(diag(wT[range(self.N_dim)]))
        rate1 = (gamma+g_el)*(1.0 + self.N_gamma)
        rate2 = (gamma+g_el)*self.N_gamma
        c_ops=[sqrt(rate1)*self.a_op, sqrt(rate2)*self.a_dag]#, sqrt(rate3)*self.a_op, sqrt(rate4)*self.a_dag]
        Omega_vec=-0.5j*(Om*self.a_dag - conj(Om)*self.a_op)
        H=transmon_levels +Omega_vec
        final_state = steadystate(H, c_ops) #solve master equation
        fexpt=expect(self.a_op, final_state) #expectation value of relaxation operator
        #return fexpt
        if self.acoustic_plot:
            return 1.0*gamma/Om*fexpt
        else:
            return 1.0*sqrt(g_el*gamma)/Om*fexpt
Ejemplo n.º 7
0
def test_correlation_2op_1t_known_cases(solver,
                                        state,
                                        is_e_op_hermitian,
                                        w,
                                        gamma,
                                       ):
    """This test compares the output correlation_2op_1 solution to an analytical
    solution."""

    a = qutip.destroy(_equivalence_dimension)
    x = (a + a.dag())/np.sqrt(2)

    H = w * a.dag() * a

    a_op = x if is_e_op_hermitian else a
    b_op = x if is_e_op_hermitian else a.dag()
    c_ops = [np.sqrt(gamma) * a]

    times = np.linspace(0, 1, 30)

    # Handle the case state==None when computing expt values
    rho0 = state if state else qutip.steadystate(H, c_ops)
    if is_e_op_hermitian:
        # Analitycal solution for x,x as operators.
        base = 0
        base += qutip.expect(a*x, rho0)*np.exp(-1j*w*times - gamma*times/2)
        base += qutip.expect(a.dag()*x, rho0)*np.exp(1j*w*times - gamma*times/2)
        base /= np.sqrt(2)
    else:
        # Analitycal solution for a,adag as operators.
        base = qutip.expect(a*a.dag(), rho0)*np.exp(-1j*w*times - gamma*times/2)

    cmp = qutip.correlation_2op_1t(H, state, times, c_ops, a_op, b_op, solver=solver)

    np.testing.assert_allclose(base, cmp, atol=0.25 if solver == 'mc' else 2e-5)
Ejemplo n.º 8
0
def self_correlation(experiment, stop_time, steps=500, field='probe'):
    """Returns the self correlation of one of the cavity fields

    :param experiment: The experiment on which the scan is performed
    :type experiment: ntypecqed.simulation.NTypeExperiment
    :param stop_time: Stop time of the correlation
    :type stop_time: float
    :param steps: Number of steps
    :type steps: int
    :param field: The field for which the self correlation is calculated, either 'probe' or 'signal'
    :type field: str
    :return: tuple(times, correlation value)
    """
    if field == 'probe':
        operator = experiment.environment.a
    elif field == 'signal':
        operator = experiment.environment.b
    else:
        raise (ValueError,
               "No valid field name, valid fields are: 'probe' or 'signal'")

    tau_list = np.linspace(0, stop_time, steps)
    ss = steadystate(experiment.driven_hamiltonian,
                     experiment.environment.c_ops)
    n = expect(operator.dag() * operator, ss)
    corr_data = correlation_3op_1t(experiment.driven_hamiltonian, ss,
                                   tau_list, experiment.environment.c_ops,
                                   operator.dag(),
                                   operator.dag() * operator, operator)
    corr_data /= (n * n)
    return tau_list, corr_data
Ejemplo n.º 9
0
def triple_coincidences(experiment, trigger_photon='probe', normed=True):
    """Returns the value of the triggered two photon self correlation at time 0

    :param experiment: The experiment on which the scan is performed
    :type experiment: ntypecqed.simulation.NTypeExperiment
    :param trigger_photon: The photon which starts the self correlation, either 'probe' or 'signal'
    :type trigger_photon: str
    :param normed: Normalize to the power level
    :type normed: bool
    :return: correlation value
    """
    if trigger_photon == 'probe':
        trig_op = experiment.environment.a
        self_op = experiment.environment.b
    elif trigger_photon == 'signal':
        trig_op = experiment.environment.b
        self_op = experiment.environment.a
    else:
        raise (
            ValueError,
            "No valid trigger photon name, valid names are: 'probe' or 'signal'"
        )
    ss = steadystate(experiment.driven_hamiltonian,
                     experiment.environment.c_ops)
    n_a, n_b = expect(experiment.environment.n_a,
                      ss), expect(experiment.environment.n_b, ss)
    expectation_operator = trig_op.dag() * self_op.dag() * self_op.dag(
    ) * self_op * self_op * trig_op
    corr_data = expect(expectation_operator, ss)
    if normed:
        if trigger_photon == 'probe':
            corr_data /= (n_a * n_b * n_b)
        else:
            corr_data /= (n_b * n_a * n_a)
    return corr_data
Ejemplo n.º 10
0
def test_ho_bicgstab():
    "Steady state: Thermal HO - iterative-bicgstab solver"
    # thermal steadystate of an oscillator: compare numerics with analytical
    # formula
    a = destroy(40)
    H = 0.5 * 2 * np.pi * a.dag() * a
    gamma1 = 0.05

    wth_vec = np.linspace(0.1, 3, 20)
    p_ss = np.zeros(np.shape(wth_vec))

    for idx, wth in enumerate(wth_vec):

        n_th = 1.0 / (np.exp(1.0 / wth) - 1)  # bath temperature
        c_op_list = []
        rate = gamma1 * (1 + n_th)
        c_op_list.append(np.sqrt(rate) * a)
        rate = gamma1 * n_th
        c_op_list.append(np.sqrt(rate) * a.dag())
        rho_ss = steadystate(H, c_op_list, method='iterative-bicgstab')
        p_ss[idx] = np.real(expect(a.dag() * a, rho_ss))

    p_ss_analytic = 1.0 / (np.exp(1.0 / wth_vec) - 1)
    delta = sum(abs(p_ss_analytic - p_ss))
    assert_equal(delta < 1e-3, True)
Ejemplo n.º 11
0
def test_qubit(method, kwargs):
    # thermal steadystate of a qubit: compare numerics with analytical formula
    sz = qutip.sigmaz()
    sm = qutip.destroy(2)

    H = 0.5 * 2 * np.pi * sz
    gamma1 = 0.05

    wth_vec = np.linspace(0.1, 3, 20)
    p_ss = np.zeros(np.shape(wth_vec))

    with warnings.catch_warnings():
        if 'use_wbm' in kwargs:
            # The deprecation has been fixed in dev.major
            warnings.simplefilter("ignore", category=DeprecationWarning)

        for idx, wth in enumerate(wth_vec):
            n_th = 1.0 / (np.exp(1.0 / wth) - 1)  # bath temperature
            c_op_list = []
            rate = gamma1 * (1 + n_th)
            c_op_list.append(np.sqrt(rate) * sm)
            rate = gamma1 * n_th
            c_op_list.append(np.sqrt(rate) * sm.dag())
            rho_ss = qutip.steadystate(H, c_op_list, method=method, **kwargs)
            if 'return_info' in kwargs:
                rho_ss, info = rho_ss
                assert isinstance(info, dict)
            p_ss[idx] = qutip.expect(sm.dag() * sm, rho_ss)

    p_ss_analytic = np.exp(-1.0 / wth_vec) / (1 + np.exp(-1.0 / wth_vec))
    np.testing.assert_allclose(p_ss_analytic, p_ss, atol=1e-5)
Ejemplo n.º 12
0
def test_ho_lgmres():
    "Steady state: Thermal HO - iterative-lgmres solver"
    # thermal steadystate of an oscillator: compare numerics with analytical
    # formula
    a = destroy(40)
    H = 0.5 * 2 * np.pi * a.dag() * a
    gamma1 = 0.05

    wth_vec = np.linspace(0.1, 3, 20)
    p_ss = np.zeros(np.shape(wth_vec))

    for idx, wth in enumerate(wth_vec):

        n_th = 1.0 / (np.exp(1.0 / wth) - 1)  # bath temperature
        c_op_list = []
        rate = gamma1 * (1 + n_th)
        c_op_list.append(np.sqrt(rate) * a)
        rate = gamma1 * n_th
        c_op_list.append(np.sqrt(rate) * a.dag())
        rho_ss = steadystate(H, c_op_list, method='iterative-lgmres')
        p_ss[idx] = np.real(expect(a.dag() * a, rho_ss))

    p_ss_analytic = 1.0 / (np.exp(1.0 / wth_vec) - 1)
    delta = sum(abs(p_ss_analytic - p_ss))
    assert_equal(delta < 1e-3, True)
Ejemplo n.º 13
0
def _spectrum_es(H, wlist, c_ops, a_op, b_op):
    """
    Internal function for calculating the spectrum of the correlation function
    :math:`\left<A(\\tau)B(0)\\right>`.
    """
    if debug:
        print(inspect.stack()[0][3])

    # construct the Liouvillian
    L = liouvillian(H, c_ops)

    # find the steady state density matrix and a_op and b_op expecation values
    rho0 = steadystate(L)

    a_op_ss = expect(a_op, rho0)
    b_op_ss = expect(b_op, rho0)

    # eseries solution for (b * rho0)(t)
    es = ode2es(L, b_op * rho0)

    # correlation
    corr_es = expect(a_op, es)

    # covariance
    cov_es = corr_es - np.real(np.conjugate(a_op_ss) * b_op_ss)

    # spectrum
    spectrum = esspec(cov_es, wlist)

    return spectrum
Ejemplo n.º 14
0
    def steady(N = 20):  # number of basis states to consider
        n=num(N)
        a = destroy(N)
        H = a.dag() * a
        print H.eigenstates()
        #psi0 = basis(N, 10)  # initial state
        kappa = 0.1  # coupling to oscillator
        c_op_list = []
        n_th_a = 2  # temperature with average of 2 excitations
        rate = kappa * (1 + n_th_a)
        c_op_list.append(sqrt(rate) * a)  # decay operators
        rate = kappa * n_th_a
        c_op_list.append(sqrt(rate) * a.dag())  # excitation operators
        final_state = steadystate(H, c_op_list)
        fexpt = expect(a.dag() * a, final_state)

        #tlist = linspace(0, 100, 100)

        #mcdata = mcsolve(H, psi0, tlist, c_op_list, [a.dag() * a], ntraj=100)

        #medata = mesolve(H, psi0, tlist, c_op_list, [a.dag() * a])
        #plot(tlist, mcdata.expect[0],
        #plt.plot(tlist, medata.expect[0], lw=2)
        plt.axhline(y=fexpt, color='r', lw=1.5) # ss expt. value as horiz line (= 2)
        plt.ylim([0, 10])
        plt.show()
Ejemplo n.º 15
0
def test_qubit_power():
    "Steady state: Thermal qubit - power solver"
    # thermal steadystate of a qubit: compare numerics with analytical formula
    sz = sigmaz()
    sm = destroy(2)

    H = 0.5 * 2 * np.pi * sz
    gamma1 = 0.05

    wth_vec = np.linspace(0.1, 3, 20)
    p_ss = np.zeros(np.shape(wth_vec))

    for idx, wth in enumerate(wth_vec):

        n_th = 1.0 / (np.exp(1.0 / wth) - 1)  # bath temperature
        c_op_list = []
        rate = gamma1 * (1 + n_th)
        c_op_list.append(np.sqrt(rate) * sm)
        rate = gamma1 * n_th
        c_op_list.append(np.sqrt(rate) * sm.dag())
        rho_ss = steadystate(H, c_op_list, method='power')
        p_ss[idx] = expect(sm.dag() * sm, rho_ss)

    p_ss_analytic = np.exp(-1.0 / wth_vec) / (1 + np.exp(-1.0 / wth_vec))
    delta = sum(abs(p_ss_analytic - p_ss))
    assert_equal(delta < 1e-5, True)
Ejemplo n.º 16
0
def generate_result_states(params, times, psi0=None, opt=None):
    if opt is None:
        opt = Options()
        opt.atol = 1e-6
        opt.rtol = 1e-6

    args = {'params': params}

    c_ops = c_ops_gen_jc(params)
    e_ops = []

    H = construct_ham(params)
    if psi0 is None:
        psi0 = steadystate(H[0], c_ops)

    opt.store_states = True
    trace = mesolve(H, psi0, times, c_ops, e_ops, args=args, options=opt)

    size = 2 * params.c_levels
    state_array = np.zeros([len(trace.states), size, size], dtype=complex)
    for i, state in enumerate(trace.states):
        state_array[i] = state.full()

    frame_content = [[trace.times, state_array, params]]
    columns = ['times', 'states', 'params']
    results_frame = pd.DataFrame(frame_content, columns=columns)
    results_frame['fd'] = params.fd
    results_frame.set_index('fd', inplace=True)

    return results_frame
Ejemplo n.º 17
0
def generate_result(params, times, psi0=None, opt=None, e_ops=None):
    if opt is None:
        opt = Options()
        opt.atol = 1e-6
        opt.rtol = 1e-6

    args = {'params': params}

    if e_ops is None:
        e_ops = e_ops_gen(params)

    c_ops = c_ops_gen_jc(params)

    H = construct_ham(params)
    if psi0 is None:
        psi0 = steadystate(H[0], c_ops)

    trace = mesolve(H, psi0, times, c_ops, e_ops, args=args, options=opt)

    results_frame = pd.DataFrame(trace.expect, index=times)
    results_frame.index.name = 'time'
    results_frame['fd'] = params.fd
    results_frame.set_index('fd', inplace=True, append=True)
    results_frame = results_frame.reorder_levels(['fd', 'time'])

    return results_frame
Ejemplo n.º 18
0
def cross_correlation(experiment,
                      start_time,
                      stop_time,
                      steps=500,
                      flip_time_axis=False):
    """Performs a cross correlation between signal and probe light field

    :param experiment: The experiment on which the scan is performed
    :type experiment: ntypecqed.simulation.NTypeExperiment
    :param start_time: Start time of the correlation
    :type start_time: float
    :param stop_time: Stop time of the correlation
    :type stop_time: float
    :param steps: Number of steps
    :type steps: int
    :param flip_time_axis: if True the positive time direction is a signal photon first and a probe photon second
    :type flip_time_axis: bool
    :return: tuple(times, correlation value)
    """

    if start_time > 0 or stop_time < 0 or start_time >= stop_time:
        raise (
            ValueError,
            'Wrong times, conditions are start_time<0, stop_time>0 and start_time < stop_time'
        )

    tau_list_pos = np.linspace(0, abs(stop_time), steps)
    tau_list_neg = np.linspace(0, abs(start_time), steps)
    ss = steadystate(experiment.driven_hamiltonian,
                     experiment.environment.c_ops)
    photon_number_field_1, photon_number_field_2 = expect(experiment.environment.n_a, ss), \
                                                   expect(experiment.environment.n_b, ss)
    corr_data_pos = correlation_3op_1t(experiment.driven_hamiltonian, ss,
                                       tau_list_pos,
                                       experiment.environment.c_ops,
                                       experiment.environment.b.dag(),
                                       experiment.environment.n_a,
                                       experiment.environment.b)
    corr_data_neg = correlation_3op_1t(experiment.driven_hamiltonian, ss,
                                       tau_list_neg,
                                       experiment.environment.c_ops,
                                       experiment.environment.a.dag(),
                                       experiment.environment.n_b,
                                       experiment.environment.a)
    # norm the correlation
    corr_data_pos /= (photon_number_field_1 * photon_number_field_2)
    corr_data_neg /= (photon_number_field_1 * photon_number_field_2)
    # change one of the correlations to negative times
    if flip_time_axis:
        tau_list_pos = -tau_list_pos[::-1]
        corr_data_pos = corr_data_pos[::-1]
        return np.concatenate((tau_list_pos, tau_list_neg)), np.concatenate(
            (corr_data_pos, corr_data_neg))
    else:
        tau_list_neg = -tau_list_neg[::-1]
        corr_data_neg = corr_data_neg[::-1]
        return np.concatenate((tau_list_neg, tau_list_pos)), np.concatenate(
            (corr_data_neg, corr_data_pos))
Ejemplo n.º 19
0
def test_pseudo_inverse(method, kwargs):
    N = 4
    a = qutip.destroy(N)
    H = (a.dag() + a)
    L = qutip.liouvillian(H, [a])
    rho = qutip.steadystate(L)
    Lpinv = qutip.pseudo_inverse(L, rho, method=method, **kwargs)
    np.testing.assert_allclose((L * Lpinv * L).full(), L.full())
    np.testing.assert_allclose((Lpinv * L * Lpinv).full(), Lpinv.full())
Ejemplo n.º 20
0
def test_dqd_current():
    "Counting statistics: current and current noise in a DQD model"

    G = 0
    L = 1
    R = 2

    sz = qutip.projection(3, L, L) - qutip.projection(3, R, R)
    sx = qutip.projection(3, L, R) + qutip.projection(3, R, L)
    sR = qutip.projection(3, G, R)
    sL = qutip.projection(3, G, L)

    w0 = 1
    tc = 0.6 * w0
    GammaR = 0.0075 * w0
    GammaL = 0.0075 * w0
    nth = 0.00
    eps_vec = np.linspace(-1.5 * w0, 1.5 * w0, 20)

    J_ops = [GammaR * qutip.sprepost(sR, sR.dag())]

    c_ops = [
        np.sqrt(GammaR * (1 + nth)) * sR,
        np.sqrt(GammaR * (nth)) * sR.dag(),
        np.sqrt(GammaL * (nth)) * sL,
        np.sqrt(GammaL * (1 + nth)) * sL.dag()
    ]

    current = np.zeros(len(eps_vec))
    noise = np.zeros(len(eps_vec))

    for n, eps in enumerate(eps_vec):
        H = (eps / 2 * sz + tc * sx)
        L = qutip.liouvillian(H, c_ops)
        rhoss = qutip.steadystate(L)
        current[n], noise[n] = qutip.countstat_current_noise(L, [],
                                                             rhoss=rhoss,
                                                             J_ops=J_ops)

        current2 = qutip.countstat_current(L, rhoss=rhoss, J_ops=J_ops)
        assert abs(current[n] - current2) < 1e-8

        current2 = qutip.countstat_current(L, c_ops, J_ops=J_ops)
        assert abs(current[n] - current2) < 1e-8

    current_target = (tc**2 * GammaR /
                      (tc**2 *
                       (2 + GammaR / GammaL) + GammaR**2 / 4 + eps_vec**2))
    noise_target = current_target * (
        1 - (8 * GammaL * tc**2 *
             (4 * eps_vec**2 * (GammaR - GammaL) + GammaR *
              (3 * GammaL * GammaR + GammaR**2 + 8 * tc**2)) /
             (4 * tc**2 * (2 * GammaL + GammaR) + GammaL * GammaR**2 +
              4 * eps_vec**2 * GammaL)**2))

    np.testing.assert_allclose(current, current_target, atol=1e-4)
    np.testing.assert_allclose(noise, noise_target, atol=1e-4)
def big_loop(num_qubits, num_states, g):
    hilbert_space_dimension = 2**num_qubits
    # num_states = hilbert_space_dimension // 2
    random_indices = sorted(
        random.sample(range(hilbert_space_dimension), num_states))

    # print("The random indices are", random_indices)

    # observable_one = hcp.generate_arbitary_observable(num_qubits, [1], ["1" + "0"*(num_qubits-1)])
    # observable_two = hcp.generate_arbitary_observable(num_qubits, [1], ["2" + "0"*(num_qubits-1)])
    # observable_three = hcp.generate_arbitary_observable(num_qubits, [1], ["3" + "0"*(num_qubits-1)])
    # observables_list = [observable_one, observable_two, observable_three]

    if sai_or_fuji == "fuji":
        hamiltonian = generate_fuji_boy_hamiltonian(num_qubits, g)
        gammas, L_terms = generate_fuji_boy_gamma_and_Lterms(num_qubits)
    elif sai_or_fuji == "sai":
        hamiltonian = generate_XXZ_hamiltonian(num_qubits, g)
        gammas, L_terms = generate_nonlocaljump_gamma_and_Lterms(
            num_qubits, Gamma, mu)

    hamiltonian_matform = hamiltonian.to_matrixform()
    L_terms_matform = [i.to_matrixform() for i in L_terms]

    qtp_hamiltonian = qutip.Qobj(hamiltonian_matform)
    qtp_Lterms = [qutip.Qobj(i) for i in L_terms_matform]
    qtp_C_ops = [
        np.sqrt(gammas[i]) * qtp_Lterms[i] for i in range(len(qtp_Lterms))
    ]
    qtp_rho_ss = qutip.steadystate(qtp_hamiltonian,
                                   qtp_C_ops,
                                   method="iterative-gmres")

    #generate matrices
    E_matrix = generate_submatrix(np.eye(hilbert_space_dimension),
                                  random_indices)
    D_matrix = generate_submatrix(hamiltonian_matform, random_indices)
    R_matrices = [
        generate_submatrix(i, random_indices) for i in L_terms_matform
    ]
    F_matrices = [
        generate_submatrix(i.conj().T @ i, random_indices)
        for i in L_terms_matform
    ]

    beta = opt_package.cvxpy_density_matrix_feasibility_sdp_routine(
        D_matrix, E_matrix, R_matrices, F_matrices, gammas, 0,
        verbose=False)[0]

    rho = submatrix_to_full_matrix(num_qubits, beta, random_indices)

    rho_dot = evaluate_rho_dot(rho, hamiltonian, gammas, L_terms)  #should be 0
    print('Max value rho_dot is: ' + str(np.max(np.max(rho_dot))))
    qtp_rho = qutip.Qobj(rho)
    fidelity = qutip.metrics.fidelity(qtp_rho, qtp_rho_ss)
    # print("The fidelity is", fidelity)
    return fidelity
Ejemplo n.º 22
0
def steadystate_parfor_func(Delta, Delta_idx=0, Deltas=[], ob_obj=None):

    print("Delta: " + str(Delta) + "\r")

    Deltas[Delta_idx] = Delta

    ob_obj.set_H_Delta(Deltas)
    H = ob_obj.H_0 + ob_obj.H_Delta + ob_obj.H_I_sum()

    return qu.steadystate(H, ob_obj.c_ops)
Ejemplo n.º 23
0
    def rhos(self, nslice=None):
        """rho
        return steadystate density matrices"""
        self.precalc = True

        if self.noisy:
            print("N = {}, len() = {}".format(self.N_field_levels, len(self.long_range)))

        def progress(*args):
            if self.noisy:
                print("|", sep="", end="", flush=True)
            return args

        if nslice is not None:
            return np.asarray(
                [progress(qt.steadystate(ham, self._c_ops())) for ham in list(self.hamiltonian())[nslice]]
            ).T
        else:
            return np.asarray([progress(qt.steadystate(ham, self._c_ops())) for ham in self.hamiltonian()]).T
Ejemplo n.º 24
0
def test_dqd_current():
    "Counting statistics: current and current noise in a DQD model"

    G = 0
    L = 1
    R = 2

    sz = projection(3, L, L) - projection(3, R, R)
    sx = projection(3, L, R) + projection(3, R, L)
    sR = projection(3, G, R)
    sL = projection(3, G, L)

    w0 = 1
    tc = 0.6 * w0
    GammaR = 0.0075 * w0
    GammaL = 0.0075 * w0
    nth = 0.00
    eps_vec = np.linspace(-1.5*w0, 1.5*w0, 20)

    J_ops = [GammaR * sprepost(sR, sR.dag())]

    c_ops = [np.sqrt(GammaR * (1 + nth)) * sR,
             np.sqrt(GammaR * (nth)) * sR.dag(),
             np.sqrt(GammaL * (nth)) * sL,
             np.sqrt(GammaL * (1 + nth)) * sL.dag(),
             ]

    I = np.zeros(len(eps_vec))
    S = np.zeros(len(eps_vec))

    for n, eps in enumerate(eps_vec):
        H = (eps/2 * sz + tc * sx)
        L = liouvillian(H, c_ops)
        rhoss = steadystate(L)
        I[n], S[n] = countstat_current_noise(L, [], rhoss=rhoss, J_ops=J_ops)

        I2 = countstat_current(L, rhoss=rhoss, J_ops=J_ops)
        assert_(abs(I[n] - I2) < 1e-8)

        I2 = countstat_current(L, c_ops, J_ops=J_ops)
        assert_(abs(I[n] - I2) < 1e-8)

    Iref = tc**2 * GammaR / (tc**2 * (2 + GammaR/GammaL) +
                             GammaR**2/4 + eps_vec**2)
    Sref = 1 * Iref * (
        1 - 8 * GammaL * tc**2 *
        (4 * eps_vec**2 * (GammaR - GammaL) +
         GammaR * (3 * GammaL * GammaR + GammaR**2 + 8*tc**2)) /
        (4 * tc**2 * (2 * GammaL + GammaR) + GammaL * GammaR**2 +
         4 * eps_vec**2 * GammaL)**2
    )

    assert_allclose(I, Iref, 1e-4)
    assert_allclose(S, Sref, 1e-4)
Ejemplo n.º 25
0
def test_exact_solution_for_simple_methods(method, kwargs):
    # this tests that simple methods correctly determine the steadystate
    # with high accuracy for a small Liouvillian requiring correct weighting.
    H = qutip.identity(2)
    c_ops = [qutip.sigmam(), 1e-8 * qutip.sigmap()]
    rho_ss = qutip.steadystate(H, c_ops, method=method, **kwargs)
    expected_rho_ss = np.array([
        [1.e-16 + 0.j, 0.e+00 - 0.j],
        [0.e+00 - 0.j, 1.e+00 + 0.j],
    ])
    np.testing.assert_allclose(expected_rho_ss, rho_ss, atol=1e-16)
    assert rho_ss.tr() == pytest.approx(1, abs=1e-14)
Ejemplo n.º 26
0
    def steadystate(self, **kwargs):
        """ Calculates the steady state of the system in the case of a
        time-independent interaction, i.e. if we let time go to infinity.

        Returns:
            rho: The density matrix in the steady state.
        """

        H = self.H_0 + self.H_Delta + self.H_I_sum()
        self.rho = qu.steadystate(H, self.c_ops, **kwargs)

        return self.rho
Ejemplo n.º 27
0
def single_photon_transmissivity(
        hamiltonian: multi_emitter_hamiltonian.MultiEmitterHamiltonian,
        input_freqs: np.ndarray,
        amp_drive: float,
        num_cav_states: int = 4) -> np.ndarray:
    """Computes the single photon transmissivity for the given Hamiltonian.

    This function computes the transmittivity of a multi-emitter using qutip.

    Args:
        hamiltonian: The hamiltonian of the multi-emitter system, specified as a
            multi_emitter_hamiltonian.MultiEmtterHamiltonian object.
        input_freqs: The frequencies (relative to the reference frequency) at
            which to compute the transmission. This should be an array rank 1.
        amp_drive: The amplitude of the coherent drive used for driving the
            cavity mode.
        num_cav_states: The number of Fock states used for describing the
            Hilbert space of the cavity.

    Returns:
        The transmissivity through the multi-emitter system at the specified
        frequencies.

    Raises:
        ValueError: If the `frequencies` is not a one-dimensional array.
    """
    if input_freqs.ndim != 1:
        raise ValueError("Expected the `input_freqs` array to be a 1D array "
                         "instead got {} dimensions".format(input_freqs.ndim))

    # List of transmissions for different frequencies.
    transmissions = []

    for freq in input_freqs:
        # Get the hamiltonian and the operators for cavity and emitters.
        qutip_hamiltonian, annihil_op, sigmas = _setup_qutip_hamiltonian(
            hamiltonian, amp_drive, freq, num_cav_states)

        # Setup the loss operators.
        loss_ops = _setup_loss_operators(hamiltonian, annihil_op, sigmas)

        # Calculate the steady state density matrix.
        density_matrix_ss = qutip.steadystate(qutip_hamiltonian, loss_ops)

        # Calculate the expectation value of the number of photons.
        num_photons = qutip.expect(annihil_op.dag() * annihil_op,
                                   density_matrix_ss)

        # Calculate the transmission.
        norm_factor = hamiltonian.kappa_in * hamiltonian.kappa_out 
        transmissions.append(norm_factor * num_photons / amp_drive**2)

    return np.array(transmissions)
Ejemplo n.º 28
0
def find_expect(vg): #phi=0.1, Omega_vec=3.0):
    phi, Omega=vg#.shape
    Omega_vec=- 0.5j*(Omega*adag - conj(Omega)*a)

    Ej = Ejmax*absolute(cos(pi*phi)) #Josephson energy as function of Phi.

    wTvec = -Ej + sqrt(8.0*Ej*Ec)*(nvec+0.5)+Ecvec #\omega_m

    wT = wTvec-wdvec #rotating frame of gate drive \omega_m-m*\omega_\gate
    transmon_levels = Qobj(diag(wT[range(N)]))
    H=transmon_levels +Omega_vec #- 0.5j*(Omega_true*adag - conj(Omega_true)*a)
    final_state = steadystate(H, c_op_list) #solve master equation

    return expect( a, final_state) #expectation value of relaxation operator
Ejemplo n.º 29
0
    def find_expect(vg, self=a): #phi=0.1, Omega_vec=3.0):
            phi, Omega=vg#.shape
            Omega_vec=-0.5j*(Omega*self.a_dag - conj(Omega)*self.a_op)

            Ej = self.Ejmax*absolute(cos(pi*phi)) #Josephson energy as function of Phi.

            wTvec = (-Ej + sqrt(8.0*Ej*self.Ec)*(self.nvec+0.5)+self.Ecvec)/h #\omega_m

            wT = wTvec-a.fdvec #rotating frame of gate drive \omega_m-m*\omega_\gate
            transmon_levels = Qobj(diag(wT[range(self.N_dim)]))
            H=transmon_levels +Omega_vec #- 0.5j*(Omega_true*adag - conj(Omega_true)*a)
            final_state = steadystate(H, self.c_ops) #solve master equation

            return expect( self.a_op, final_state) #expectation value of relaxation operator
Ejemplo n.º 30
0
def test_driven_cavity_power_bicgstab():
    "Steady state: Driven cavity - power-bicgstab solver"

    N = 30
    Omega = 0.01 * 2 * np.pi
    Gamma = 0.05

    a = destroy(N)
    H = Omega * (a.dag() + a)
    c_ops = [np.sqrt(Gamma) * a]
    M = build_preconditioner(H, c_ops, method='power')
    rho_ss = steadystate(H, c_ops, method='power-bicgstab', M=M, use_precond=1)
    rho_ss_analytic = coherent_dm(N, -1.0j * (Omega) / (Gamma / 2))
    assert_((rho_ss - rho_ss_analytic).norm() < 1e-4)
Ejemplo n.º 31
0
def test_driven_cavity_power_bicgstab():
    "Steady state: Driven cavity - power-bicgstab solver"

    N = 30
    Omega = 0.01 * 2 * np.pi
    Gamma = 0.05

    a = destroy(N)
    H = Omega * (a.dag() + a)
    c_ops = [np.sqrt(Gamma) * a]
    M = build_preconditioner(H, c_ops, method='power')
    rho_ss = steadystate(H, c_ops, method='power-bicgstab', M=M, use_precond=1)
    rho_ss_analytic = coherent_dm(N, -1.0j * (Omega)/(Gamma/2))
    assert_((rho_ss - rho_ss_analytic).norm() < 1e-4)
Ejemplo n.º 32
0
def test_driven_cavity(method, kwargs):
    N = 30
    Omega = 0.01 * 2 * np.pi
    Gamma = 0.05

    a = qutip.destroy(N)
    H = Omega * (a.dag() + a)
    c_ops = [np.sqrt(Gamma) * a]
    if 'use_precond' in kwargs:
        kwargs['M'] = qutip.build_preconditioner(H, c_ops, method=kwargs['M'])
    rho_ss = qutip.steadystate(H, c_ops, method=method, **kwargs)
    rho_ss_analytic = qutip.coherent_dm(N, -1.0j * (Omega) / (Gamma / 2))

    np.testing.assert_allclose(rho_ss, rho_ss_analytic, atol=1e-4)
Ejemplo n.º 33
0
def additive_populations_and_current_vs_voltage(PARAMS, x_range=[0.6,1.6], num_voltages=35):
    ti = time.time()
    if PARAMS['T_L']<100:
        number_of_voltages = int(1.8*num_voltages)
    else:
        number_of_voltages = num_voltages
    #bias_voltages = np. linspace(x_range[0]*ev_to_inv_cm, x_range[1]*ev_to_inv_cm, number_of_voltages)
    bias_voltages = np.concatenate((np.array([0]), 
                    np.linspace(x_range[0]*ev_to_inv_cm, x_range[1]*ev_to_inv_cm, number_of_voltages)), 
                                   axis=0)
    current = []
    conduction_population = []
    valence_population = []
    ground_population = []
    hole_population = []
    electron_population = []
    exciton_population = []
    CC_population = []
    ops = make_expectation_operators(PARAMS)
    for i, bv in enumerate(bias_voltages):
        PARAMS.update({'mu_R': PARAMS['mu']+bv/2, 'mu_L': PARAMS['mu']-bv/2})
        #if i in [10, 90]:
        #    print_PARAMS(PARAMS)
        L_Lindblad_dict = build_L(PARAMS, silent=True)
        #ops = make_expectation_operators(PARAMS)
        n_c = tensor(d_e.dag()*d_e, qeye(PARAMS['N']))
        n_v = tensor(d_h.dag()*d_h, qeye(PARAMS['N']))
        ss = steadystate(L_Lindblad_dict['H_S'], [L_Lindblad_dict['L_add_EM']])
        current.append(current_from_ss(ss, L_Lindblad_dict['L_R'], n_c))
        conduction_population.append((n_c*ss).tr())
        valence_population.append((n_v*ss).tr())
        ground_population.append((ops['vac']*ss).tr())
        hole_population.append((ops['hole']*ss).tr())
        electron_population.append((ops['electron']*ss).tr())
        exciton_population.append((ops['exciton']*ss).tr())
        CC_population.append((ops['CC_pop']*ss).tr())
    bias_voltages/=ev_to_inv_cm
    data_dict = {'bias_voltages':bias_voltages, 
                 'current': current,
                 'conduction_population' : conduction_population, 
                 'valence_population' : valence_population,
                 'ground_population': ground_population,
                 'hole_population' : hole_population,
                 'electron_population' : electron_population,
                 'exciton_population' : exciton_population,
                 'CC_population' : CC_population,
                'PARAMS': PARAMS}
    print("C-V data calculated in {:0.1f} seconds".format(time.time() - ti))
    return data_dict
Ejemplo n.º 34
0
    def rhos(self, nslice=None):
        '''rho
        return steadystate density matrices'''
        self.precalc = True

        if self.noisy:
            print('N = {}, len() = {}'.format(self.N_field_levels,
                                              len(self.long_range)))

        def progress(*args):
            if self.noisy:
                print('|', sep='', end='', flush=True)
            return args

        if nslice is not None:
            return np.asarray([
                progress(qt.steadystate(ham, self._c_ops()))
                for ham in list(self.hamiltonian())[nslice]
            ]).T
        else:
            return np.asarray([
                progress(qt.steadystate(ham, self._c_ops()))
                for ham in self.hamiltonian()
            ]).T
Ejemplo n.º 35
0
def test_driven_cavity_lgmres():
    "Steady state: Driven cavity - iterative-lgmres solver"

    N = 30
    Omega = 0.01 * 2 * np.pi
    Gamma = 0.05

    a = destroy(N)
    H = Omega * (a.dag() + a)
    c_ops = [np.sqrt(Gamma) * a]

    rho_ss = steadystate(H, c_ops, method='iterative-lgmres')
    rho_ss_analytic = coherent_dm(N, -1.0j * (Omega)/(Gamma/2))

    assert_((rho_ss - rho_ss_analytic).norm() < 1e-4)
Ejemplo n.º 36
0
def find_expect(vg):
    phi, Omega = vg
    H = make_H(phi, Omega, wdvec, 0.0)
    #Omega_op=- 0.5j*(Omega*adag - conj(Omega)*a)

    #Ej = Ejmax*absolute(cos(pi*phi)) #Josephson energy as function of Phi.

    #wTvec = -Ej + sqrt(8.0*Ej*Ec)*(nvec+0.5)+Ecvec

    #wT = wTvec-wdvec
    #transmon_levels = Qobj(diag(wT[range(N)]))
    #H=transmon_levels +Omega_op
    final_state = steadystate(H, c_op_list)

    return expect(a, final_state)
Ejemplo n.º 37
0
def test_driven_cavity_bicgstab():
    "Steady state: Driven cavity - iterative-bicgstab solver"

    N = 30
    Omega = 0.01 * 2 * np.pi
    Gamma = 0.05

    a = destroy(N)
    H = Omega * (a.dag() + a)
    c_ops = [np.sqrt(Gamma) * a]

    rho_ss = steadystate(H, c_ops, method='iterative-bicgstab')
    rho_ss_analytic = coherent_dm(N, -1.0j * (Omega) / (Gamma / 2))

    assert_((rho_ss - rho_ss_analytic).norm() < 1e-4)
Ejemplo n.º 38
0
    def find_expect(vg, self=a):  #phi=0.1, Omega_vec=3.0):
        phi, Omega = vg  #.shape
        Omega_vec = -0.5j * (Omega * self.a_dag - conj(Omega) * self.a_op)

        Ej = self.Ejmax * absolute(cos(
            pi * phi))  #Josephson energy as function of Phi.

        wTvec = (-Ej + sqrt(8.0 * Ej * self.Ec) *
                 (self.nvec + 0.5) + self.Ecvec) / h  #\omega_m

        wT = wTvec - a.fdvec  #rotating frame of gate drive \omega_m-m*\omega_\gate
        transmon_levels = Qobj(diag(wT[range(self.N_dim)]))
        H = transmon_levels + Omega_vec  #- 0.5j*(Omega_true*adag - conj(Omega_true)*a)
        final_state = steadystate(H, self.c_ops)  #solve master equation

        return expect(self.a_op,
                      final_state)  #expectation value of relaxation operator
Ejemplo n.º 39
0
    def jc_steadystate(self, N, wc, wa, g, kappa, gamma,
                       pump, psi0, use_rwa, tlist):

        # Hamiltonian
        a = tensor(destroy(N), identity(2))
        sm = tensor(identity(N), destroy(2))

        if use_rwa:
            # use the rotating wave approxiation
            H = wc * a.dag(
            ) * a + wa * sm.dag() * sm + g * (a.dag() * sm + a * sm.dag())
        else:
            H = wc * a.dag() * a + wa * sm.dag() * sm + g * (
                a.dag() + a) * (sm + sm.dag())

        # collapse operators
        c_op_list = []

        n_th_a = 0.0  # zero temperature

        rate = kappa * (1 + n_th_a)
        c_op_list.append(np.sqrt(rate) * a)

        rate = kappa * n_th_a
        if rate > 0.0:
            c_op_list.append(np.sqrt(rate) * a.dag())

        rate = gamma
        if rate > 0.0:
            c_op_list.append(np.sqrt(rate) * sm)

        rate = pump
        if rate > 0.0:
            c_op_list.append(np.sqrt(rate) * sm.dag())

        # find the steady state
        rho_ss = steadystate(H, c_op_list)

        return expect(a.dag() * a, rho_ss), expect(sm.dag() * sm, rho_ss)
Ejemplo n.º 40
0
def _spectrum_pi(H, wlist, c_ops, a_op, b_op, use_pinv=False):
    """
    Internal function for calculating the spectrum of the correlation function
    :math:`\left<A(\\tau)B(0)\\right>`.
    """

    #print issuper(H)

    L = H if issuper(H) else liouvillian(H, c_ops)

    tr_mat = tensor([qeye(n) for n in L.dims[0][0]])
    N = prod(L.dims[0][0])

    A = L.full()
    b = spre(b_op).full()
    a = spre(a_op).full()

    tr_vec = transpose(mat2vec(tr_mat.full()))

    rho_ss = steadystate(L)
    rho = transpose(mat2vec(rho_ss.full()))

    I = identity(N * N)
    P = kron(transpose(rho), tr_vec)
    Q = I - P

    spectrum = zeros(len(wlist))

    for idx, w in enumerate(wlist):
        if use_pinv:
            MMR = pinv(-1.0j * w * I + A)
        else:
            MMR = dot(Q, solve(-1.0j * w * I + A, Q))

        s = dot(tr_vec,
                   dot(a, dot(MMR, dot(b, transpose(rho)))))
        spectrum[idx] = -2 * real(s[0, 0])

    return spectrum
Ejemplo n.º 41
0
def find_expect(phi=0.1, Omega_vec=3.0, wd=wd):

    wdvec=nvec*wd

    Ej = Ejmax*absolute(cos(pi*phi)) #; % Josephson energy as function of Phi.
    wq0=sqrt(8*Ej*Ec)
    X=Np*pi*(wq0-f0)/f0
    Ba=-1*gamma*(sin(2.0*X)-2.0*X)/(2.0*X**2.0)
    Ecp=Ec*(1-2*Ba/wq0)
    Ecvec=-Ecp*(6.0*nvec**2+6.0*nvec+3.0)/12.0

    wTvec = -Ej + sqrt(8.0*Ej*Ecp)*(nvec+0.5)+Ecvec


    #print diff(wTvec)
    if phi==0.4:
        print Ba/wq0
    if 0:
        zr=zeros(N)
        X=Np*pi*(diff(wTvec)-f0)/f0
        Ba=-0*gamma*(sin(2.0*X)-2.0*X)/(2.0*X**2.0)
        ls=-Ba#/(2*Ct)/(2*pi)#/1e6
        zr[1:]=ls
        #print Ga0/(2*Ct)/(2*pi)
        #print zr
        wTvec=wTvec+zr
    wTvec = wTvec-wdvec

    #print wTvec+diff(wTvec)


    transmon_levels = Qobj(diag(wTvec[range(N)]))

    H=transmon_levels +Omega_vec #- 0.5j*(Omega_true*adag - conj(Omega_true)*a)
    final_state = steadystate(H, c_op_list)

    return expect( tm_l, final_state)
Ejemplo n.º 42
0
# Calculating steady-state solutions using the qutip library

def H(w):
    """ Hamiltonian of a spin 1/2 in B0 + Brf using the RWA. """
    return (w0 - w)/2 * qt.sigmaz() + w1/2 * qt.sigmax()

# Collsapse operators which should describe the relaxation of the system
c1 = np.sqrt(1.0/T1) * qt.destroy(2)
c2 = np.sqrt(1.0/T2)/2 * qt.destroy(2)
c3 = np.sqrt(1.0/(T1*T2)) * qt.destroy(2)
c4 = np.sqrt(1.0/T2) /2 * qt.create(2)
c5 = np.sqrt(1.0/(T1*T2)) * qt.create(2)


wHVals = np.linspace(-2 * np.pi, 6 * np.pi, 31)
MxH = [qt.expect(qt.sigmax(), qt.steadystate(H(w), [c1,c2,c3], maxiter=10)) for w in wHVals]
MyH = [qt.expect(qt.sigmay(), qt.steadystate(H(w), [c2,c5], maxiter=10)) for w in wHVals]
MzH = [qt.expect(qt.sigmaz(), qt.steadystate(H(w), [c1], maxiter=10)) for w in wHVals]

wVals = np.linspace(-2 * np.pi, 6 * np.pi, 100)

# Plot results of the algebraic formula and the solution given by qutip

plt.ylim([-1.0, 1.0])

plt.plot(wVals, Mx(wVals), label='Mx')
plt.plot(wVals, My(wVals), label='My')
plt.plot(wVals, Mz(wVals), label='Mz')

plt.plot(wHVals, MxH, 'bo', label='MxH')
plt.plot(wHVals, MyH, 'go', label='MyH')
Ejemplo n.º 43
0
wVals = np.linspace(-2 * np.pi, 6 * np.pi, 100)

# Solving the dynamics of a spin 1/2 in B0 and Brf in the lab frame

def H(w):
    """ Hamiltonian in the lab frame. """
    return w0 / 2 * qt.sigmaz() + w1 * np.cos(w) * qt.sigmax()

c1 = np.sqrt(1.0/T1) * qt.destroy(2)
c2 = np.sqrt(1.0/T2) / 2 * qt.destroy(2)
c_op_list = [c1,c2]


wHVals = np.linspace(-2 * np.pi, 6 * np.pi, 51)
MxH = [qt.expect(qt.sigmax(), qt.steadystate(H(w), c_op_list, maxiter=100)) for w in wHVals]
MyH = [qt.expect(qt.sigmay(), qt.steadystate(H(w), c_op_list, maxiter=100)) for w in wHVals]
MzH = [qt.expect(qt.sigmaz(), qt.steadystate(H(w), c_op_list, maxiter=100)) for w in wHVals]


# Plot results of the algebraic formula and the solution given by qutip

plt.ylim([-1.0, 1.0])

plt.plot(wVals, Mx(wVals), label='Mx')
plt.plot(wVals, My(wVals), label='My')
plt.plot(wVals, Mz(wVals), label='Mz')

plt.plot(wHVals, MxH, 'bo', label='MxH')
plt.plot(wHVals, MyH, 'go', label='MyH')
plt.plot(wHVals, MzH, 'ro', label='MzH')
Ejemplo n.º 44
0
def two_tone(vg):
    phi, wd=vg
    Ej = Ejmax*absolute(cos(pi*phi))#(phi**2)/(8*Ec) # #; % Josephson energy as function of Phi.

    wTvec = -Ej + sqrt(8.0*Ej*Ec)*(nvec+0.5)+Ecvec
    wdvec=nvec*wd
    wT = wTvec-wdvec

    transmon_levels = Qobj(diag(wT[range(N)]))
    

    for Om in Omega_op:
        H = transmon_levels + Om
        exp1=spectrum(H, wlist2, c_op_list, a, p, solver="pi", use_pinv=False)
        exp2=spectrum(H, wlist2, c_op_list, p, a, solver="pi", use_pinv=False)
        return exp1-exp2


        #H_comm = -1j*(kron(It,H) - kron(transpose(H),It));

        #L = H_comm + Lindblad_tm + Lindblad_tp #+ Lindblad_deph;

        #print L

        #L2 = [reshape(eye(N),1,N**2); L]; %Add the condition trace(rho) = 1

        #rho_ss = L2\[1;zeros(dim^2,1)]; % Steady state density matrix

        #rho_ss_c = rho_ss; %Column vector form
        L = liouvillian(H, c_op_list)

        #D, V=L.eigenstates()
        #print "D", D.shape
        #print "V", V.shape
        #print L.diag()
        #print L.diag().shape
        #raise Exception
        A = L.full()

        rho_ss = steadystate(L)
        rho = transpose(mat2vec(rho_ss.full()))
        P = kron(transpose(rho), tr_vec)
        Q = I - P

        if 1:
            w=wp-wd
            #MMR = pinv(-1.0j * w * I + A)
            MMR = dot(Q, solve(-1.0j * w * I + A, Q))

            #Lexp=L.expm()
            #MMR=Lexp*MMR*Lexp.dag()
            #    MMR = np.dot(Q, np.linalg.solve(-1.0j * w * I + A, Q))

            #print p_l.shape
            #print p_l
            #print transpose(rho).shape

            #print dot(p_l.full(), transpose(rho))
            s = dot(tr_vec,
                       dot(tm_l, dot(MMR, dot(p_l_m_p_r, transpose(rho)))))
            return -2 * real(s[0, 0])
        D,U = eig(L.full())

        Uinv = inv(U)

        Dint = diag(1.0/(1.0j*(wp-wd)*Idiag + diag(D)))

        Lint = U*Dint*Uinv


        #H_comm = -1.0j*(kron(It,H) - kron(transpose(H),It))


        #print H
        #print H.shape, H.full().shape
        #print H_comm, H_comm.shape
        #L = H_comm + Lindblad_tm + Lindblad_tp + Lindblad_deph
        #p_l=spre(p)
        #p_r=spost(p)
        #tm_l=spre(a)
        #print L.shape, A.shape,
        #print dir(L)
        #print L.eigenenergies().shape
        #print L.eigenstates()#.shape
        #L2 = [reshape(eye(dim),1,dim^2);L]; %Add the condition trace(rho) = 1
        #rho_ss = L2\[1;zeros(dim^2,1)]; % Steady state density matrix
        #rho_ss_c = rho_ss; %Column vector form

        #print "tm_l", tm_l.full().shape
        #print "Lint", Lint.shape
        #print "pl", p_l.full().shape
        #print "pr", p_r.full().shape
        #print rho.shape, to_super(rho_ss).full().shape
        #print "rho", to_super(rho_ss) #rho_ss.full().shape #rho.shape
        #print (tm_l.full()*Lint*(p_l.full() - p_r.full())*rho).shape
        #raise Exception
        return 1j*trace(tm_l*Lint*(p_l_m_p_r)*rho_ss)
Ejemplo n.º 45
0
print Omega_vec
H=transmon_levels +Omega_vec #- 0.5j*(Omega_true*adag - conj(Omega_true)*a)
print H
#Ht = H.data.T
#from qutip.cy.spmath import zcsr_kron

#from qutip.fastsparse import fast_csr_matrix, fast_identity
#spI=fast_identity(N)
#data = -1j * zcsr_kron(spI, H.data)
#data += 1j * zcsr_kron(Ht, spI)
#print data.toarray()
L=liouvillian(H, c_op_list) #ends at same thing as L = H_comm + Lindblad_tm ;
#print L
#print dir(L)

rho_ss = steadystate(L) #same as rho_ss_c but that's in column vector form
print rho_ss

wlist = linspace(-500.0, 500.0, 201)

use_pinv=True

tr_mat = tensor([qeye(n) for n in L.dims[0][0]])
N = prod(L.dims[0][0])

A = L.full()
D, U= L.eigenstates()
print D.shape, D
print diag(D)
b = spre(p).full()-spost(p).full()
a = spre(a).full()
Ejemplo n.º 46
0
def find_expect(phi=0.1, Omega_vec=3.0, wd=wd, use_pinv=True):

    Ej = (phi**2)/(8*Ec) #Ejmax*absolute(cos(pi*phi)) #; % Josephson energy as function of Phi.

    wTvec = -Ej + sqrt(8.0*Ej*Ec)*(nvec+0.5)+Ecvec

    #wdvec=nvec*sqrt(8.0*Ej*Ec)
    #wdvec=nvec*wd

    wT = wTvec-wdvec
    transmon_levels = Qobj(diag(wT[range(N)]))
    H=transmon_levels +Omega_vec #- 0.5j*(Omega_true*adag - conj(Omega_true)*a)
    L=liouvillian(H, c_op_list) #ends at same thing as L = H_comm + Lindblad_tm ;
    rho_ss = steadystate(L) #same as rho_ss_c but that's in column vector form

    tr_mat = tensor([qeye(n) for n in L.dims[0][0]])
    #N = prod(L.dims[0][0])

    A = L.full()
    #D, U= L.eigenstates()
    #print D.shape, D
    #print diag(D)
    b = spre(p).full()-spost(p).full()
    a2 = spre(a).full()

    tr_vec = transpose(mat2vec(tr_mat.full()))

    rho = transpose(mat2vec(rho_ss.full()))

    I = identity(N * N)
    P = kron(transpose(rho), tr_vec)
    Q = I - P

    #wp=4.9
    #w=-(wp-wd)
    spectrum = zeros(len(wlist2), dtype=complex)
    for idx, w in enumerate(wlist2):

        if use_pinv:
            MMR = pinv(-1.0j * w * I + A) #eig(MMR)[0] is equiv to Dint
        else:
            MMR = dot(Q, solve(-1.0j * w * I + A, Q))
    #print diag(1.0/(1j*(wp-wd)*ones(N**2)+D)) #Dint = diag(1./(1i*(wp-wd)*diag(eye(dim^2)) + diag(D)))

    #print 1.0/(1j*(wp-wd)*ones(N**2)+D) #Dint = diag(1./(1i*(wp-wd)*diag(eye(dim^2)) + diag(D)))
    #U2=squeeze([u.full() for u in U]).transpose()
    #Dint=eig(MMR)[0]
    #print "MMR", eig(MMR)[1]
    #print "Umult", U2*Dint*inv(U2)

        s = dot(tr_vec,
            dot(a2, dot(MMR, dot(b, transpose(rho)))))
        #spectrum[idx] = -2 * real(s[0, 0])
        spectrum[idx]=1j*s[0][0] #matches Chi_temp result #(1/theta_steps)
    return spectrum
    #final_state = steadystate(H, c_op_list)
    #print H.shape
    #print dir(H)
    #U,D = eig(H.full())
    #print D
    #Uinv = Qobj(inv(D))
    #U=Qobj(D)
    # Doing the chi integral (gives the susceptibility)

    #Dint = 1.0/(1.0j*(wp-wd)) #Qobj(1.0/(1.0j*(wp-wd)*diag(qeye(N**2))))# + diag(D))))

    #Hint = H.expm() #U*H*Uinv

    #Chi_temp(i,j) += (1.0/theta_steps)*1j*trace(reshape(tm_l*Lint*(p_l - p_r)*rho_ss_c,dim,dim))
    #exp1=correlation_2op_1t(H, None, wlist2, c_op_list, a, p, solver="es")
    #exp2=correlation_2op_1t(H, None, wlist2, c_op_list, p, a, solver="es", reverse=True)
    #exp1=correlation_2op_1t(H, None, wlist2, c_op_list, a, p_l-p_r, solver="es")

    #exp1=correlation_ss(H, wlist2, c_op_list, a, p)
    #exp2=correlation_ss(H, wlist2, c_op_list, p, a, reverse=True)
    exp1=spectrum(H, wlist2, c_op_list, a, p, solver="pi", use_pinv=False)
    exp2=spectrum(H, wlist2, c_op_list, p, a, solver="pi", use_pinv=False)
    return exp1-exp2
    return expect( a, final_state) #tm_l