Exemplo n.º 1
0
def test_liouvillian():
    """Test conversion of Hamiltonian/Lindblad operators into a Liouvillian"""
    H = [
        tensor(sigmaz(), identity(2)) + tensor(identity(2), sigmaz()),
        [tensor(sigmax(), identity(2)), lambda t, args: 1.0],
        [tensor(identity(2), sigmax()), lambda t, args: 1.0],
    ]
    c_ops = [tensor(sigmam(), identity(2)), tensor(identity(2), sigmam())]

    assert (
        krotov.objectives.liouvillian(H[0], c_ops)
        - qutip.liouvillian(H[0], c_ops)
    ).norm('max') < 1e-15

    L = krotov.objectives.liouvillian(H, c_ops)
    assert isinstance(L, list)
    assert len(L) == 3
    assert (L[0] - qutip.liouvillian(H[0], c_ops)).norm('max') < 1e-15
    assert (L[1][0] - qutip.liouvillian(H[1][0])).norm('max') < 1e-15
    assert (L[2][0] - qutip.liouvillian(H[2][0])).norm('max') < 1e-15
    assert L[1][1] is H[1][1]
    assert L[2][1] is H[2][1]

    with pytest.raises(ValueError):
        krotov.objectives.liouvillian(tuple(H), c_ops)
Exemplo n.º 2
0
def liouvillian(omega, g, gamma, beta):
    """Liouvillian for the coupled system of qubit and TLS"""

    H0_q = omega*0.5*(-qutip.operators.sigmaz()+qutip.qeye(2))
    # drive qubit Hamiltonian
    H1_q = -0.5*qutip.operators.sigmax()

    # drift TLS Hamiltonian
    H0_T = qutip.tensor(omega*0.5*(-qutip.operators.sigmaz()+qutip.qeye(2)), qutip.qeye(2), qutip.qeye(2), qutip.qeye(2), qutip.qeye(2))\
                        +qutip.tensor(qutip.qeye(2), omega*0.5*(-qutip.operators.sigmaz()+qutip.qeye(2)), qutip.qeye(2), qutip.qeye(2), qutip.qeye(2))\
                        +qutip.tensor(qutip.qeye(2), qutip.qeye(2), omega*0.5*(-qutip.operators.sigmaz()+qutip.qeye(2)), qutip.qeye(2), qutip.qeye(2))\
                        +qutip.tensor(qutip.qeye(2), qutip.qeye(2), qutip.qeye(2), omega*0.5*(-qutip.operators.sigmaz()+qutip.qeye(2)), qutip.qeye(2))\
                        +qutip.tensor(qutip.qeye(2), qutip.qeye(2), qutip.qeye(2), qutip.qeye(2), omega*0.5*(-qutip.operators.sigmaz() + qutip.qeye(2)))

    # Lift Hamiltonians to joint system operators
    H0 = qutip.tensor(H0_q, qutip.qeye(2), qutip.qeye(2), qutip.qeye(2), qutip.qeye(2), qutip.qeye(2)) + qutip.tensor(qutip.qeye(2), H0_T)
    H1 = qutip.tensor(H1_q, qutip.qeye(2), qutip.qeye(2), qutip.qeye(2), qutip.qeye(2), qutip.qeye(2))

    # qubit-TLS interaction
    H_int =  g*(qutip.tensor(qutip.destroy(2),qutip.create(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2))\
                +qutip.tensor(qutip.create(2),qutip.destroy(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2))\
                +qutip.tensor(qutip.destroy(2),qutip.qeye(2),qutip.create(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2))\
                +qutip.tensor(qutip.create(2),qutip.qeye(2),qutip.destroy(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2))\
                +qutip.tensor(qutip.destroy(2),qutip.qeye(2),qutip.qeye(2),qutip.create(2),qutip.qeye(2),qutip.qeye(2))\
                +qutip.tensor(qutip.create(2),qutip.qeye(2),qutip.qeye(2),qutip.destroy(2),qutip.qeye(2),qutip.qeye(2))\
                +qutip.tensor(qutip.destroy(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2),qutip.create(2),qutip.qeye(2))\
                +qutip.tensor(qutip.create(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2),qutip.destroy(2),qutip.qeye(2))\
                +qutip.tensor(qutip.destroy(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2),qutip.create(2))\
                +qutip.tensor(qutip.create(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2),qutip.destroy(2)))

    # convert Hamiltonians to QuTiP objects
    H0 = qutip.Qobj(H0 + H_int)
    H1 = qutip.Qobj(H1)

    # Define Lindblad operators
    N = 1.0 / (np.exp(beta * omega) - 1.0)
    # Cooling on TLS
    L1 = np.sqrt(gamma * (N + 1)) * qutip.tensor(qutip.destroy(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2))
    # Heating on TLS
    L2 = np.sqrt(gamma * N) *qutip.tensor(qutip.create(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2),qutip.qeye(2))
    

    # convert Lindblad operators to QuTiP objects
    L1 = qutip.Qobj(L1)
    L2 = qutip.Qobj(L2)

    # generate the Liouvillian
    L0 = qutip.liouvillian(H=H0, c_ops=[L1, L2])
    L1 = qutip.liouvillian(H=H1)

    # Shift the qubit and TLS into resonance by default
    eps0 = lambda t, args: 1
    return [L0, [L1, eps0]]
Exemplo n.º 3
0
def liouvillian(omega, g, gamma, beta,n,amp):
    """Liouvillian for the coupled system of qubit and TLS"""
    A=np.zeros((n,n))
    B=np.zeros((n,n))
    Mu=np.zeros((n,n))
    for i in range (n):
      for j in range (n):
        if j-i==1:
          A[i,j]=0.5
        elif i-j==1:
          B[i,j]=0.5
    Mu=A+B

    H0_q = qutip.Qobj(omega*np.array(np.dot(qutip.create(n),qutip.destroy(n))))
    # drive qubit Hamiltonian
    H1_q = omega*Mu 

    # drift TLS Hamiltonian
    H0_T = omega*np.array(np.dot(qutip.create(n),qutip.destroy(n)))

    # Lift Hamiltonians to joint system operators
    H0 = np.kron(H0_q, np.identity(n)) + np.kron(np.identity(n), H0_T)
    H1 = np.kron(H1_q, np.identity(n))

    # qubit-TLS interaction
    H_int =  g*(np.kron(np.array(qutip.create(n)),np.array(qutip.destroy(n)))+np.kron(np.array(qutip.destroy(n)),np.array(qutip.create(n))))

    # convert Hamiltonians to QuTiP objects
    H0 = qutip.Qobj(H0 + H_int)
    H1 = qutip.Qobj(H1)

    # Define Lindblad operators
    N = 1.0 / (np.exp(beta * omega) - 1.0)
    
    L=[]
    k=0
    for i in range (0,n-1):
    # Cooling on TLS
      L.append(np.sqrt(gamma * (N + 1)) * np.kron(np.array(qutip.basis(n,i)*qutip.basis(n,i+1).dag()),np.identity(n)))
      L.append(np.sqrt(gamma * N) * np.kron(np.array(qutip.basis(n,i+1)*qutip.basis(n,i).dag()),np.identity(n)))
      L[k]=qutip.Qobj(L[k])
      L[k+1]=qutip.Qobj(L[k+1])
      k=2*(i+1)
    # convert Lindblad operators to QuTiP objects

    # generate the Liouvillian

    L0 = qutip.liouvillian(H=H0, c_ops=L)
    L1 = qutip.liouvillian(H=H1)

    # Shift the qubit and TLS into resonance by default
    eps0 = lambda t, args: amp
    return [L0, [L1, eps0]]
Exemplo n.º 4
0
def test_dissipation_superop(tmpdir, request, H0, L1, L2):
    """Test that we can add a dissipatio superoperator as an alternative to
    Lindblad operators"""
    filename = request.module.__file__
    test_dir, _ = os.path.splitext(filename)

    model = LevelModel()
    model.add_ham(H0)
    model.add_lindblad_op(L1)
    model.add_lindblad_op(L2)

    D = qutip.liouvillian(H=None, c_ops=[qutip.Qobj(L1), qutip.Qobj(L2)])
    with pytest.raises(ValueError):
        model.set_dissipator(D)

    model._lindblad_ops = []
    model.set_dissipator(D)

    with pytest.raises(ValueError):
        model.add_lindblad_op(L1)

    model.write_to_runfolder(str(tmpdir.join('model_rf')),
                             config='dissipator.config')

    assert filecmp.cmp(
        os.path.join(test_dir, 'dissipator.config'),
        str(tmpdir.join('model_rf', 'dissipator.config')),
        shallow=False,
    )
Exemplo n.º 5
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
Exemplo n.º 6
0
def time_evolution(H_vec, c_ops, sim_step):
    '''
    Arguments:
        H:        list of Hamiltonians at different times, each on for a time = sim_step
        c_ops:  list of collapse operators. if an element of the list is a single operator, then it is a time-independent one,
                otherwise, if it's a 2-list, then the first el. is the operator and the second one is a list of time-dependent coefficients.
                Note that in the first case the coefficient is included in the operator
        sim_step:  time for which each H[t] is on.

    '''

    exp_L_total = 1
    for i in range(len(H_vec)):
        H = H_vec[i]
        if c_ops != []:
            c_ops_temp = []
            for c in range(len(c_ops)):
                if isinstance(c_ops[c], list):
                    c_ops_temp.append(
                        c_ops[c][0] *
                        c_ops[c][1][i])  # c_ops are already in the H_0 basis
                else:
                    c_ops_temp.append(c_ops[c])
            liouville_exp_t = (qtp.liouvillian(H, c_ops_temp) *
                               sim_step).expm()
        else:
            liouville_exp_t = (-1j * H * sim_step).expm()
        exp_L_total = liouville_exp_t * exp_L_total

    return exp_L_total
def time_evolution_squarepulse(H, c_ops, time, initial_propagator=1):
    '''scalefactor=1e6
    tlist_sim=tlist_sim*scalefactor
    eps_vec=eps_vec/scalefactor
    H_0=H_0/scalefactor
    if c_ops!=[]:       # c_ops is a list of either operators or lists where the first element is
                                    # an operator and the second one is a list of the (time-dependent) coefficients
        for c in range(len(c_ops)):
            if isinstance(c_ops[c],list):
                c_ops[c][1]=c_ops[c][1]/np.sqrt(scalefactor)
            else:
                c_ops[c]=c_ops[c]/np.sqrt(scalefactor)'''

    exp_L_total = initial_propagator
    '''
    if isinstance(tlist_sim,list):
        length_tlist=len(tlist_sim)
    else:
    	length_tlist=np.size(tlist_sim)'''
    c_ops_temp = list()
    if c_ops != []:
        for c in range(len(c_ops)):
            if isinstance(c_ops[c], list):
                c_ops_temp.append(c_ops[c][0] * c_ops[c][1][i])
            else:
                c_ops_temp.append(c_ops[c])
        liouville_exp_t = (qtp.liouvillian(H, c_ops_temp) * time).expm()
    else:
        liouville_exp_t = (-1j * H * time).expm()
    exp_L_total = liouville_exp_t * exp_L_total

    return exp_L_total
Exemplo n.º 8
0
def test_dissipation_superop(tmpdir, request, H0, L1, L2):
    """Test that we can add a dissipatio superoperator as an alternative to
    Lindblad operators"""
    filename = request.module.__file__
    test_dir, _ = os.path.splitext(filename)

    model = LevelModel()
    model.add_ham(H0)
    model.add_lindblad_op(L1)
    model.add_lindblad_op(L2)

    D = qutip.liouvillian(H=None, c_ops=[qutip.Qobj(L1), qutip.Qobj(L2)])
    with pytest.raises(ValueError):
        model.set_dissipator(D)

    model._lindblad_ops = []
    model.set_dissipator(D)

    with pytest.raises(ValueError):
        model.add_lindblad_op(L1)

    model.write_to_runfolder(
        str(tmpdir.join('model_rf')), config='dissipator.config'
    )

    assert filecmp.cmp(
        os.path.join(test_dir, 'dissipator.config'),
        str(tmpdir.join('model_rf', 'dissipator.config')),
        shallow=False,
    )
Exemplo n.º 9
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())
Exemplo n.º 10
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)
Exemplo n.º 11
0
def generator(k,H,L1,L2):
    """
    Create the generator for the cascaded chain of k system copies
    """
    # create bare operators
    id = qt.qeye(H.dims[0][0])
    Id = qt.spre(id)*qt.spost(id)
    Hlist = []
    L1list = []
    L2list = []
    for l in range(1,k+1):
        h = H
        l1 = L1
        l2 = L2
        for i in range(1,l):
            h = qt.tensor(h,id)
            l1 = qt.tensor(l1,id)
            l2 = qt.tensor(l2,id)
        for i in range(l+1,k+1):
            h = qt.tensor(id,h)
            l1 = qt.tensor(id,l1)
            l2 = qt.tensor(id,l2)
        Hlist.append(h)
        L1list.append(l1)
        L2list.append(l2)
    # create Lindbladian
    L = qt.Qobj()
    H0 = 0.5*Hlist[0]
    L0 = L2list[0]
    #L0 = 0.*L2list[0]
    L += qt.liouvillian(H0,[L0])
    E0 = Id
    for l in range(k-1):
        E0 = qt.composite(Id,E0)
        Hl = 0.5*(Hlist[l]+Hlist[l+1]+1j*(L1list[l].dag()*L2list[l+1] 
                                          -L2list[l+1].dag()*L1list[l]))
        Ll = L1list[l] + L2list[l+1]
        L += qt.liouvillian(Hl,[Ll])
    Hk = 0.5*Hlist[k-1]
    Hk = 0.5*Hlist[k-1]
    Lk = L1list[k-1]
    L += qt.liouvillian(Hk,[Lk])
    E0.dims = L.dims
    return L,E0
Exemplo n.º 12
0
    def essolve(self, tlist, rho0=None, recalc=True, savefile=None):
        """ 
        Evolution of the density matrix by
        expressing the ODE as an exponential series.

        Args:
            tlist: The list of times for which to find the density matrix.
            rho0: Define an initial density matrix. Default is ground state.
            recalc: Rerun the calculation if a saved file exists?
            savefile: (string) Save the data to savefile.qu

        Returns:
            result: qutip result object containing the solved data.

        Notes:
            QuTiP essolve method doesn't return the states properly so I use
            the underlying ode2es method.

            Unlike the mesolve method, the tlist here doesn't have any need 
            for high resolution to solve. So better when the density matrix 
            is only needed at a few points.

        """

        if not rho0:
            rho0 = self.ground_state() * self.ground_state().dag()

        savefile_exists = os.path.isfile(str(savefile) + '.qu')

        # Solve if 1) we ask for it to be recalculated or 2) it *must* be
        # calculated because no savefile exists.
        if (recalc or not savefile_exists):

            H = self.H_0 + self.H_Delta + self.H_I_sum()
            L = qu.liouvillian(H, self.c_ops)

            es = qu.ode2es(L, rho0)
            states = es.value(tlist)

            self.result = qu.solver.Result()
            self.result.states = states
            self.result.solver = "essolve"
            self.result.times = tlist

            self.rho = self.result.states[-1]  # Set rho to the final state.

            # Only save the file if we have a place to save it.
            if (savefile != None):
                qu.qsave(self.result, savefile)

        # Otherwise load the steady state rho_v_delta from file
        else:
            self.result = qu.qload(savefile)
            self.rho = self.result.states[-1]

        return self.result
Exemplo n.º 13
0
def test_diag_liou_mult(dimension):
    "BR Tools : Diagonal Liouvillian mult"
    H = qutip.rand_dm(dimension, 0.5)
    evals, evecs = H.eigenstates()
    L = qutip.liouvillian(H.transform(evecs))
    coefficients = np.ones((dimension * dimension, ), dtype=np.complex128)
    calculated = np.zeros_like(coefficients)
    target = L.data.dot(coefficients)
    _test_diag_liou_mult(evals, coefficients, calculated, dimension)
    np.testing.assert_allclose(target, calculated, atol=1e-11, rtol=1e-6)
Exemplo n.º 14
0
    def to_qobj(self) -> "qutip.liouvillian":  # noqa: F821
        r"""Convert the operator to a qutip's liouvillian Qobj.

        Returns:
            A `qutip.liouvillian` object.
        """
        from qutip import liouvillian

        return liouvillian(self.hamiltonian.to_qobj(),
                           [op.to_qobj() for op in self.jump_operators])
Exemplo n.º 15
0
def test_diag_liou_mult():
    "BR Tools : Diagonal Liouvillian mult"
    for dimension in range(2, 100):
        H = qutip.rand_dm(dimension, 0.5)
        evals, evecs = H.eigenstates()
        L = qutip.liouvillian(H.transform(evecs))
        coefficients = np.ones((dimension*dimension,), dtype=np.complex128)
        calculated = np.zeros_like(coefficients)
        target = L.data.dot(coefficients)
        _test_diag_liou_mult(evals, coefficients, calculated, dimension)
        assert np.allclose(target, calculated)
Exemplo n.º 16
0
def test_bad_options_pseudo_inverse():
    N = 4
    a = qutip.destroy(N)
    H = (a.dag() + a)
    L = qutip.liouvillian(H, [a])
    with pytest.raises(TypeError):
        qutip.pseudo_inverse(L, method='splu', bad_opt=True)
    with pytest.raises(ValueError):
        qutip.pseudo_inverse(L, method='not a method', sparse=False)
    with pytest.raises(ValueError):
        qutip.pseudo_inverse(L, method='not a method')
Exemplo n.º 17
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)
Exemplo n.º 18
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
Exemplo n.º 19
0
def test_general_stochastic():
    "Stochastic: general_stochastic"
    "Reproduce smesolve homodyne"
    tol = 0.025
    N = 4
    gamma = 0.25
    ntraj = 20
    nsubsteps = 50
    a = destroy(N)

    H = [[a.dag() * a, f]]
    psi0 = coherent(N, 0.5)
    sc_ops = [np.sqrt(gamma) * a, np.sqrt(gamma) * a * 0.5]
    e_ops = [a.dag() * a, a + a.dag(), (-1j) * (a - a.dag())]

    L = liouvillian(QobjEvo([[a.dag() * a, f]], args={"a": 2}), c_ops=sc_ops)
    L.compile()
    sc_opsM = [QobjEvo(spre(op) + spost(op.dag())) for op in sc_ops]
    [op.compile() for op in sc_opsM]
    e_opsM = [spre(op) for op in e_ops]

    def d1(t, vec):
        return L.mul_vec(t, vec)

    def d2(t, vec):
        out = []
        for op in sc_opsM:
            out.append(op.mul_vec(t, vec) - op.expect(t, vec) * vec)
        return np.stack(out)

    times = np.linspace(0, 0.5, 13)
    res_ref = mesolve(H, psi0, times, sc_ops, e_ops, args={"a": 2})
    list_methods_tol = ['euler-maruyama', 'platen', 'explicit15']
    for solver in list_methods_tol:
        res = general_stochastic(ket2dm(psi0),
                                 times,
                                 d1,
                                 d2,
                                 len_d2=2,
                                 e_ops=e_opsM,
                                 normalize=False,
                                 ntraj=ntraj,
                                 nsubsteps=nsubsteps,
                                 solver=solver)
    assert_(
        all([
            np.mean(abs(res.expect[idx] - res_ref.expect[idx])) < tol
            for idx in range(len(e_ops))
        ]))
    assert_(len(res.measurement) == ntraj)
Exemplo n.º 20
0
def test_cop_super_mult():
    "BR Tools : cop_super_mult"
    dimension = 10
    for _ in range(50):
        H = qutip.rand_herm(dimension, 0.5)
        basis = H.eigenstates()[1]
        a = qutip.destroy(dimension)
        L = qutip.liouvillian(None, [a.transform(basis)])
        vec = np.ones((dimension * dimension, ), dtype=np.complex128)
        target = L.data.dot(vec)
        calculated = np.zeros_like(target)
        _eigenvalues = np.empty((dimension, ), dtype=np.float64)
        _cop_super_mult(a.full('F'), _test_zheevr(H.full('F'), _eigenvalues),
                        vec, 1, calculated, dimension, qutip.settings.atol)
        np.testing.assert_allclose(target, calculated, atol=1e-12)
Exemplo n.º 21
0
def liouvillian(H, c_ops):
    """Convert Hamiltonian and Lindblad operators into a Liouvillian.

    This is like :func:`qutip.superoperator.liouvillian`, but `H` may be a
    time-dependent Hamiltonian in nested-list format. `H` is assumed to contain
    a drift Hamiltonian, and the Lindblad operators in `c_ops` cannot be
    time-dependent.
    """
    if isinstance(H, qutip.Qobj):
        return qutip.liouvillian(H, c_ops)
    elif isinstance(H, list):
        res = []
        for spec in H:
            if isinstance(spec, qutip.Qobj):
                res.append(qutip.liouvillian(spec, c_ops))
                c_ops = []
            else:
                res.append([qutip.liouvillian(spec[0]), spec[1]])
        assert len(c_ops) == 0, "No drift Hamiltonian"
        return res
    else:
        raise ValueError(
            "H must either be a Qobj, or a time-dependent Hamiltonian in "
            "nested-list format")
Exemplo n.º 22
0
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)
Exemplo n.º 23
0
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)
Exemplo n.º 24
0
def test_general_stochastic():
    "Stochastic: general_stochastic"
    "Reproduce smesolve homodyne"
    tol = 0.025
    N = 4
    gamma = 0.25
    ntraj = 20
    nsubsteps = 50
    a = destroy(N)

    H = [[a.dag() * a,f]]
    psi0 = coherent(N, 0.5)
    sc_ops = [np.sqrt(gamma) * a, np.sqrt(gamma) * a * 0.5]
    e_ops = [a.dag() * a, a + a.dag(), (-1j)*(a - a.dag())]

    L = liouvillian(QobjEvo([[a.dag() * a,f]], args={"a":2}), c_ops = sc_ops)
    L.compile()
    sc_opsM = [QobjEvo(spre(op) + spost(op.dag())) for op in sc_ops]
    [op.compile() for op in sc_opsM]
    e_opsM = [spre(op) for op in e_ops]

    def d1(t, vec):
        return L.mul_vec(t,vec)

    def d2(t, vec):
        out = []
        for op in sc_opsM:
            out.append(op.mul_vec(t,vec)-op.expect(t,vec)*vec)
        return np.stack(out)

    times = np.linspace(0, 0.5, 13)
    res_ref = mesolve(H, psi0, times, sc_ops, e_ops, args={"a":2})
    list_methods_tol = ['euler-maruyama',
                        'platen',
                        'explicit15']
    for solver in list_methods_tol:
        res = general_stochastic(ket2dm(psi0),times,d1,d2,len_d2=2, e_ops=e_opsM,
                                 normalize=False, ntraj=ntraj, nsubsteps=nsubsteps,
                                 solver=solver)
    assert_(all([np.mean(abs(res.expect[idx] - res_ref.expect[idx])) < tol
                 for idx in range(len(e_ops))]))
    assert_(len(res.measurement) == ntraj)
    def calculate_first_order_correction(self, cutoff_matrix_element, L0,
                                         **kwargs):
        """Calculates the first order correction to the steady-state density matrix due to drive term,
           and thereby calculating the corresponding relevance parameter
           returns: relevance parameter, Delta_{nm}
           @param cutoff_matrix_element: (float)
           @param **kwargs: (dictionary) of relevant drive term indices, usually n labels ket, m for bra
           @param L0: (QObj) the Liouvillian superoperator L_0 needed to solve for the correction, independent of indices
                             so not needed to be re-evaluated every time this function is called
        """
        n = kwargs['ket_index']
        m = kwargs['bra_index']
        if n >= m: return 0.0
        evecs = self.evecs
        evals = self.evals
        # ignore drive terms whose matrix elements are beneath a specificied cutoff for speed-up.
        v_nm = (evecs[n].dag() * (self.v * evecs[m]))[0][0][0]
        if abs(v_nm) <= cutoff_matrix_element: return 0.0

        k = self.integer_list
        rho_s_vectorform = np.reshape(self.density_matrix, (self.dim**2, 1),
                                      order='F')

        V_nm = (evecs[n] * evecs[m].dag() * (evecs[n].dag() *
                                             (self.v * evecs[m])))
        L_nm = qt.liouvillian(V_nm)
        #b = np.dot(L_nm.full(),rho_0)
        b = (L_nm * rho_s_vectorform).data
        omega_of_k = (k[n] - k[m] + 1) * self.omega

        A = 1j * omega_of_k * qt.identity(self.dim**2).data - L0.data

        #A = A.full()
        #del_rho = la.lstsq(A,b,rcond = 1e-6)[0]

        if omega_of_k == 0:
            del_rho = la.lsmr(A, b)[0]
        else:
            del_rho = spsolve(A, b)

        return nla.norm(del_rho)
Exemplo n.º 26
0
def test_br_term_mult(secular):
    "BR Tools : br_term_mult"
    dimension = 10
    time = 1.0
    atol = 1e-12
    for _ in range(10):
        H = qutip.rand_herm(dimension, 0.5)
        basis = H.eigenstates()[1]
        L_diagonal = qutip.liouvillian(H.transform(basis))
        evals = np.empty((dimension,), dtype=np.float64)
        evecs = _test_zheevr(H.full('F'), evals)
        operator = qutip.rand_herm(dimension, 0.5)
        a_ops = [[operator, lambda w: 1.0]]
        vec = np.ones((dimension*dimension,), dtype=np.complex128)
        br_tensor, _ = qutip.bloch_redfield_tensor(H, a_ops,
                                                   use_secular=secular)
        target = (br_tensor - L_diagonal).data.dot(vec)
        calculated = np.zeros_like(target)
        _test_br_term_mult(time, operator.full('F'), evecs, evals, vec,
                           calculated, secular, 0.1, atol)
        assert np.allclose(target, calculated)
Exemplo n.º 27
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
Exemplo n.º 28
0
        def _run_solver() -> CoherentResults:
            """Returns CoherentResults: Object containing evolution results."""
            # Decide if progress bar will be fed to QuTiP solver
            p_bar: Optional[bool]
            if progress_bar is True:
                p_bar = True
            elif (progress_bar is False) or (progress_bar is None):
                p_bar = None
            else:
                raise ValueError("`progress_bar` must be a bool.")

            if "dephasing" in self.config.noise:
                # temporary workaround due to a qutip bug when using mesolve
                liouvillian = qutip.liouvillian(self._hamiltonian,
                                                self._collapse_ops)
                result = qutip.mesolve(
                    liouvillian,
                    self.initial_state,
                    self._eval_times_array,
                    progress_bar=p_bar,
                    options=solv_ops,
                )
            else:
                result = qutip.sesolve(
                    self._hamiltonian,
                    self.initial_state,
                    self._eval_times_array,
                    progress_bar=p_bar,
                    options=solv_ops,
                )
            return CoherentResults(
                result.states,
                self._size,
                self.basis_name,
                self._eval_times_array,
                self._meas_basis,
                meas_errors,
            )
Exemplo n.º 29
0
    def test_pure_dephasing_model_drude_lorentz_baths(self,
                                                      terminator,
                                                      bath_cls,
                                                      atol=1e-3):
        dlm = DrudeLorentzPureDephasingModel(
            lam=0.025,
            gamma=0.05,
            T=1 / 0.95,
            Nk=2,
        )
        bath = bath_cls(
            Q=dlm.Q,
            lam=dlm.lam,
            gamma=dlm.gamma,
            T=dlm.T,
            Nk=dlm.Nk,
        )
        if terminator:
            _, terminator_op = bath.terminator()
            H_sys = liouvillian(dlm.H) + terminator_op
        else:
            H_sys = dlm.H

        options = Options(nsteps=15000, store_states=True)
        hsolver = HEOMSolver(H_sys, bath, 14, options=options)

        tlist = np.linspace(0, 10, 21)
        result = hsolver.run(dlm.rho(), tlist)

        test = dlm.state_results(result.states)
        expected = dlm.analytic_results(tlist)
        np.testing.assert_allclose(test, expected, atol=atol)

        rho_final, ado_state = hsolver.steady_state()
        test = dlm.state_results([rho_final])
        expected = dlm.analytic_results([100])
        np.testing.assert_allclose(test, expected, atol=atol)
        assert rho_final == ado_state.extract(0)
Exemplo n.º 30
0
def _generator(k, H, L1, L2, S=None, c_ops_markov=None):
    """
    Create a Liouvillian for a cascaded chain of k system copies
    """
    id = qt.qeye(H.dims[0][0])
    Id = qt.sprepost(id, id)
    if S is None:
        S = np.identity(len(L1))
    # create Lindbladian
    L = qt.Qobj()
    E0 = Id
    # first system
    L += qt.liouvillian(None, [_localop(c, 1, k) for c in L2])
    for l in range(1, k):
        # Identiy superoperator
        E0 = qt.composite(E0, Id)
        # Bare Hamiltonian
        Hl = _localop(H, l, k)
        L += qt.liouvillian(Hl, [])
        # Markovian Decay channels
        if c_ops_markov is not None:
            for c in c_ops_markov:
                cl = _localop(c, l, k)
                L += qt.liouvillian(None, [cl])
        # Cascade coupling
        c1 = np.array([_localop(c, l, k) for c in L1])
        c2 = np.array([_localop(c, l+1, k) for c in L2])
        c2dag = np.array([c.dag() for c in c2])
        Hcasc = -0.5j*np.dot(c2dag, np.dot(S, c1))
        Hcasc += Hcasc.dag()
        Lvec = c2 + np.dot(S, c1)
        L += qt.liouvillian(Hcasc, [c for c in Lvec])
    # last system
    L += qt.liouvillian(_localop(H, k, k), [_localop(c, k, k) for c in L1])
    if c_ops_markov is not None:
        for c in c_ops_markov:
            cl = _localop(c, k, k)
            L += qt.liouvillian(None, [cl])
    E0.dims = L.dims
    # return generator and identity superop E0
    return L, E0
Exemplo n.º 31
0
def _generator(k, H, L1, L2, S=None, c_ops_markov=None):
    """
    Create a Liouvillian for a cascaded chain of k system copies
    """
    id = qt.qeye(H.dims[0][0])
    Id = qt.sprepost(id, id)
    if S is None:
        S = np.identity(len(L1))
    # create Lindbladian
    L = qt.Qobj()
    E0 = Id
    # first system
    L += qt.liouvillian(None, [_localop(c, 1, k) for c in L2])
    for l in range(1, k):
        # Identiy superoperator
        E0 = qt.composite(E0, Id)
        # Bare Hamiltonian
        Hl = _localop(H, l, k)
        L += qt.liouvillian(Hl, [])
        # Markovian Decay channels
        if c_ops_markov is not None:
            for c in c_ops_markov:
                cl = _localop(c, l, k)
                L += qt.liouvillian(None, [cl])
        # Cascade coupling
        c1 = np.array([_localop(c, l, k) for c in L1])
        c2 = np.array([_localop(c, l+1, k) for c in L2])
        c2dag = np.array([c.dag() for c in c2])
        Hcasc = -0.5j*np.dot(c2dag, np.dot(S, c1))
        Hcasc += Hcasc.dag()
        Lvec = c2 + np.dot(S, c1)
        L += qt.liouvillian(Hcasc, [c for c in Lvec])
    # last system
    L += qt.liouvillian(_localop(H, k, k), [_localop(c, k, k) for c in L1])
    if c_ops_markov is not None:
        for c in c_ops_markov:
            cl = _localop(c, k, k)
            L += qt.liouvillian(None, [cl])
    E0.dims = L.dims
    # return generator and identity superop E0
    return L, E0
Exemplo n.º 32
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)
Exemplo n.º 33
0
def hsolve(H, psi0, tlist, Q, gam, lam0, Nc, N, w_th, options=None):
    """
    Function to solve for an open quantum system using the
    hierarchy model.

    Parameters
    ----------
    H: Qobj
        The system hamiltonian.
    psi0: Qobj
        Initial state of the system.
    tlist: List.
        Time over which system evolves.
    Q: Qobj
        The coupling between system and bath.
    gam: Float
        Bath cutoff frequency.
    lam0: Float
        Coupling strength.
    Nc: Integer
        Cutoff parameter.
    N: Integer
        Number of matsubara terms.
    w_th: Float
        Temperature.
    options : :class:`qutip.Options`
        With options for the solver.

    Returns
    -------
    output: Result
        System evolution.
    """
    if options is None:
        options = Options()

    # Set up terms of the matsubara and tanimura boundaries

    # Parameters and hamiltonian
    hbar = 1.
    kb = 1.

    # Set by system
    dimensions = dims(H)
    Nsup = dimensions[0][0] * dimensions[0][0]
    unit = qeye(dimensions[0])

    # Ntot is the total number of ancillary elements in the hierarchy
    Ntot = int(round(factorial(Nc+N) / (factorial(Nc) * factorial(N))))
    c0 = (lam0 * gam * (_cot(gam * hbar / (2. * kb * w_th)) - (1j))) / hbar
    LD1 = (-2. * spre(Q) * spost(Q.dag()) + spre(Q.dag()*Q) + spost(Q.dag()*Q))
    pref = ((2. * lam0 * kb * w_th / (gam * hbar)) - 1j * lam0) / hbar
    gj = 2 * np.pi * kb * w_th / hbar
    L12 = -pref * LD1 + (c0 / gam) * LD1

    for i1 in range(1, N):
        num = (4 * lam0 * gam * kb * w_th * i1 * gj/((i1 * gj)**2 - gam**2))
        ci = num / (hbar**2)
        L12 = L12 + (ci / gj) * LD1

    # Setup liouvillian

    L = liouvillian(H, [L12])
    Ltot = L.data
    unit = sp.eye(Ntot,format='csr')
    Lbig = sp.kron(unit, Ltot)
    rho0big1 = np.zeros((Nsup * Ntot), dtype=complex)

    # Prepare initial state:

    rhotemp = mat2vec(np.array(psi0.full(), dtype=complex))

    for idx, element in enumerate(rhotemp):
        rho0big1[idx] = element[0]
    
    nstates, state2idx, idx2state = enr_state_dictionaries([Nc+1]*(N), Nc)
    for nlabelt in state_number_enumerate([Nc+1]*(N), Nc):
        nlabel = list(nlabelt)
        ntotalcheck = 0
        for ncheck in range(N):
            ntotalcheck = ntotalcheck + nlabel[ncheck]
        current_pos = int(round(state2idx[tuple(nlabel)]))
        Ltemp = sp.lil_matrix((Ntot, Ntot))
        Ltemp[current_pos, current_pos] = 1
        Ltemp.tocsr()
        Lbig = Lbig + sp.kron(Ltemp, (-nlabel[0] * gam * spre(unit).data))

        for kcount in range(1, N):
            counts = -nlabel[kcount] * kcount * gj * spre(unit).data
            Lbig = Lbig + sp.kron(Ltemp, counts)

        for kcount in range(N):
            if nlabel[kcount] >= 1:
                # find the position of the neighbour
                nlabeltemp = copy(nlabel)
                nlabel[kcount] = nlabel[kcount] - 1
                current_pos2 = int(round(state2idx[tuple(nlabel)]))
                Ltemp = sp.lil_matrix((Ntot, Ntot))
                Ltemp[current_pos, current_pos2] = 1
                Ltemp.tocsr()
                # renormalized version:
                ci = (4 * lam0 * gam * kb * w_th * kcount
                      * gj/((kcount * gj)**2 - gam**2)) / (hbar**2)
                if kcount == 0:
                    Lbig = Lbig + sp.kron(Ltemp, (-1j
                                          * (np.sqrt(nlabeltemp[kcount]
                                             / abs(c0)))
                                          * ((c0) * spre(Q).data
                                             - (np.conj(c0))
                                             * spost(Q).data)))
                if kcount > 0:
                    ci = (4 * lam0 * gam * kb * w_th * kcount
                          * gj/((kcount * gj)**2 - gam**2)) / (hbar**2)
                    Lbig = Lbig + sp.kron(Ltemp, (-1j
                                          * (np.sqrt(nlabeltemp[kcount]
                                             / abs(ci)))
                                          * ((ci) * spre(Q).data
                                             - (np.conj(ci))
                                             * spost(Q).data)))
                nlabel = copy(nlabeltemp)

        for kcount in range(N):
            if ntotalcheck <= (Nc-1):
                nlabeltemp = copy(nlabel)
                nlabel[kcount] = nlabel[kcount] + 1
                current_pos3 = int(round(state2idx[tuple(nlabel)]))
            if current_pos3 <= (Ntot):
                Ltemp = sp.lil_matrix((Ntot, Ntot))
                Ltemp[current_pos, current_pos3] = 1
                Ltemp.tocsr()
            # renormalized
                if kcount == 0:
                    Lbig = Lbig + sp.kron(Ltemp, -1j
                                          * (np.sqrt((nlabeltemp[kcount]+1)
                                             * abs(c0)))
                                          * (spre(Q) - spost(Q)).data)
                if kcount > 0:
                    ci = (4 * lam0 * gam * kb * w_th * kcount
                          * gj/((kcount * gj)**2 - gam**2)) / (hbar**2)
                    Lbig = Lbig + sp.kron(Ltemp, -1j
                                          * (np.sqrt((nlabeltemp[kcount]+1)
                                             * abs(ci)))
                                          * (spre(Q) - spost(Q)).data)
            nlabel = copy(nlabeltemp)

    output = []
    for element in rhotemp:
        output.append([])
    r = scipy.integrate.ode(cy_ode_rhs)
    Lbig2 = Lbig.tocsr()
    r.set_f_params(Lbig2.data, Lbig2.indices, Lbig2.indptr)
    r.set_integrator('zvode', method=options.method, order=options.order,
                     atol=options.atol, rtol=options.rtol,
                     nsteps=options.nsteps, first_step=options.first_step,
                     min_step=options.min_step, max_step=options.max_step)

    r.set_initial_value(rho0big1, tlist[0])
    dt = tlist[1] - tlist[0]

    for t_idx, t in enumerate(tlist):
        r.integrate(r.t + dt)
        for idx, element in enumerate(rhotemp):
            output[idx].append(r.y[idx])

    return output
Exemplo n.º 34
0
print transmon_levels
#Omega_vec=- 0.5j*(Omega*adag - conj(Omega)*a)
theta=0.0
Omega_vec= 0.5*Omega*(a*exp(-1j*theta)+adag*exp(1j*theta))
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()
Exemplo n.º 35
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug  1 07:15:05 2018

@author: huang
"""
import qutip as qt
import numpy as np

H = 10 * qt.sigmaz()

c1 = qt.destroy(2)
L = qt.liouvillian(H, [c1])

print(L)

S = (12 * L).expm()
print("S: ", S)
Exemplo n.º 36
0
if 0:
    value_grid = array(meshgrid(phi_arr, Omega_sim_vec))
    vg = zip(value_grid[0, :, :].flatten(), value_grid[1, :, :].flatten())
    fexpt = parallel_map(find_expect, vg, progress_bar=True)
    fexpt = reshape(fexpt, (31, 101))
    pcolormesh(phi_arr, sample_power_sim_dBm, absolute(fexpt), cmap="RdBu_r")
    show()

#w01_vec(i) = wT_vec(2)- wT_vec(1); % Transition energies.
#w12_vec(i) = wT_vec(3)- wT_vec(2);
#w23_vec(i) = wT_vec(4)- wT_vec(3);
#w34_vec(i) = wT_vec(5)- wT_vec(4);
H = make_H(0.2, 190, 4000.0)
print H
L = liouvillian(H, c_op_list)
print L
tr_mat = tensor([qeye(n) for n in L.dims[0][0]])
print tr_mat
tr_vec = transpose(mat2vec(tr_mat.full()))
print tr_vec
N = prod(L.dims[0][0])
print N
A = L.full()

a_sup = spre(a).full()
b_sup = spre(p).full()

D, U = eig(A)
print "D", D
I = identity(N * N)
Exemplo n.º 37
0
def simulate_quantities_of_interest_superoperator(H_0,
                                                  tlist,
                                                  c_ops,
                                                  eps_vec,
                                                  sim_step,
                                                  verbose: bool = True):
    """
    Calculates the quantities of interest from the propagator U

    Args:
        H_0 (Qobj): static hamiltonian, see "coupled_transmons_hamiltonian"
            for the expected form of the Hamiltonian.
        tlist (array): times in s, describes the x component of the
            trajectory to simulate
        c-ops (list of Qobj): list of jump operators, time-independent at the momennt
        eps_vec(array): detuning describes the y-component of the trajectory
            to simulate.

    Returns
        phi_cond (float):   conditional phase (deg)
        L1      (float):    leakage
        L2      (float):    seepage
        avgatefid (float):  average gate fidelity in full space
        avgatefid_compsubspace (float):  average gate fidelity only in the computational subspace

    """

    scalefactor = 1e6  # otherwise qtp.propagator in parallel mode doesn't work
    # time is multiplied by scalefactor and frequency is divided by it
    tlist = tlist * scalefactor
    eps_vec = eps_vec / scalefactor
    sim_step = sim_step * scalefactor
    H_0 = H_0 / scalefactor
    if c_ops != []:  # c_ops is a list of either operators or lists where the first element is
        # an operator and the second one is a list of the (time-dependent) coefficients
        for c in range(len(c_ops)):
            if isinstance(c_ops[c], list):
                c_ops[c][1] = c_ops[c][1] / np.sqrt(scalefactor)
            else:
                c_ops[c] = c_ops[c] / np.sqrt(scalefactor)
    H_c = n_q0
    '''								# step of 1/sampling_rate=1/2.4e9=0.4 ns seems good by itself
    sim_step_new=sim_step*2
    
    eps_interp = interp1d(tlist, eps_vec, fill_value='extrapolate')
    tlist_new = (np.linspace(0, np.max(tlist), 576/2)) 
    eps_vec_new=eps_interp(tlist_new)
    
    c_ops_new=[]
    for c in range(len(c_ops)):
        if isinstance(c_ops[c],list):
            c_ops_interp=interp1d(tlist,c_ops[c][1], fill_value='extrapolate')
            c_ops_new.append([c_ops[c][0],c_ops_interp(tlist_new)])
        else:
            c_ops_new.append(c_ops[c])

    # function only exists to wrap
    #def eps_t(t, args=None):
    #    return eps_interp(t)
    print(len(eps_vec),len(eps_vec_new))


  			
    t0 = time.time()

    exp_L_total_new=1
    for i in range(len(tlist_new)):
        H=H_0+eps_vec_new[i]*H_c
        c_ops_temp=[]
        for c in range(len(c_ops_new)):
            if isinstance(c_ops_new[c],list):
                c_ops_temp.append(c_ops_new[c][0]*c_ops_new[c][1][i])
            else:
                c_ops_temp.append(c_ops_new[c])
        liouville_exp_t=(qtp.liouvillian(H,c_ops_temp)*sim_step_new).expm()
        exp_L_total_new=liouville_exp_t*exp_L_total_new

    #exp_L_oneway=(qtp.liouvillian(H_0,c_ops)*240e-3).expm()

    t1 = time.time()
    print('\n alternative propagator_new',t1-t0)
    '''

    t0 = time.time()

    exp_L_total = 1
    for i in range(len(tlist)):
        H = H_0 + eps_vec[i] * H_c
        c_ops_temp = []
        for c in range(len(c_ops)):
            if isinstance(c_ops[c], list):
                c_ops_temp.append(c_ops[c][0] * c_ops[c][1][i])
            else:
                c_ops_temp.append(c_ops[c])
        liouville_exp_t = (qtp.liouvillian(H, c_ops_temp) * sim_step).expm()
        exp_L_total = liouville_exp_t * exp_L_total

    #exp_L_oneway=(qtp.liouvillian(H_0,c_ops)*240e-3).expm()

    t1 = time.time()
    print('\n alternative propagator', t1 - t0)
    '''						# qutip propagator not used anymore because it takes too much time
    t0 = time.time()
    if c_ops==[]:
    	nstepsmax=1000
    else:
    	nstepsmax=100000
    H_t = [H_0, [H_c, eps_vec]]
    U_t = qtp.propagator(H_t, tlist, c_ops, parallel=True, options=qtp.Options(nsteps=nstepsmax))   # returns unitary 'oper' if c_ops=[], otherwise 'super'
    t1 = time.time()
    print('/n propagator',t1-t0)
    if verbose:
        print('simulation took {:.2f}s'.format(t1-t0))
    '''

    U_final = exp_L_total
    phases = phases_from_superoperator(U_final)
    phi_cond = phases[-1]
    L1 = leakage_from_superoperator(U_final)
    L2 = seepage_from_superoperator(U_final)
    avgatefid = pro_avfid_superoperator_phasecorrected(U_final, phases)
    avgatefid_compsubspace = pro_avfid_superoperator_compsubspace_phasecorrected(
        U_final, L1,
        phases)  # leakage has to be taken into account, see Woods & Gambetta
    print('avgatefid_compsubspace', avgatefid_compsubspace)
    '''
    U_final = exp_L_total_new
    phases2 = phases_from_superoperator(U_final)
    phi_cond2 = phases2[-1]
    L12 = leakage_from_superoperator(U_final)
    L22 = seepage_from_superoperator(U_final)
    avgatefid2 = pro_avfid_superoperator_phasecorrected(U_final,phases2)
    avgatefid_compsubspace2 = pro_avfid_superoperator_compsubspace_phasecorrected(U_final,L12,phases2)


    print(phi_cond-phi_cond2,phi_cond)
    print(L1-L12,L1)
    print(L2-L22,L2)
    print(avgatefid-avgatefid2,avgatefid)
    print(avgatefid_compsubspace-avgatefid_compsubspace2,avgatefid_compsubspace)
    '''

    return {
        'phi_cond': phi_cond,
        'L1': L1,
        'L2': L2,
        'avgatefid_pc': avgatefid,
        'avgatefid_compsubspace_pc': avgatefid_compsubspace
    }
Exemplo n.º 38
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
Exemplo n.º 39
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
Exemplo n.º 40
0
 def Liouvillian_func(t, args):
     c = np.sqrt(kappa * np.exp(-t)) * a
     data = liouvillian(H, [c]).data
     return data