Exemple #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)
Exemple #2
0
def two_qubit_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())]
    return krotov.objectives.liouvillian(H, c_ops)
def get_H_XY_terms(N):
    """ Returns local terms, without coupling coefficients, that make up the XY hamiltonian.
        returns: Hx, Hz, HPM
        Hx = list of pauli X's
        Hz = list of Pauli Z's
        HPM = list of sigma_plus * sigma_minus """

    I = qt.tensor([qt.qeye(2)] * N)
    c = list(it.combinations(range(N), 2))
    Hz, Hx, HPM = [0 * I for x in range(N)], [0 * I for x in range(N)
                                              ], [0 * I for x in c]
    for i in range(N):
        l = [qt.qeye(2)] * N
        l[i] = qt.sigmaz()
        Hz[i] = qt.tensor(l)
        l[i] = qt.sigmax()
        Hx[i] = qt.tensor(l)
    for s in range(len(c)):
        i, j = c[s]
        l = [qt.qeye(2)] * N
        l[i] = qt.sigmap()
        l[j] = qt.sigmam()
        HPM[s] = qt.tensor(l)
        HPM[s] += HPM[s].dag()
    return Hx, Hz, HPM
Exemple #4
0
def e_ops_gen(params):

    projectors = gen_projectors(params)

    sm = tensor(sigmam(), qeye(params.c_levels))
    a = tensor(qeye(2), destroy(params.c_levels))

    base_e_ops = {'a': a, 'sm': sm, 'n': a.dag() * a}
    e_ops = base_e_ops.copy()

    for key, item in base_e_ops.items():
        for i in range(2):
            for j in range(2):
                e_ops[key + '_' + str(i) + str(j)] = projectors[i] * item * projectors[j]

    for n in range(2):
        e_ops['p_q' + str(n)] = tensor(fock_dm(2, n), qeye(params.c_levels))

    for n in range(params.c_levels):
        e_ops['p_c' + str(n)] = tensor(qeye(2), fock_dm(params.c_levels, n))

    e_ops['P_0'] = projectors[0]
    e_ops['P_1'] = projectors[1]
    e_ops['P_01'] = projectors[0] * projectors[1]

    return e_ops
    def to_matrix(self, fd):
        n = num(fd)
        a = destroy(fd)
        ic = qeye(fd)
        sz = sigmaz()
        sm = sigmam()
        iq = qeye(2)

        ms = {
            "id": tensor(iq, ic),
            "a*ad" : tensor(iq, n),
            "a+hc" : tensor(iq, a),
            "sz" : tensor(sz, ic),
            "sm+hc" : tensor(sm, ic)
        }

        H0 = 0
        H1s = []
        for (p1, p2), v in self.coefs.items():
            h = ms[p1] * ms[p2]
            try:
                term = float(v) * h
                if not term.isherm:
                    term += term.dag()
                H0 += term
            except ValueError:
                H1s.append([h, v])
                if not h.isherm:
                    replacement = lambda m: '(-' + m.group() + ')'
                    conj_v = re.sub('[1-9]+j', replacement, v)
                    H1s.append([h.dag(), conj_v])
        if H1s:
            return [H0] + H1s
        else:
            return H0
Exemple #6
0
def test_jmat_12():
    spinhalf = qutip.jmat(1 / 2.)

    paulix = np.array([[0. + 0.j, 1. + 0.j], [1. + 0.j, 0. + 0.j]])
    pauliy = np.array([[0. + 0.j, 0. - 1.j], [0. + 1.j, 0. + 0.j]])
    pauliz = np.array([[1. + 0.j, 0. + 0.j], [0. + 0.j, -1. + 0.j]])
    sigmap = np.array([[0. + 0.j, 1. + 0.j], [0. + 0.j, 0. + 0.j]])
    sigmam = np.array([[0. + 0.j, 0. + 0.j], [1. + 0.j, 0. + 0.j]])

    np.testing.assert_allclose(spinhalf[0].full() * 2, paulix)
    np.testing.assert_allclose(spinhalf[1].full() * 2, pauliy)
    np.testing.assert_allclose(spinhalf[2].full() * 2, pauliz)
    np.testing.assert_allclose(qutip.jmat(1 / 2., '+').full(), sigmap)
    np.testing.assert_allclose(qutip.jmat(1 / 2., '-').full(), sigmam)

    np.testing.assert_allclose(qutip.spin_Jx(1 / 2.).full() * 2, paulix)
    np.testing.assert_allclose(qutip.spin_Jy(1 / 2.).full() * 2, pauliy)
    np.testing.assert_allclose(qutip.spin_Jz(1 / 2.).full() * 2, pauliz)
    np.testing.assert_allclose(qutip.spin_Jp(1 / 2.).full(), sigmap)
    np.testing.assert_allclose(qutip.spin_Jm(1 / 2.).full(), sigmam)

    np.testing.assert_allclose(qutip.sigmax().full(), paulix)
    np.testing.assert_allclose(qutip.sigmay().full(), pauliy)
    np.testing.assert_allclose(qutip.sigmaz().full(), pauliz)
    np.testing.assert_allclose(qutip.sigmap().full(), sigmap)
    np.testing.assert_allclose(qutip.sigmam().full(), sigmam)

    spin_set = qutip.spin_J_set(0.5)
    for i in range(3):
        assert spinhalf[i] == spin_set[i]
Exemple #7
0
    def setup_collapse_operators(self):

        print("Setup Collapse Operators in Lindblad form", end=" ")
        #Reference: http://qutip.org/docs/4.1/guide/dynamics/dynamics-time.html
        collapse = []
        #Empty list for collapse operators
        # Collapse coefficients from the dictionary
        k_Dwn = pars['kDwn']
        k_Up = pars['kUp']
        G_e2g = pars['Gamma_E2G']
        G_g2e = pars['Gamma_G2E']
        print("for the parameters")
        print("kDwn = 2pi * %.3lg [GHz],\nkUp  = 2pi * %.3lg [GHz]"\
              %(k_Dwn/(2*np.pi), k_Up/(2*np.pi)))
        print("Ge2g = %.3lg   [GHz],\nGg2e = %.3lg [GHz]\n" % (G_e2g, G_g2e))
        #------------------------------------------------
        # Collapse operators in Lindblad Master Equation
        #------------------------------------------------
        a = self.a
        sp = tensor(sigmap(), qeye(pars['N']))  # sigma+
        sm = tensor(sigmam(), qeye(pars['N']))  # sigma-

        #if isLindblad == True:
        collapse.append(np.sqrt(k_Dwn) * a)
        #[sqrt(2p*Gzh)]
        collapse.append(np.sqrt(k_Up) * a.dag())
        #[sqrt(2p*Gzh)]
        collapse.append(np.sqrt(G_e2g) * sm)
        #[sqrt(2p*Gzh)]
        collapse.append(np.sqrt(G_g2e) * sp)
        #[sqrt(2p*Gzh)]
        #DISREGARDED#collapse.append(np.sqrt(Gamma_varphi) * sz);#[dimensionless]
        return collapse
def _qubit_integrate(tlist, psi0, epsilon, delta, g1, g2, solver):

    H = epsilon / 2.0 * sigmaz() + delta / 2.0 * sigmax()

    c_op_list = []

    rate = g1
    if rate > 0.0:
        c_op_list.append(np.sqrt(rate) * sigmam())

    rate = g2
    if rate > 0.0:
        c_op_list.append(np.sqrt(rate) * sigmaz())

    e_ops = [sigmax(), sigmay(), sigmaz()]

    if solver == "me":
        output = mesolve(H, psi0, tlist, c_op_list, e_ops)
    elif solver == "es":
        output = essolve(H, psi0, tlist, c_op_list, e_ops)
    elif solver == "mc":
        output = mcsolve(H, psi0, tlist, c_op_list, e_ops, ntraj=750)
    else:
        raise ValueError("unknown solver")

    return output.expect[0], output.expect[1], output.expect[2]
	def test_jumpBinary(self):
		tStart = 0
		psi0 = qutip.basis(2, 0)
		psi0 = psi0.full()

		sp = qutip.sigmap()
		sm = qutip.sigmam()
		jumpOps = []
		#Decay
		jumpOps.append(5 * sm)
		jumpOps.append(5 * sp)
		for i, jumpOp in enumerate(jumpOps):
			jumpOps[i] = jumpOp.full()
			jumpOps[i]= scipy.sparse.csc_matrix(jumpOps[i])
		jumpOpsPaired = QJMCSetUp.jumpOperatorsPaired(jumpOps)

		sx = qutip.sigmax()
		H = sx
		#All objects must be in a scipy sparse format
		H = H.full()
		H = scipy.sparse.csc_matrix(H)

		settings = QJMCAA.Settings()
		settings.smallestDt = 0.0001

		HEffExponentDtSet, dtSet = QJMCSetUp.HEffExponentSetProductionBinary(H,
			jumpOpsPaired, 0.1, settings)

		for _ in range(1000):
			r = 0.5
			t, _, r = QJMCJump.jumpBinary(tStart, psi0, r, jumpOps, jumpOpsPaired,
		 		dtSet, HEffExponentDtSet)
			self.assertAlmostEqual(t,0.1)
Exemple #10
0
def _qubit_integrate(tlist, psi0, epsilon, delta, g1, g2, solver):

    H = epsilon / 2.0 * sigmaz() + delta / 2.0 * sigmax()

    c_op_list = []

    rate = g1
    if rate > 0.0:
        c_op_list.append(np.sqrt(rate) * sigmam())

    rate = g2
    if rate > 0.0:
        c_op_list.append(np.sqrt(rate) * sigmaz())

    e_ops = [sigmax(), sigmay(), sigmaz()]

    if solver == "me":
        output = mesolve(H, psi0, tlist, c_op_list, e_ops)
    elif solver == "es":
        output = essolve(H, psi0, tlist, c_op_list, e_ops)
    elif solver == "mc":
        output = mcsolve(H, psi0, tlist, c_op_list, e_ops, ntraj=750)
    else:
        raise ValueError("unknown solver")

    return output.expect[0], output.expect[1], output.expect[2]
Exemple #11
0
    def __init__(self, N_field_levels, coupling=None, N_qubits=1):

        # basic parameters
        self.N_field_levels = N_field_levels
        self.N_qubits = N_qubits

        if coupling is None:
            self.g = 0
        else:
            self.g = coupling

        # bare operators
        self.idcavity = qt.qeye(self.N_field_levels)
        self.idqubit = qt.qeye(2)
        self.a_bare = qt.destroy(self.N_field_levels)
        self.sm_bare = qt.sigmam()
        self.sz_bare = qt.sigmaz()
        self.sx_bare = qt.sigmax()
        self.sy_bare = qt.sigmay()

        # 1 atom 1 cavity operators
        self.jc_a = qt.tensor(self.a_bare, self.idqubit)
        self.jc_sm = qt.tensor(self.idcavity, self.sm_bare)
        self.jc_sx = qt.tensor(self.idcavity, self.sx_bare)
        self.jc_sy = qt.tensor(self.idcavity, self.sy_bare)
        self.jc_sz = qt.tensor(self.idcavity, self.sz_bare)
    def __init__(self, N_field_levels, coupling=None, N_qubits=1):

        # basic parameters
        self.N_field_levels = N_field_levels
        self.N_qubits = N_qubits

        if coupling is None:
            self.g = 0
        else:
            self.g = coupling

        # bare operators
        self.idcavity = qt.qeye(self.N_field_levels)
        self.idqubit = qt.qeye(2)
        self.a_bare = qt.destroy(self.N_field_levels)
        self.sm_bare = qt.sigmam()
        self.sz_bare = qt.sigmaz()
        self.sx_bare = qt.sigmax()
        self.sy_bare = qt.sigmay()

        # 1 atom 1 cavity operators
        self.jc_a = qt.tensor(self.a_bare, self.idqubit)
        self.jc_sm = qt.tensor(self.idcavity, self.sm_bare)
        self.jc_sx = qt.tensor(self.idcavity, self.sx_bare)
        self.jc_sy = qt.tensor(self.idcavity, self.sy_bare)
        self.jc_sz = qt.tensor(self.idcavity, self.sz_bare)
Exemple #13
0
def test_mc_dtypes2():
    "Monte-carlo: check for correct dtypes (average_states=False)"
    # set system parameters
    kappa = 2.0  # mirror coupling
    gamma = 0.2  # spontaneous emission rate
    g = 1  # atom/cavity coupling strength
    wc = 0  # cavity frequency
    w0 = 0  # atom frequency
    wl = 0  # driving frequency
    E = 0.5  # driving amplitude
    N = 5  # number of cavity energy levels (0->3 Fock states)
    tlist = np.linspace(0, 10, 5)  # times for expectation values
    # construct Hamiltonian
    ida = qeye(N)
    idatom = qeye(2)
    a = tensor(destroy(N), idatom)
    sm = tensor(ida, sigmam())
    H = (w0 - wl) * sm.dag() * sm + (wc - wl) * a.dag() * a + \
        1j * g * (a.dag() * sm - sm.dag() * a) + E * (a.dag() + a)
    # collapse operators
    C1 = np.sqrt(2 * kappa) * a
    C2 = np.sqrt(gamma) * sm
    C1dC1 = C1.dag() * C1
    C2dC2 = C2.dag() * C2
    # intial state
    psi0 = tensor(basis(N, 0), basis(2, 1))
    opts = Options(average_expect=False)
    data = mcsolve(
        H, psi0, tlist, [C1, C2], [C1dC1, C2dC2, a], ntraj=5, options=opts)
    assert_equal(isinstance(data.expect[0][0][1], float), True)
    assert_equal(isinstance(data.expect[0][1][1], float), True)
    assert_equal(isinstance(data.expect[0][2][1], complex), True)
Exemple #14
0
def testCOPSwithAOPS():
    """
    brmesolve: c_ops with a_ops
    """

    delta = 0.0 * 2 * np.pi
    epsilon = 0.5 * 2 * np.pi
    gamma = 0.25
    times = np.linspace(0, 10, 100)
    H = delta / 2 * sigmax() + epsilon / 2 * sigmaz()
    psi0 = (2 * basis(2, 0) + basis(2, 1)).unit()
    c_ops = [np.sqrt(gamma) * sigmam(), np.sqrt(gamma) * sigmaz()]
    c_ops_brme = [np.sqrt(gamma) * sigmaz()]
    a_ops = [sigmax()]
    e_ops = [sigmax(), sigmay(), sigmaz()]
    res_me = mesolve(H, psi0, times, c_ops, e_ops)
    res_brme = brmesolve(H,
                         psi0,
                         times,
                         a_ops,
                         e_ops,
                         spectra_cb=[lambda w: gamma * (w >= 0)],
                         c_ops=c_ops_brme)

    for idx, e in enumerate(e_ops):
        diff = abs(res_me.expect[idx] - res_brme.expect[idx]).max()
        assert_(diff < 1e-2)
Exemple #15
0
def test_mcf90_dtypes2():
    "mcsolve_f90: check for correct dtypes (average_states=False)"
    # set system parameters
    kappa = 2.0  # mirror coupling
    gamma = 0.2  # spontaneous emission rate
    g = 1  # atom/cavity coupling strength
    wc = 0  # cavity frequency
    w0 = 0  # atom frequency
    wl = 0  # driving frequency
    E = 0.5  # driving amplitude
    N = 5  # number of cavity energy levels (0->3 Fock states)
    tlist = np.linspace(0, 10, 5)  # times for expectation values
    # construct Hamiltonian
    ida = qeye(N)
    idatom = qeye(2)
    a = tensor(destroy(N), idatom)
    sm = tensor(ida, sigmam())
    H = (w0 - wl) * sm.dag() * sm + (wc - wl) * a.dag() * a + \
        1j * g * (a.dag() * sm - sm.dag() * a) + E * (a.dag() + a)
    # collapse operators
    C1 = np.sqrt(2 * kappa) * a
    C2 = np.sqrt(gamma) * sm
    C1dC1 = C1.dag() * C1
    C2dC2 = C2.dag() * C2
    # intial state
    psi0 = tensor(basis(N, 0), basis(2, 1))
    opts = Options(average_expect=False)
    data = mcsolve_f90(
        H, psi0, tlist, [C1, C2], [C1dC1, C2dC2, a], ntraj=5, options=opts)
    assert_equal(isinstance(data.expect[0][0][1], float), True)
    assert_equal(isinstance(data.expect[0][1][1], float), True)
    assert_equal(isinstance(data.expect[0][2][1], complex), True)
    def test_jumpOperatorsPaired(self):
        #Sets up the jump operators
        sp = qutip.sigmap()
    	sm = qutip.sigmam()
    	no = sp*sm

    	jumpOps = []
        jumpOps.append(sm)
        jumpOps.append(sp)
        jumpOps.append(no)

        for i, jumpOp in enumerate(jumpOps):
    		jumpOps[i] = jumpOp.full()
    		jumpOps[i]= scipy.sparse.csc_matrix(jumpOps[i])
        #Runs the function
        jumpOpsPaired = QJMCSetUp.jumpOperatorsPaired(jumpOps)

        #Calculating what they should be
        jumpOpsExpect = []

        jumpOpsExpect.append(scipy.sparse.csc_matrix([[complex(1,0),0.0],[0.0,0.0]]))
        jumpOpsExpect.append(scipy.sparse.csc_matrix([[0.0,0.0],[0.0,complex(1,0)]]))
        jumpOpsExpect.append(scipy.sparse.csc_matrix([[complex(1,0),0.0],[0.0,0.0]]))

        fail = -1
        for i in range(len(jumpOps)):
            if (jumpOpsPaired[i] - jumpOpsExpect[i]).nnz == complex(0,0):
                continue
            else:
                fail = i
                break
        self.assertEqual(fail,-1)
Exemple #17
0
def f(N, options):
    wa = 1
    wc = 0.9
    delta = wa - wc
    g = 2
    kappa = 0.5
    gamma = 0.1
    n_th = 0.75
    tspan = np.linspace(0, 10, 11)

    Ia = qt.qeye(2)
    Ic = qt.qeye(N)

    a = qt.destroy(N)
    at = qt.create(N)

    sm = qt.sigmam()
    sp = qt.sigmap()

    # H = wc*qt.tensor(n, Ia) + qt.tensor(Ic, wa/2.*sz) + g*(qt.tensor(at, sm) + qt.tensor(a, sp))
    Ha = g * qt.tensor(at, sm)
    Hb = g * qt.tensor(a, sp)
    H = [[Ha, lambda t, args: np.exp(-1j*delta*t)],
         [Hb, lambda t, args: np.exp(1j*delta*t)]]
    c_ops = [
        qt.tensor(np.sqrt(kappa*(1+n_th)) * a, Ia),
        qt.tensor(np.sqrt(kappa*n_th) * at, Ia),
        qt.tensor(Ic, np.sqrt(gamma) * sm),
    ]

    psi0 = qt.tensor(qt.fock(N, 0), (qt.basis(2, 0) + qt.basis(2, 1)).unit())
    exp_n = qt.mesolve(H, psi0, tspan, c_ops, [qt.tensor(a, sp)], options=options).expect[0]
    return np.real(exp_n)
    def test_measure(self):
        #Defines all needed variables for a test
        index = 0

        psi = qutip.basis(2, 1)
        psi = psi.full()

        eResults = []

        eResults.append(numpy.zeros(1))

        sp = qutip.sigmap()
        sm = qutip.sigmam()
        no = sp * sm
        eOps = []
        eOps.append(no)
        for i, eOp in enumerate(eOps):
            eOps[i] = eOp.full()
            eOps[i] = scipy.sparse.csc_matrix(eOps[i])

        histograms = []

        savingSettings = QJMCAA.SavingSettings()

        #Tests with no histograms set
        QJMCMeasure.measure(index, psi, eResults, eOps, histograms,
                            savingSettings)

        self.assertEqual(histograms, [])
        self.assertEqual(eResults, [[0.]])
Exemple #19
0
 def destroy(self, mode):
     """Returns a destruction operator for the given mode
     """
     ops = []
     for m, i in zip(self.modes(), it.count()):
         if m == mode:
             ops.append(qt.sigmam())
         else:
             ops.append(qt.qeye(self.nfock(mode)))
     return qt.tensor(ops)
Exemple #20
0
    def get_hamiltonian(self, controls):
        H_control = self.get_hamiltonian_control(controls)
        c_ops = []

        if self.gamma[0] > 0.0:
            c_ops.append(np.sqrt(self.gamma[0]) * q.sigmam())

        if self.gamma[1] > 0.0:
            c_ops.append(np.sqrt(self.gamma[1]) * q.sigmaz())
        #H_noise = [self.get_hamiltonian_operator_noise(), self.noise]
        return [H_control, c_ops]
def Hamiltonian(parameters, lattice):
    #Constructs the operators
    #(these are the essential operators that are needed for spin)
    si = qutip.qeye(2)
    sx = qutip.sigmax()
    #sy = qutip.sigmay()
    #sz = qutip.sigmaz()
    sp = qutip.sigmap()
    sm = qutip.sigmam()
    no = sp * sm

    #Constructs operators for the chain of length N
    #si_list = []
    sx_list = []
    #sy_list = []
    #sz_list = []
    #sp_list = []
    #sm_list = []
    no_list = []

    #Runs over each site defining the operator on that site
    for k in range(lattice.numberOfSites):
        #Puts an indentity on every site
        op_list = [si] * lattice.numberOfSites
        #Defines the sigma_x on site k
        op_list[k] = sx
        sx_list.append(qutip.tensor(op_list))
        #op_list[k] = sy
        #sy_list.append(qutip.tensor(op_list))
        #op_list[k] = sz
        #sz_list.append(qutip.tensor(op_list))
        #op_list[k] = sp
        #sp_list.append(qutip.tensor(op_list))
        #op_list[k] = sm
        #sm_list.append(qutip.tensor(op_list))
        op_list[k] = no
        no_list.append(qutip.tensor(op_list))

    #Constructs the Hamiltonian
    H = 0

    #Periodic boundary conditions
    #TODO define the periodic boundary conditions and closed in QJMCMath.neighbour operator with a choice
    for k in range(lattice.numberOfSites):
        H += (parameters.omega *
              (no_list[QJMCMath.neighbour(k, lattice.numberOfSites, -1)] +
               no_list[QJMCMath.neighbour(k, lattice.numberOfSites, 1)]) *
              sx_list[k])

    #All objects must be in a scipy sparse format
    H = H.full()
    H = scipy.sparse.csc_matrix(H)
    return H
Exemple #22
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)
Exemple #23
0
 def test_collapse_with_different_tlist(self):
     """
     Test if there are errors raised because of wrong tlist handling.
     """
     qc = QubitCircuit(1)
     qc.add_gate("X", 0)
     proc = LinearSpinChain(1)
     proc.load_circuit(qc)
     tlist = np.linspace(0, 30., 100)
     coeff = tlist * 0.1
     noise = DecoherenceNoise(sigmam(), targets=0, coeff=coeff, tlist=tlist)
     proc.add_noise(noise)
     proc.run_state(basis(2, 0))
Exemple #24
0
def construct_ham_floquet(params):
    sz = tensor(sigmaz(), qeye(params.c_levels))
    sx = tensor(sigmax(), qeye(params.c_levels))
    sm = tensor(sigmam(), qeye(params.c_levels))
    a = tensor(qeye(2), destroy(params.c_levels))

    ham0 = (params.fc - params.fp) * a.dag() * a + 0.5 * (params.fa -
                                                          params.fp) * sz
    ham0 += params.g * (sm * a.dag() + sm.dag() * a)
    ham0 += 0.5 * params.f1 * (sm + sm.dag())
    ham0 *= 2 * np.pi

    return ham0
def expectationOperators(lattice, settings):
    #Constructs the operators
    si = qutip.qeye(2)
    #sx = qutip.sigmax()
    #sy = qutip.sigmay()
    #sz = qutip.sigmaz()
    sp = qutip.sigmap()
    sm = qutip.sigmam()
    no = sp * sm
    #print no

    #Constructs operators for the chain of length N
    #si_list = []
    #sx_list = []
    #sy_list = []
    #sz_list = []
    #sp_list = []
    #sm_list = []
    no_list = []

    #si_list.append(qutip.tensor([si] * N))

    for k in range(lattice.numberOfSites):
        op_list = [si] * lattice.numberOfSites
        #op_list[k] = sx
        #sx_list.append(qutip.tensor(op_list))
        #op_list[k] = sy
        #sy_list.append(qutip.tensor(op_list))
        #op_list[k] = sz
        #sz_list.append(qutip.tensor(op_list))
        #op_list[k] = sp
        #sp_list.append(qutip.tensor(op_list))
        #op_list[k] = sm
        #sm_list.append(qutip.tensor(op_list))
        op_list[k] = no
        no_list.append(qutip.tensor(op_list))

    #Defines the expectation operators
    e_op_list = []

    #This adds on the measurement of the average population per site
    e_op_list.append(no_list[0])
    for i in range(1, lattice.numberOfSites):
        e_op_list[0] += no_list[i]
    e_op_list[0] /= lattice.numberOfSites

    for i, eOp in enumerate(e_op_list):
        e_op_list[i] = eOp.full()
        e_op_list[i] = scipy.sparse.csc_matrix(e_op_list[i])

    return e_op_list
Exemple #26
0
def test_pull_572_error():
    """
    brmesolve: Check for #572 bug.
    """
    w1, w2, w3 = 1, 2, 3
    gamma2, gamma3 = 0.1, 0.1
    id2 = qutip.qeye(2)

    # Hamiltonian for three uncoupled qubits
    H = (w1 / 2. * qutip.tensor(qutip.sigmaz(), id2, id2) +
         w2 / 2. * qutip.tensor(id2, qutip.sigmaz(), id2) +
         w3 / 2. * qutip.tensor(id2, id2, qutip.sigmaz()))

    # White noise
    def S2(w):
        return gamma2

    def S3(w):
        return gamma3

    qubit_2_x = qutip.tensor(id2, qutip.sigmax(), id2)
    qubit_3_x = qutip.tensor(id2, id2, qutip.sigmax())
    # Bloch-Redfield tensor including dissipation for qubits 2 and 3 only
    R, ekets = qutip.bloch_redfield_tensor(H,
                                           [[qubit_2_x, S2], [qubit_3_x, S3]])
    # Initial state : first qubit is excited
    grnd2 = qutip.sigmam() * qutip.sigmap()  # 2x2 ground
    exc2 = qutip.sigmap() * qutip.sigmam()  # 2x2 excited state
    ini = qutip.tensor(exc2, grnd2, grnd2)  # Full system

    # Projector on the excited state of qubit 1
    proj_up1 = qutip.tensor(exc2, id2, id2)

    # Solution of the master equation
    times = np.linspace(0, 10. / gamma3, 1000)
    sol = qutip.bloch_redfield_solve(R, ekets, ini, times, [proj_up1])
    np.testing.assert_allclose(sol[0], np.ones_like(times))
Exemple #27
0
def c_ops_gen_jc(params, alpha=0):
    c_ops = []
    sm = tensor(sigmam(), qeye(params.c_levels))
    a = tensor(qeye(2), destroy(params.c_levels)) + alpha
    if params.gamma > 0.0:
        c_ops.append(np.sqrt(2 * np.pi * params.gamma * (1 + params.n_t)) * sm)
        if params.n_t > 0:
            c_ops.append(np.sqrt(2 * np.pi * params.gamma * params.n_t) * sm.dag())
    if params.gamma_phi > 0.0:
        c_ops.append(np.sqrt(2 * np.pi * params.gamma_phi) * sm.dag() * sm)
    if params.kappa > 0.0:
        c_ops.append(np.sqrt(2 * np.pi * params.kappa * (1 + params.n_c)) * a)
        if params.n_c > 0:
            c_ops.append(np.sqrt(2 * np.pi * params.kappa * params.n_c) * a.dag())
    return c_ops
def compute_free_evolution_hamiltonian(nb_qubits, nb_drives, omega, omega0,
                                       hbar):
    H_res = qt.qzero([[2, 2]])

    for index_qubit in range(nb_qubits):
        H_qubit_tmp = qt.Qobj(np.zeros((2, 2)))

        for index_drive in range(nb_drives):
            delta = omega[index_drive] - omega0[index_qubit]
            H_qubit_tmp += -hbar * delta * (qt.sigmam() * qt.sigmap())

        H_res = H_res + compute_multiqbt_hamil(H_qubit_tmp, nb_qubits,
                                               index_qubit, 2)

    return H_res
def expectationOperators():
    #si = qutip.qeye(2)
    sp = qutip.sigmap()
    sm = qutip.sigmam()
    no = sp * sm

    eOps = []

    eOps.append(no)

    for i, eOp in enumerate(eOps):
        eOps[i] = eOp.full()
        eOps[i] = scipy.sparse.csc_matrix(eOps[i])

    return eOps
Exemple #30
0
def get_spin_hamiltonian(op_terms: List[Op]):
    sigma_dict = {
        "sigma_+": qutip.sigmap(),
        "sigma_-": qutip.sigmam(),
        "sigma_z": qutip.sigmaz()
    }

    terms = []
    for op in op_terms:
        qutip_list = []
        for symbol in op.split_symbol:
            qutip_list.append(sigma_dict[symbol])
        qutip_term = qutip.tensor(qutip_list)
        qutip_term *= op.factor
        terms.append(qutip_term)
    return sum(terms)
def hamiltonians_n_atoms_C2(NH1, NH2, N_atoms):
    #Contructs the Jaynes_cummings hamiltonians for the interaction of each atom with C2
    #The result is given as a list of hamiltonians in the same order as in the tensor product
    hamiltonians = []
    Hd_temp = qt.tensor(qt.qeye(NH1), qt.destroy(NH2))
    Hc_temp = qt.tensor(qt.qeye(NH1), qt.create(NH2))
    for i in range(N_atoms):
        for j, H in enumerate(hamiltonians):
            hamiltonians[j] = qt.tensor(qt.qeye(2), hamiltonians[j])
        hamiltonians = [
            .5 *
            (qt.tensor(qt.sigmap(), Hd_temp) + qt.tensor(qt.sigmam(), Hc_temp))
        ] + hamiltonians
        Hd_temp = qt.tensor(qt.qeye(2), Hd_temp)
        Hc_temp = qt.tensor(qt.qeye(2), Hc_temp)
    return (hamiltonians)
Exemple #32
0
def test_solver_accepts_list_hamiltonian():
    """
    brmesolve: input list of Qobj
    """
    delta = 0.0 * 2 * np.pi
    epsilon = 0.5 * 2 * np.pi
    gamma = 0.25
    c_ops = [np.sqrt(gamma) * qutip.sigmam()]
    e_ops = pauli_spin_operators()
    H = [delta * 0.5 * qutip.sigmax(), epsilon * 0.5 * qutip.sigmaz()]
    psi0 = (2 * qutip.basis(2, 0) + qutip.basis(2, 1)).unit()
    times = np.linspace(0, 10, 100)
    me = qutip.mesolve(H, psi0, times, c_ops=c_ops, e_ops=e_ops).expect
    brme = qutip.brmesolve(H, psi0, times, [], e_ops, c_ops).expect
    for me_expectation, brme_expectation in zip(me, brme):
        np.testing.assert_allclose(me_expectation, brme_expectation, atol=1e-8)
Exemple #33
0
def construct_ham_floquet_rwa(params):
    sz = tensor(sigmaz(), qeye(params.c_levels))
    sx = tensor(sigmax(), qeye(params.c_levels))
    sm = tensor(sigmam(), qeye(params.c_levels))
    a = tensor(qeye(2), destroy(params.c_levels))

    fap = params.fa - params.fp
    fr = np.sqrt(fap**2 + params.f1**2)
    sin_alpha = fap / np.sqrt(fap**2 + params.f1**2)
    g_prime = 0.5 * params.g * (sin_alpha + 1)

    ham0 = 0.5 * fr * sz + (params.fc - params.fp) * a.dag() * a + g_prime * (
        sm * a.dag() + sm.dag() * a)
    ham0 *= 2 * np.pi

    return ham0
Exemple #34
0
    def __init__(self, init_state, target_state, num_focks, num_steps, alpha_list=[1]):
        self.init_state = init_state
        self.target_state = target_state
        self.num_focks = num_focks

        Sp = tensor(sigmap(), qeye(num_focks))
        Sm = tensor(sigmam(), qeye(num_focks))
        a = tensor(qeye(2), destroy(num_focks))
        adag = tensor(qeye(2), create(num_focks))

        # Control Hamiltonians
        self._ctrl_hamils = [Sp + Sm, Sp * a + Sm * adag, Sp * adag + Sm * a,
                             1j * (Sp - Sm), 1j * (Sp * a - Sm * adag), 1j * (Sp * adag - Sm * a)]
        # Number operator
        self._adaga = adag * a
        self.num_steps = num_steps
        self.alpha_list = np.array(alpha_list + [0] * (3 - len(alpha_list)))
Exemple #35
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)
Exemple #36
0
    def qubit_integrate(self, tlist, psi0, epsilon, delta, g1, g2):

        H = epsilon / 2.0 * sigmaz() + delta / 2.0 * sigmax()

        c_op_list = []

        rate = g1
        if rate > 0.0:
            c_op_list.append(np.sqrt(rate) * sigmam())

        rate = g2
        if rate > 0.0:
            c_op_list.append(np.sqrt(rate) * sigmaz())

        output = mesolve(H, psi0, tlist, c_op_list, [sigmax(), sigmay(), sigmaz()])
        expt_list = output.expect[0], output.expect[1], output.expect[2]

        return expt_list[0], expt_list[1], expt_list[2]
Exemple #37
0
    def testTLS(self):
        "brmesolve: qubit"

        delta = 0.0 * 2 * np.pi
        epsilon = 0.5 * 2 * np.pi
        gamma = 0.25
        times = np.linspace(0, 10, 100)
        H = delta/2 * sigmax() + epsilon/2 * sigmaz()
        psi0 = (2 * basis(2, 0) + basis(2, 1)).unit()
        c_ops = [np.sqrt(gamma) * sigmam()]
        a_ops = [sigmax()]
        e_ops = [sigmax(), sigmay(), sigmaz()]
        res_me = mesolve(H, psi0, times, c_ops, e_ops)
        res_brme = brmesolve(H, psi0, times, a_ops, e_ops,
                             spectra_cb=[lambda w: gamma * (w >= 0)])

        for idx, e in enumerate(e_ops):
            diff = abs(res_me.expect[idx] - res_brme.expect[idx]).max()
            assert_(diff < 1e-2)
Exemple #38
0
def testCOPS():
    """
    brmesolve: c_ops alone
    """

    delta = 0.0 * 2 * np.pi
    epsilon = 0.5 * 2 * np.pi
    gamma = 0.25
    times = np.linspace(0, 10, 100)
    H = delta/2 * sigmax() + epsilon/2 * sigmaz()
    psi0 = (2 * basis(2, 0) + basis(2, 1)).unit()
    c_ops = [np.sqrt(gamma) * sigmam()]
    e_ops = [sigmax(), sigmay(), sigmaz()]
    res_me = mesolve(H, psi0, times, c_ops, e_ops)
    res_brme = brmesolve(H, psi0, times, [], e_ops,
                         spectra_cb=[], c_ops=c_ops)

    for idx, e in enumerate(e_ops):
        diff = abs(res_me.expect[idx] - res_brme.expect[idx]).max()
        assert_(diff < 1e-2)
Exemple #39
0
def run():
    from mpi4py import MPI
    comm = MPI.COMM_WORLD
    size = comm.Get_size()
    rank = comm.Get_rank()
    print "Process number", rank, "of", size, "total."

    neq = 2
    gamma = 1.0
    psi0 = qt.basis(neq,neq-1)
    H = qt.sigmax()
    c_ops = [np.sqrt(gamma)*qt.sigmax()]
    e_ops = [qt.sigmam()*qt.sigmap()]

    tlist = np.linspace(0,10,100)

    ntraj=100

    # One CPU per MPI process
    opts = qt.Odeoptions()
    opts.num_cpus = 1

    # Solve
    sols = mcf90.mcsolve_f90(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,options=opts)
    #sols = qt.mcsolve(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,options=opts)

    # Gather data
    sols = comm.gather(sols,root=0)
    if (rank==0):
        sol = sols[0]
        sol.expect = np.array(sols[0].expect)
        plt.figure()
        plt.plot(tlist,sols[0].expect[0],'r',label='proc '+str(0))
        for i in range(1,size):
            plt.plot(tlist,sols[i].expect[0],'r',label='proc '+str(i))
            sol.expect += np.array(sols[i].expect)
        sol.expect = sol.expect/size
        plt.plot(tlist,sol.expect[0],'b',label='average')
        plt.legend()
        plt.show()
Exemple #40
0
def spin_algebra(N, op=None):
    """Create the list [sx, sy, sz] with the spin operators.

    The operators are constructed for a collection of N two-level systems
    (TLSs). Each element of the list, i.e., sx, is a vector of `qutip.Qobj`
    objects (spin matrices), as it cointains the list of the SU(2) Pauli
    matrices for the N TLSs. Each TLS operator sx[i], with i = 0, ..., (N-1),
    is placed in a :math:`2^N`-dimensional Hilbert space.

    Notes
    -----
    sx[i] is :math:`\\frac{\\sigma_x}{2}` in the composite Hilbert space.

    Parameters
    ----------
    N: int
        The number of two-level systems.

    Returns
    -------
    spin_operators: list or :class: qutip.Qobj
        A list of `qutip.Qobj` operators - [sx, sy, sz] or the
        requested operator.
    """
    # 1. Define N TLS spin-1/2 matrices in the uncoupled basis
    N = int(N)
    sx = [0 for i in range(N)]
    sy = [0 for i in range(N)]
    sz = [0 for i in range(N)]
    sp = [0 for i in range(N)]
    sm = [0 for i in range(N)]

    sx[0] = 0.5 * sigmax()
    sy[0] = 0.5 * sigmay()
    sz[0] = 0.5 * sigmaz()
    sp[0] = sigmap()
    sm[0] = sigmam()

    # 2. Place operators in total Hilbert space
    for k in range(N - 1):
        sx[0] = tensor(sx[0], identity(2))
        sy[0] = tensor(sy[0], identity(2))
        sz[0] = tensor(sz[0], identity(2))
        sp[0] = tensor(sp[0], identity(2))
        sm[0] = tensor(sm[0], identity(2))

    # 3. Cyclic sequence to create all N operators
    a = [i for i in range(N)]
    b = [[a[i - i2] for i in range(N)] for i2 in range(N)]

    # 4. Create N operators
    for i in range(1, N):
        sx[i] = sx[0].permute(b[i])
        sy[i] = sy[0].permute(b[i])
        sz[i] = sz[0].permute(b[i])
        sp[i] = sp[0].permute(b[i])
        sm[i] = sm[0].permute(b[i])

    spin_operators = [sx, sy, sz]

    if not op:
        return spin_operators
    elif op == 'x':
        return sx
    elif op == 'y':
        return sy
    elif op == 'z':
        return sz
    elif op == '+':
        return sp
    elif op == '-':
        return sm
    else:
        raise TypeError('Invalid type')
Exemple #41
0
def test():
    gamma = 1.
    neq = 2
    psi0 = qt.basis(neq,neq-1)
    #a = qt.destroy(neq)
    #ad = a.dag()
    #H = ad*a
    #c_ops = [gamma*a]
    #e_ops = [ad*a]
    H = qt.sigmax()
    c_ops = [np.sqrt(gamma)*qt.sigmax()]
    #c_ops = []
    e_ops = [qt.sigmam()*qt.sigmap(),qt.sigmap()*qt.sigmam()]
    #e_ops = []

    # Times
    T = 2.0
    dt = 0.1
    nstep = int(T/dt)
    tlist = np.linspace(0,T,nstep)

    ntraj=100

    # set options
    opts = qt.Odeoptions()
    opts.num_cpus=2
    #opts.mc_avg = True
    #opts.gui=False
    #opts.max_step=1000
    #opts.atol =
    #opts.rtol =

    sol_f90 = qt.Odedata()
    start_time = time.time()
    sol_f90 = mcf90.mcsolve_f90(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,options=opts)
    print "mcsolve_f90 solutiton took", time.time()-start_time, "s"

    sol_me = qt.Odedata()
    start_time = time.time()
    sol_me = qt.mesolve(H,psi0,tlist,c_ops,e_ops,options=opts)
    print "mesolve solutiton took", time.time()-start_time, "s"

    sol_mc = qt.Odedata()
    start_time = time.time()
    sol_mc = qt.mcsolve(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,options=opts)
    print "mcsolve solutiton took", time.time()-start_time, "s"

    if (e_ops == []):
        e_ops = [qt.sigmam()*qt.sigmap(),qt.sigmap()*qt.sigmam()]
        sol_f90expect = [np.array([0.+0.j]*nstep)]*len(e_ops)
        sol_mcexpect = [np.array([0.+0.j]*nstep)]*len(e_ops)
        sol_meexpect = [np.array([0.+0.j]*nstep)]*len(e_ops)
        for i in range(len(e_ops)):
            if (not opts.mc_avg):
                sol_f90expect[i] = sum([qt.expect(e_ops[i],
                    sol_f90.states[j]) for j in range(ntraj)])/ntraj
                sol_mcexpect[i] = sum([qt.expect(e_ops[i],
                    sol_mc.states[j]) for j in range(ntraj)])/ntraj
            else:
                sol_f90expect[i] = qt.expect(e_ops[i],sol_f90.states)
                sol_mcexpect[i] = qt.expect(e_ops[i],sol_mc.states)
            sol_meexpect[i] = qt.expect(e_ops[i],sol_me.states)
    elif (not opts.mc_avg):
        sol_f90expect = sum(sol_f90.expect,0)/ntraj
        sol_mcexpect = sum(sol_f90.expect,0)/ntraj
        sol_meexpect = sol_me.expect
    else:
        sol_f90expect = sol_f90.expect
        sol_mcexpect = sol_mc.expect
        sol_meexpect = sol_me.expect

    plt.figure()
    for i in range(len(e_ops)):
        plt.plot(tlist,sol_f90expect[i],'b')
        plt.plot(tlist,sol_mcexpect[i],'g')
        plt.plot(tlist,sol_meexpect[i],'k')

    return sol_f90, sol_mc
Exemple #42
0
import cascade

gamma = 1.0 # coupling strength to reservoir
phi = 1.*np.pi # phase shift in fb loop
eps = 2.0*np.pi*gamma # eps/2 = Rabi frequency
delta = 0. # detuning

# time delay
tau = np.pi/(eps)
print 'tau =',tau

dim_S = 2
Id = qt.spre(qt.qeye(dim_S))*qt.spost(qt.qeye(dim_S))

# Hamiltonian and jump operators
H_S = delta*qt.sigmap()*qt.sigmam() + eps*(qt.sigmam()+qt.sigmap())
L1 = sp.sqrt(gamma)*qt.sigmam()
L2 = sp.exp(1j*phi)*L1

# initial state
rho0 = qt.ket2dm(qt.basis(2,0))

# times to evaluate rho(t)
tlist=np.arange(0.0001,2*tau,0.01)

def run(rho0=rho0,tau=tau,tlist=tlist):
    # run feedback simulation
    opts = qt.Options()
    opts.nsteps = 1e7
    sol = np.array([rho0]*len(tlist))
    for i,t in enumerate(tlist):