Ejemplo n.º 1
0
def gkp(hilbert_size, delta, mu=0, zrange=20):
    """Generates a GKP state. 

    For a detailed discussion on the definition see
    `Albert, Victor V. et al. “Performance and Structure of Single-Mode Bosonic Codes.” Physical Review A 97.3 (2018) <https://arxiv.org/abs/1708.05010>`_
    and `Ahmed, Shahnawaz et al., “Classification and reconstruction of quantum states with neural networks.” Journal <https://arxiv.org/abs/1708.05010>`_
    
    Args:
        hilbert_size (int): Hilbert space size (cutoff).
        delta (float): 
        mu (int, optional): Logical encoding (0/1)
                            default: 0
        zrange (int, optional): The number of lattice points to loop over to construct
                                the grid of states. This depends on the Hilbert space
                                size and the delta value.
                                default: 20
    
    Returns:
        :class:`qutip.Qobj`: GKP state.
    """
    gkp = 0 * coherent(hilbert_size, 0)

    c = np.sqrt(np.pi / 2)

    zrange = range(-20, 20)

    for n1 in zrange:
        for n2 in zrange:
            a = c * (2 * n1 + mu + 1j * n2)
            alpha = coherent(hilbert_size, a)
            gkp += (np.exp(-(delta**2) * np.abs(a)**2) *
                    np.exp(-1j * c**2 * 2 * n1 * n2) * alpha)

    ket = gkp.unit()
    return ket
Ejemplo n.º 2
0
def H_2cat(alpha):
    C_p = (qt.coherent(NFock, alpha) + qt.coherent(NFock, -alpha)).unit()
    C_m = (qt.coherent(NFock, alpha) - qt.coherent(NFock, -alpha)).unit()

    H = -(qt.ket2dm(C_p) - qt.ket2dm(C_m))

    return H
Ejemplo n.º 3
0
 def testCoherentState(self):
     """
     states: coherent state
     """
     N = 10
     alpha = 0.5
     c1 = coherent(N, alpha) # displacement method
     c2 = coherent(7, alpha, offset=3) # analytic method
     assert_(abs(expect(destroy(N), c1) - alpha) < 1e-10)
     assert_((c1[3:]-c2).norm() < 1e-7)
Ejemplo n.º 4
0
 def testCoherentState(self):
     """
     states: coherent state
     """
     N = 10
     alpha = 0.5
     c1 = coherent(N, alpha)  # displacement method
     c2 = coherent(7, alpha, offset=3)  # analytic method
     assert_(abs(expect(destroy(N), c1) - alpha) < 1e-10)
     assert_((c1[3:] - c2).norm() < 1e-7)
Ejemplo n.º 5
0
def test_CoherentState():
    N = 10
    alpha = 0.5
    c1 = qutip.coherent(N, alpha)  # displacement method
    c2 = qutip.coherent(7, alpha, offset=3)  # analytic method
    c3 = qutip.coherent(N, alpha, offset=0, method="analytic")
    np.testing.assert_allclose(c1.full()[3:], c2.full(), atol=1e-7)
    np.testing.assert_allclose(c1.full(), c3.full(), atol=1e-7)
    with pytest.raises(ValueError) as e:
        qutip.coherent(N, alpha, method="other")
    assert str(e.value) == ("The method option can only take "
                            "values 'operator' or 'analytic'")
Ejemplo n.º 6
0
def test_ssesolve_bad_e_ops():
    tol = 0.01
    N = 4
    ntraj = 10
    nsubsteps = 100
    a = destroy(N)
    b = destroy(N - 1)

    H = [num(N)]
    psi0 = coherent(N, 2.5)
    sc_ops = [a + a.dag()]
    e_ops = [a.dag() * a, a + a.dag(), (-1j) * (b - b.dag()), qeye(N + 1)]
    times = np.linspace(0, 10, 101)
    with pytest.raises(TypeError) as exc:
        res = ssesolve(H,
                       psi0,
                       times,
                       sc_ops,
                       e_ops,
                       solver=None,
                       noise=1,
                       ntraj=ntraj,
                       nsubsteps=nsubsteps,
                       method='homodyne',
                       map_func=parallel_map)
Ejemplo n.º 7
0
def test_ssesolve_heterodyne():
    "Stochastic: ssesolve: heterodyne, time-dependent H"
    tol = 0.01

    N = 4
    gamma = 0.25
    ntraj = 25
    nsubsteps = 100
    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())]

    times = np.linspace(0, 2.5, 50)
    res_ref = mesolve(H, psi0, times, sc_ops, e_ops, args={"a":2})
    res = ssesolve(H, psi0, times, sc_ops, e_ops,
                   ntraj=ntraj, nsubsteps=nsubsteps,
                   method='heterodyne', store_measurement=True,
                   map_func=parallel_map, args={"a":2})

    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)
    assert_(all([m.shape == (len(times), len(sc_ops), 2)
                 for m in res.measurement]))
Ejemplo n.º 8
0
def test_ssesolve_feedback():
    "Stochastic: ssesolve: time-dependent H with feedback"
    tol = 0.01
    N = 4
    ntraj = 10
    nsubsteps = 100
    a = destroy(N)

    H = [num(N)]
    psi0 = coherent(N, 2.5)
    sc_ops = [[a + a.dag(), f_dargs]]
    e_ops = [a.dag() * a, a + a.dag(), (-1j) * (a - a.dag()), qeye(N)]

    times = np.linspace(0, 10, 101)
    res_ref = mesolve(H,
                      psi0,
                      times,
                      sc_ops,
                      e_ops,
                      args={"expect_op_3": qeye(N)})
    res = ssesolve(H,
                   psi0,
                   times,
                   sc_ops,
                   e_ops,
                   solver=None,
                   noise=1,
                   ntraj=ntraj,
                   nsubsteps=nsubsteps,
                   method='homodyne',
                   map_func=parallel_map,
                   args={"expect_op_3": qeye(N)})
Ejemplo n.º 9
0
def test_ssesolve_homodyne():
    "Stochastic: smesolve: homodyne"
    tol = 0.01

    N = 4
    gamma = 0.25
    ntraj = 25
    nsubsteps = 100
    a = destroy(N)

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

    times = np.linspace(0, 2.5, 50)
    res_ref = mesolve(H, psi0, times, sc_ops, e_ops)
    res = smesolve(
        H,
        psi0,
        times,
        [],
        sc_ops,
        e_ops,
        ntraj=ntraj,
        nsubsteps=nsubsteps,
        method="homodyne",
        store_measurement=True,
        map_func=parallel_map,
    )

    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)
    assert_(all([m.shape == (len(times), len(sc_ops)) for m in res.measurement]))
Ejemplo n.º 10
0
def test_smesolve_photocurrent():
    "Stochastic: photocurrent_mesolve"
    tol = 0.01

    N = 4
    gamma = 0.25
    ntraj = 20
    nsubsteps = 100
    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())]

    times = np.linspace(0, 1.0, 21)
    res_ref = mesolve(H, psi0, times, sc_ops, e_ops, args={"a":2})
    res = photocurrent_mesolve(H, psi0, times, [], sc_ops, e_ops, args={"a":2},
                   ntraj=ntraj, nsubsteps=nsubsteps,  store_measurement=True,
                   map_func=parallel_map)

    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)
    assert_(all([m.shape == (len(times), len(sc_ops))
                 for m in res.measurement]))
Ejemplo n.º 11
0
def test_smesolve_photocurrent():
    "Stochastic: photocurrent_mesolve"
    tol = 0.01

    N = 4
    gamma = 0.25
    ntraj = 20
    nsubsteps = 100
    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())]

    times = np.linspace(0, 1.0, 21)
    res_ref = mesolve(H, psi0, times, sc_ops, e_ops, args={"a":2})
    res = photocurrent_mesolve(H, psi0, times, [], sc_ops, e_ops, args={"a":2},
                   ntraj=ntraj, nsubsteps=nsubsteps,  store_measurement=True,
                   map_func=parallel_map)

    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)
    assert_(all([m.shape == (len(times), len(sc_ops))
                 for m in res.measurement]))
def setup(N):
    alpha = 0.7
    xvec = np.linspace(-50, 50, 100)
    yvec = np.linspace(-50, 50, 100)
    state = qt.coherent(N, alpha)
    op = state * state.dag()
    return op, xvec, yvec
Ejemplo n.º 13
0
def cat(hilbert_size, alpha=None, S=None, mu=None):
    """
    Generates a cat state. For a detailed discussion on the definition
    see `Albert, Victor V. et al. “Performance and Structure of Single-Mode Bosonic Codes.” Physical Review A 97.3 (2018) <https://arxiv.org/abs/1708.05010>`_
    and `Ahmed, Shahnawaz et al., “Classification and reconstruction of quantum states with neural networks.” Journal <https://arxiv.org/abs/1708.05010>`_
    
    Args:
    -----
        N (int): Hilbert size dimension.
        alpha (complex64): Complex number determining the amplitude.
        S (int): An integer >= 0 determining the number of coherent states used
                 to generate the cat superposition. S = {0, 1, 2, ...}.
                 corresponds to {2, 4, 6, ...} coherent state superpositions.
        mu (int): An integer 0/1 which generates the logical 0/1 encoding of 
                  a computational state for the cat state.


    Returns:
    -------
        cat (:class:`qutip.Qobj`): Cat state density matrix
    """
    if alpha == None:
        alpha = random_alpha(2, 3)

    if S == None:
        S = np.random.randint(0, 3)

    if mu is None:
        mu = np.random.randint(0, 2)

    kend = 2 * S + 1
    cstates = 0 * (coherent(hilbert_size, 0))

    for k in range(0, int((kend + 1) / 2)):
        sign = 1

        if k >= S:
            sign = (-1) ** int(mu > 0.5)

        prefactor = np.exp(1j * (np.pi / (S + 1)) * k)

        cstates += sign * coherent(hilbert_size, prefactor * alpha * (-((1j) ** mu)))
        cstates += sign * coherent(hilbert_size, -prefactor * alpha * (-((1j) ** mu)))

    rho = cstates * cstates.dag()
    return rho.unit(), mu
Ejemplo n.º 14
0
def qfunc_rere(N, rho, x_vec):
    #if(rho.type == 'ket'):
    #   rho = qt.ket2dm(rho)
    #elif(rho.type is not 'oper'):
    #   print('invalid type')

    num_points = len(x_vec)
    Q = np.zeros((num_points, num_points), dtype = complex)
    for i, j in itertools.product(range(num_points), range(num_points)):
        #a = qt.tensor(qt.coherent(N, x_vec[i]), qt.qeye(N))
        #b = qt.tensor(qt.qeye(N), qt.coherent(N, x_vec[j]))
        alpha = np.array(qt.tensor(qt.coherent(N, x_vec[i]), qt.coherent(N, x_vec[j])).full())

        Q[i][j] = np.absolute(np.matmul(np.matmul(alpha.T, rho), alpha))
        #Q[i][j] = (2*np.pi)**2 * a.dag()*(b.dag()*rho*b)*a
        #Q[i][j] = (2*np.pi)**2 * a
    return Q
Ejemplo n.º 15
0
 def test_against_naive_implementation(self, xs, ys, g, size):
     state = qutip.rand_dm(size)
     state_np = state.full()
     x, y = np.meshgrid(xs, ys)
     alphas = 0.5 * g * (x + 1j * y)
     naive = np.empty(alphas.shape, dtype=np.float64)
     for i, alpha in enumerate(alphas.flat):
         coh = qutip.coherent(size, alpha, method='analytic').full()
         naive.flat[i] = (coh.conj().T @ state_np @ coh).real
     naive *= (0.5 * g)**2 / np.pi
     np.testing.assert_allclose(naive, qutip.qfunc(state, xs, ys, g))
     np.testing.assert_allclose(naive, qutip.QFunc(xs, ys, g)(state))
Ejemplo n.º 16
0
def test_ket2dm():
    N = 5
    ket = qutip.coherent(N, 2)
    bra = ket.dag()
    oper = qutip.ket2dm(ket)
    oper_from_bra = qutip.ket2dm(bra)
    assert qutip.expect(oper, ket) == pytest.approx(1.)
    assert qutip.isoper(oper)
    assert oper == ket * bra
    assert oper == oper_from_bra
    with pytest.raises(TypeError) as e:
        qutip.ket2dm(oper)
    assert str(e.value) == "Input is not a ket or bra vector."
Ejemplo n.º 17
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)
Ejemplo n.º 18
0
def gkp(hilbert_size, delta=None, mu = None):
    """Generates a GKP state
    """
    gkp = 0*coherent(hilbert_size, 0)

    c = np.sqrt(np.pi/2)

    if mu is None:
        mu = np.random.randint(2)

    if delta is None:
        delta = np.random.uniform(0.2, .50)

    zrange = range(-20, 20)

    for n1 in zrange:
        for n2 in zrange:        
            a = c*(2*n1 + mu + 1j*n2)
            alpha = coherent(hilbert_size, a)
            gkp += np.exp(-delta**2*np.abs(a)**2)*np.exp(-1j*c**2 * 2*n1 * n2)*alpha

    rho = gkp*gkp.dag()
    return rho.unit(), mu
Ejemplo n.º 19
0
def test_CoherentState():
    N = 10
    alpha = 0.5
    c1 = qutip.coherent(N, alpha)  # displacement method
    c2 = qutip.coherent(7, alpha, offset=3)  # analytic method
    c3 = qutip.coherent(N, alpha, offset=0, method="analytic")
    np.testing.assert_allclose(c1.full()[3:], c2.full(), atol=1e-7)
    np.testing.assert_allclose(c1.full(), c3.full(), atol=1e-7)
    with pytest.raises(ValueError) as e:
        qutip.coherent(N, alpha, method="other")
    assert str(e.value) == ("The method option can only take "
                            "values 'operator' or 'analytic'")
    with pytest.raises(ValueError) as e:
        qutip.coherent(N, alpha, offset=-1)
    assert str(e.value) == ("Offset must be non-negative")
    with pytest.raises(ValueError) as e:
        qutip.coherent(N, alpha, offset=1, method="operator")
    assert str(e.value) == (
        "The method 'operator' does not support offset != 0. Please"
        " select another method or set the offset to zero.")
Ejemplo n.º 20
0
def H_4cat(alpha):

    C_p = (qt.coherent(NFock, alpha) + qt.coherent(NFock, -alpha)).unit()
    C_m = (qt.coherent(NFock, alpha) - qt.coherent(NFock, -alpha)).unit()
    C_ip = (qt.coherent(NFock, 1j * alpha) +
            qt.coherent(NFock, -1j * alpha)).unit()
    C_im = (qt.coherent(NFock, 1j * alpha) -
            qt.coherent(NFock, -1j * alpha)).unit()

    C_0 = (C_p + C_ip).unit()
    C_1 = (C_m + -1j * C_im).unit()
    C_2 = (C_p - C_ip).unit()
    C_3 = (C_m + 1j * C_im).unit()

    H = -(qt.ket2dm(C_0) + qt.ket2dm(C_2) - qt.ket2dm(C_1) - qt.ket2dm(C_3))

    return H
Ejemplo n.º 21
0
def test_mc_seed_noreuse():
    "Monte-carlo: check not reusing seeds"
    N0 = 6
    N1 = 6
    N2 = 6
    # damping rates
    gamma0 = 0.1
    gamma1 = 0.4
    gamma2 = 0.1
    alpha = np.sqrt(2)  # initial coherent state param for mode 0
    tlist = np.linspace(0, 10, 2)
    ntraj = 500  # number of trajectories
    # define operators
    a0 = tensor(destroy(N0), qeye(N1), qeye(N2))
    a1 = tensor(qeye(N0), destroy(N1), qeye(N2))
    a2 = tensor(qeye(N0), qeye(N1), destroy(N2))
    # number operators for each mode
    num0 = a0.dag() * a0
    num1 = a1.dag() * a1
    num2 = a2.dag() * a2
    # dissipative operators for zero-temp. baths
    C0 = np.sqrt(2.0 * gamma0) * a0
    C1 = np.sqrt(2.0 * gamma1) * a1
    C2 = np.sqrt(2.0 * gamma2) * a2
    # initial state: coherent mode 0 & vacuum for modes #1 & #2
    psi0 = tensor(coherent(N0, alpha), basis(N1, 0), basis(N2, 0))
    # trilinear Hamiltonian
    H = 1j * (a0 * a1.dag() * a2.dag() - a0.dag() * a1 * a2)
    # run Monte-Carlo
    data1 = mcsolve(H,
                    psi0,
                    tlist, [C0, C1, C2], [num0, num1, num2],
                    ntraj=ntraj)
    data2 = mcsolve(H,
                    psi0,
                    tlist, [C0, C1, C2], [num0, num1, num2],
                    ntraj=ntraj)
    diff_flag = False
    for k in range(ntraj):
        if len(data1.col_times[k]) != len(data2.col_times[k]):
            diff_flag = 1
            break
        else:
            if not np.allclose(data1.col_which[k], data2.col_which[k]):
                diff_flag = 1
                break
    assert_equal(diff_flag, 1)
def f(N, options):
    eta = 1.5
    wc = 1.8
    wl = 2.
    delta_c = wl - wc
    alpha0 = 0.3 - 0.5j
    tspan = np.linspace(0, 10, 11)

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

    H = delta_c * n + eta * (a + at)

    psi0 = qt.coherent(N, alpha0)
    exp_n = qt.mesolve(H, psi0, tspan, [], [n], options=options).expect[0]
    return np.real(exp_n)
Ejemplo n.º 23
0
def test_smesolve_heterodyne():
    "Stochastic: smesolve: heterodyne, time-dependent H"
    tol = 0.01

    N = 4
    gamma = 0.25
    ntraj = 20
    nsubsteps = 100
    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())]

    times = np.linspace(0, 1.0, 21)
    res_ref = mesolve(H, psi0, times, sc_ops, e_ops, args={"a": 2})
    list_methods_tol = [
        'euler-maruyama', 'pc-euler', 'pc-euler-2', 'platen', 'milstein',
        'milstein-imp', 'rouchon', 'taylor15', 'taylor15-imp', 'explicit15'
    ]
    for solver in list_methods_tol:
        res = smesolve(H,
                       psi0,
                       times, [],
                       sc_ops,
                       e_ops,
                       ntraj=ntraj,
                       nsubsteps=nsubsteps,
                       args={"a": 2},
                       method='heterodyne',
                       store_measurement=True,
                       solver=solver,
                       map_func=parallel_map)
        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)
        assert_(
            all([
                m.shape == (len(times), len(sc_ops), 2)
                for m in res.measurement
            ]))
Ejemplo n.º 24
0
def test_smesolve_bad_e_ops():
    "Stochastic: ssesolve: time-dependent H with feedback"
    tol = 0.01
    N = 4
    ntraj = 10
    nsubsteps = 100
    a = destroy(N)

    H = [num(N)]
    psi0 = coherent(N, 2.5)
    sc_ops = [a + a.dag()]
    e_ops = [a.dag() * a, a + a.dag(), (-1j)*(a - a.dag()), qeye(N+1)]

    times = np.linspace(0, 10, 101)
    with pytest.raises(TypeError) as exc:
        res = smesolve(H, psi0, times, sc_ops=sc_ops, e_ops=e_ops, noise=1,
                       ntraj=ntraj, nsubsteps=nsubsteps, method='homodyne',
                       map_func=parallel_map)
Ejemplo n.º 25
0
def test_mc_seed_noreuse():
    "Monte-carlo: check not reusing seeds"
    N0 = 6
    N1 = 6
    N2 = 6
    # damping rates
    gamma0 = 0.1
    gamma1 = 0.4
    gamma2 = 0.1
    alpha = np.sqrt(2)  # initial coherent state param for mode 0
    tlist = np.linspace(0, 10, 2)
    ntraj = 500  # number of trajectories
    # define operators
    a0 = tensor(destroy(N0), qeye(N1), qeye(N2))
    a1 = tensor(qeye(N0), destroy(N1), qeye(N2))
    a2 = tensor(qeye(N0), qeye(N1), destroy(N2))
    # number operators for each mode
    num0 = a0.dag() * a0
    num1 = a1.dag() * a1
    num2 = a2.dag() * a2
    # dissipative operators for zero-temp. baths
    C0 = np.sqrt(2.0 * gamma0) * a0
    C1 = np.sqrt(2.0 * gamma1) * a1
    C2 = np.sqrt(2.0 * gamma2) * a2
    # initial state: coherent mode 0 & vacuum for modes #1 & #2
    psi0 = tensor(coherent(N0, alpha), basis(N1, 0), basis(N2, 0))
    # trilinear Hamiltonian
    H = 1j * (a0 * a1.dag() * a2.dag() - a0.dag() * a1 * a2)
    # run Monte-Carlo
    data1 = mcsolve(H, psi0, tlist, [C0, C1, C2], [num0, num1, num2],
                    ntraj=ntraj)
    data2 = mcsolve(H, psi0, tlist, [C0, C1, C2], [num0, num1, num2],
                    ntraj=ntraj)
    diff_flag = False
    for k in range(ntraj):
        if len(data1.col_times[k]) != len(data2.col_times[k]):
            diff_flag = 1
            break
        else:
            if not np.allclose(data1.col_which[k],data2.col_which[k]):
                diff_flag = 1
                break
    assert_equal(diff_flag, 1)
Ejemplo n.º 26
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)
Ejemplo n.º 27
0
def f(N, options):
    kappa = 1.
    eta = 1.5
    wc = 1.8
    wl = 2.
    delta_c = wl - wc
    alpha0 = 0.3 - 0.5j
    tspan = np.linspace(0, 10, 11)

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

    H = delta_c * n + eta * (a + at)
    J = [np.sqrt(kappa) * a]

    psi0 = qt.coherent(N, alpha0)
    exp_n = qt.mcsolve(H, psi0, tspan, J, [n], ntraj=evals,
                       options=options).expect[0]
    return np.real(exp_n)
def f(N, options):
    kappa = 1.
    eta = 1.5
    wc = 1.8
    wl = 2.
    # delta_c = wl - wc
    alpha0 = 0.3 - 0.5j
    tspan = np.linspace(0, 10, 11)

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

    J = [np.sqrt(kappa) * a]
    psi0 = qt.coherent(N, alpha0)
    H = [
        wc * n, [eta * a, lambda t, args: np.exp(1j * wl * t)],
        [eta * at, lambda t, args: np.exp(-1j * wl * t)]
    ]
    alpha_t = qt.mesolve(H, psi0, tspan, J, [a], options=options).expect[0]
    return np.real(alpha_t)
Ejemplo n.º 29
0
class TestSeeds:
    sizes = [6, 6, 6]
    dampings = [0.1, 0.4, 0.1]
    ntraj = 25  # Big enough to ensure there are differences without being slow
    a = [qutip.destroy(size) for size in sizes]
    H = 1j * (qutip.tensor(a[0], a[1].dag(), a[2].dag()) -
              qutip.tensor(a[0].dag(), a[1], a[2]))
    state = qutip.tensor(qutip.coherent(sizes[0], np.sqrt(2)),
                         qutip.basis(sizes[1:], [0, 0]))
    times = np.linspace(0, 10, 2)
    c_ops = [
        np.sqrt(2 * dampings[0]) * qutip.tensor(a[0], qutip.qeye(sizes[1:])),
        (np.sqrt(2 * dampings[1]) *
         qutip.tensor(qutip.qeye(sizes[0]), a[1], qutip.qeye(sizes[2]))),
        np.sqrt(2 * dampings[2]) * qutip.tensor(qutip.qeye(sizes[:2]), a[2]),
    ]

    def test_seeds_can_be_reused(self):
        args = (self.H, self.state, self.times)
        kwargs = {'c_ops': self.c_ops, 'ntraj': self.ntraj}
        first = qutip.mcsolve(*args, **kwargs)
        options = qutip.Options(seeds=first.seeds)
        second = qutip.mcsolve(*args, options=options, **kwargs)
        for first_t, second_t in zip(first.col_times, second.col_times):
            np.testing.assert_equal(first_t, second_t)
        for first_w, second_w in zip(first.col_which, second.col_which):
            np.testing.assert_equal(first_w, second_w)

    def test_seeds_are_not_reused_by_default(self):
        args = (self.H, self.state, self.times)
        kwargs = {'c_ops': self.c_ops, 'ntraj': self.ntraj}
        first = qutip.mcsolve(*args, **kwargs)
        second = qutip.mcsolve(*args, **kwargs)
        assert not all(
            np.array_equal(first_t, second_t)
            for first_t, second_t in zip(first.col_times, second.col_times))
        assert not all(
            np.array_equal(first_w, second_w)
            for first_w, second_w in zip(first.col_which, second.col_which))
Ejemplo n.º 30
0
def test_smesolve_heterodyne():
    "Stochastic: smesolve: heterodyne, time-dependent H"
    tol = 0.01

    N = 4
    gamma = 0.25
    ntraj = 20
    nsubsteps = 100
    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())]

    times = np.linspace(0, 1.0, 21)
    res_ref = mesolve(H, psi0, times, sc_ops, e_ops, args={"a":2})
    list_methods_tol = ['euler-maruyama',
                        'pc-euler',
                        'pc-euler-2',
                        'platen',
                        'milstein',
                        'milstein-imp',
                        'rouchon',
                        'taylor15',
                        'taylor15-imp',
                        'explicit15']
    for solver in list_methods_tol:
        res = smesolve(H, psi0, times, [], sc_ops, e_ops,
                       ntraj=ntraj, nsubsteps=nsubsteps, args={"a":2},
                       method='heterodyne', store_measurement=True,
                       solver=solver, map_func=parallel_map)
        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)
        assert_(all([m.shape == (len(times), len(sc_ops), 2)
                     for m in res.measurement]))
Ejemplo n.º 31
0
def test_ssesolve_feedback():
    "Stochastic: ssesolve: time-dependent H with feedback"
    tol = 0.01
    N = 4
    ntraj = 10
    nsubsteps = 100
    a = destroy(N)

    H = [num(N)]
    psi0 = coherent(N, 2.5)
    sc_ops = [[a + a.dag(), f_dargs]]
    e_ops = [a.dag() * a, a + a.dag(), (-1j) * (a - a.dag()), qeye(N)]

    times = np.linspace(0, 10, 101)
    res_ref = mesolve(H,
                      psi0,
                      times,
                      sc_ops,
                      e_ops,
                      args={"expect_op_3": qeye(N)})
    res = smesolve(H,
                   psi0,
                   times,
                   sc_ops=sc_ops,
                   e_ops=e_ops,
                   noise=1,
                   ntraj=ntraj,
                   nsubsteps=nsubsteps,
                   method='homodyne',
                   map_func=parallel_map,
                   args={"expect_op_3": qeye(N)})

    print(
        all([
            np.mean(abs(res.expect[idx] - res_ref.expect[idx])) < tol
            for idx in range(len(e_ops))
        ]))
def test_ssesolve_photocurrent():
    "Stochastic: ssesolve: photo-current"
    tol = 0.01

    N = 4
    gamma = 0.25
    ntraj = 25
    nsubsteps = 100
    a = destroy(N)

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

    times = np.linspace(0, 2.5, 50)
    res_ref = mesolve(H, psi0, times, sc_ops, e_ops)
    res = ssesolve(H,
                   psi0,
                   times,
                   sc_ops,
                   e_ops,
                   ntraj=ntraj,
                   nsubsteps=nsubsteps,
                   method='photocurrent',
                   store_measurement=True,
                   map_func=parallel_map)

    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)
    assert_(
        all([m.shape == (len(times), len(sc_ops)) for m in res.measurement]))
Ejemplo n.º 33
0
 def test_displacement(self):
     c0 = Cavity("c0", levels=10, kerr=-10e-6)
     c1 = Cavity("c1", levels=12, kerr=-10e-6)
     system = System("system", modes=[c0, c1])
     init_state = system.fock()
     for cavity in [c0, c1]:
         for _ in range(1):
             _ = tune_displacement(system,
                                   init_state,
                                   mode_name=cavity.name,
                                   verify=False)
         for alpha in [0, 1, -1, 1j, -1j, 2, -2, 2j, -2j]:
             ideal_state = cavity.tensor_with_zero(
                 qutip.coherent(cavity.levels, alpha))
             seq = get_sequence(system)
             unitary = cavity.displace(alpha, unitary=True)
             cavity.displace(alpha)
             result = seq.run(init_state)
             unitary_fidelity = (qutip.fidelity(unitary * init_state,
                                                ideal_state)**2)
             pulse_fidelity = qutip.fidelity(result.states[-1],
                                             ideal_state)**2
             self.assertGreater(unitary_fidelity, 1 - 1e-4)
             self.assertGreater(pulse_fidelity, 1 - 1e-4)
Ejemplo n.º 34
0
K = 1
P = 4 
#Local Parameters
k1_PCC = 0
k2_PCC = 1
k2_storage = 0
beta =  2# Nb of photons in PCC
alpha = 2 # Nb of photons in Storage
beta_inf = 2
alpha_inf = 2
chi0 = k2_PCC/30
Tp = np.pi/(4*chi0*beta)



C_beta_plus = qt.coherent(Nb, beta)+qt.coherent(Nb, -beta)
C_beta_plus = C_beta_plus/C_beta_plus.norm()
C_beta_moins = qt.coherent(Nb, beta)-qt.coherent(Nb, -beta)
C_beta_moins = C_beta_moins/C_beta_moins.norm()

PCC_0 = C_beta_plus

#C_alpha_plus = qt.coherent(Na, alpha)+qt.coherent(Na, -alpha)
#C_alpha_plus = C_alpha_plus/C_alpha_plus.norm()
#C_ialpha_plus = qt.coherent(Na, alpha*1j)+qt.coherent(Na, -alpha*1j)
#C_ialpha_plus = C_ialpha_plus/C_ialpha_plus.norm()
#storage_0 = C_alpha_plus + 1j*C_ialpha_plus
C_alpha_plus = qt.coherent(Nb, alpha)+qt.coherent(Nb, -alpha)
C_alpha_plus = C_alpha_plus/C_alpha_plus.norm()
C_alpha_moins = qt.coherent(Nb, alpha)-qt.coherent(Nb, -alpha)
C_alpha_moins = C_alpha_moins/C_alpha_moins.norm()
Ejemplo n.º 35
0
@author: andre
"""

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import qutip as qt

N = 20
n = 5
a = qt.destroy(N)
x = qt.position(N)
p = qt.momentum(N)
H = a.dag() * a
psi0 = qt.coherent(N, n**0.5)
#psi0=qt.fock(N,n)
time = np.linspace(0, 100, 1000)
sol = qt.mesolve(H, psi0, time, [], [])

fig, ax = plt.subplots(2, 1)
xvec = np.linspace(-10, 10, 100)
#ax.plot(qt.expect(x,sol.states),qt.expect(p,sol.states))
line, = ax[1].plot([0], [qt.expect(H, psi0)])
im = ax[0].imshow(qt.wigner(psi0, xvec, xvec))


def updatefig(i):
    psi = sol.states[i]
    data = qt.wigner(psi, xvec, xvec)
    im.set_array(data)
Ejemplo n.º 36
0
def test_coherent_type():
    "State CSR Type: coherent"
    st = coherent(25,2+2j)
    assert_equal(isspmatrix_csr(st.data), True)
    st = coherent(25,2+2j, method='analytic')
    assert_equal(isspmatrix_csr(st.data), True)
        default=25,
        help="How often do you want to see the states rendered?")
    parser.add_argument('-e',
                        '--epochs',
                        type=int,
                        default=1000,
                        help="How many epochs the network is trained")
    args = parser.parse_args()

    dim = parameters_para.N
    n_par = 64  #M=3: 256, M=4: 64, M=5: 16

    # target state
    target_a = np.sqrt(4)
    target_state = 1 / np.sqrt(2) * (
        qu.coherent(dim, target_a) + qu.coherent(dim, -target_a))  # eigencat

    # initialize figures to render
    if args.render == True: fig, axes = plt.subplots(1, 5, figsize=(18, 4))

    model = PredCorrNetwork(dim, n_par, target_state)
    print(model)
    # print('Check Biases:')
    # print(model.net_action[-1].bias)
    print('--------------------------------')
    print("number of model parameters:",
          sum([np.prod(p.size()) for p in model.parameters()]))

    if args.optimizer == "SGD":
        optimizer = optim.SGD(model.parameters(), lr=1e-6)
    elif args.optimizer == "ADAM":
Ejemplo n.º 38
0
def thermal_state(freq, T, cav_dim=5):
    n_therm = get_n_therm(freq, T)
    return qt.coherent(5,n_therm)