コード例 #1
0
ファイル: test_mcsolve.py プロジェクト: JonathanUlm/qutip
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)
コード例 #2
0
ファイル: test_brmesolve.py プロジェクト: JonathanUlm/qutip
def testHOFiniteTemperatureStates():
    """
    brmesolve: harmonic oscillator, finite temperature, states
    """

    N = 10
    w0 = 1.0 * 2 * np.pi
    g = 0.05 * w0
    kappa = 0.25
    times = np.linspace(0, 25, 1000)
    a = destroy(N)
    H = w0 * a.dag() * a + g * (a + a.dag())
    psi0 = ket2dm((basis(N, 4) + basis(N, 2) + basis(N, 0)).unit())

    n_th = 1.5
    w_th = w0/np.log(1 + 1/n_th)

    def S_w(w):
        if w >= 0:
            return (n_th + 1) * kappa
        else:
            return (n_th + 1) * kappa * np.exp(w / w_th)

    c_ops = [np.sqrt(kappa * (n_th + 1)) * a, np.sqrt(kappa * n_th) * a.dag()]
    a_ops = [a + a.dag()]
    e_ops = []

    res_me = mesolve(H, psi0, times, c_ops, e_ops)
    res_brme = brmesolve(H, psi0, times, a_ops, e_ops, [S_w])

    n_me = expect(a.dag() * a, res_me.states)
    n_brme = expect(a.dag() * a, res_brme.states)

    diff = abs(n_me - n_brme).max()
    assert_(diff < 1e-2)
コード例 #3
0
ファイル: test_mesolve.py プロジェクト: JonathanUlm/qutip
    def testCase3(self):
        "mesolve: cavity-qubit with interaction, decay"

        use_rwa = True
        N = 4           # number of cavity fock states
        wc = 2 * np.pi * 1.0   # cavity frequency
        wa = 2 * np.pi * 1.0   # atom frequency
        g = 2 * np.pi * 0.1   # coupling strength
        kappa = 0.05    # cavity dissipation rate
        gamma = 0.001   # atom dissipation rate
        pump = 0.25    # atom pump rate

        # start with an excited atom and maximum number of photons
        n = N - 2
        psi0 = tensor(basis(N, n), basis(2, 1))
        tlist = np.linspace(0, 200, 500)

        nc, na = self.jc_integrate(
            N, wc, wa, g, kappa, gamma, pump, psi0, use_rwa, tlist)

        # we don't have any analytics for this parameters, so
        # compare with the steady state
        nc_ss, na_ss = self.jc_steadystate(
            N, wc, wa, g, kappa, gamma, pump, psi0, use_rwa, tlist)

        nc_ss = nc_ss * np.ones(np.shape(nc))
        na_ss = na_ss * np.ones(np.shape(na))

        assert_(abs(nc[-1] - nc_ss[-1]) < 0.005, True)
        assert_(abs(na[-1] - na_ss[-1]) < 0.005, True)
コード例 #4
0
ファイル: test_brmesolve.py プロジェクト: tmng/qutip
    def testHOFiniteTemperature(self):
        "brmesolve: harmonic oscillator, finite temperature"

        N = 10
        w0 = 1.0 * 2 * np.pi
        g = 0.05 * w0
        kappa = 0.15
        times = np.linspace(0, 25, 1000)
        a = destroy(N)
        H = w0 * a.dag() * a + g * (a + a.dag())
        psi0 = ket2dm((basis(N, 4) + basis(N, 2) + basis(N, 0)).unit())

        n_th = 1.5
        w_th = w0/np.log(1 + 1/n_th)

        def S_w(w):
            if w >= 0:
                return (n_th + 1) * kappa
            else:
                return (n_th + 1) * kappa * np.exp(w / w_th)

        c_ops = [np.sqrt(kappa * (n_th + 1)) * a, np.sqrt(kappa * n_th) * a.dag()]
        a_ops = [a + a.dag()]
        e_ops = [a.dag() * a, a + a.dag()]

        res_me = mesolve(H, psi0, times, c_ops, e_ops)
        res_brme = brmesolve(H, psi0, times, a_ops, e_ops, [S_w])

        for idx, e in enumerate(e_ops):
            diff = abs(res_me.expect[idx] - res_brme.expect[idx]).max()
            assert_(diff < 1e-2)
コード例 #5
0
ファイル: test_mesolve.py プロジェクト: JonathanUlm/qutip
    def testCase2(self):
        "mesolve: cavity-qubit without interaction, decay"

        use_rwa = True
        N = 4           # number of cavity fock states
        wc = 2 * np.pi * 1.0   # cavity frequency
        wa = 2 * np.pi * 1.0   # atom frequency
        g = 2 * np.pi * 0.0   # coupling strength
        kappa = 0.005   # cavity dissipation rate
        gamma = 0.01    # atom dissipation rate
        pump = 0.0     # atom pump rate

        # start with an excited atom and maximum number of photons
        n = N - 2
        psi0 = tensor(basis(N, n), basis(2, 1))
        tlist = np.linspace(0, 1000, 2000)

        nc, na = self.jc_integrate(
            N, wc, wa, g, kappa, gamma, pump, psi0, use_rwa, tlist)

        nc_ex = (n + 0.5 * (1 - np.cos(2 * g * np.sqrt(n + 1) * tlist))) * \
            np.exp(-kappa * tlist)
        na_ex = 0.5 * (1 + np.cos(2 * g * np.sqrt(n + 1) * tlist)) * \
            np.exp(-gamma * tlist)

        assert_(max(abs(nc - nc_ex)) < 0.005, True)
        assert_(max(abs(na - na_ex)) < 0.005, True)
コード例 #6
0
ファイル: test_brmesolve.py プロジェクト: JonathanUlm/qutip
def testJCZeroTemperature():
    """
    brmesolve: Jaynes-Cummings model, zero temperature
    """

    N = 10
    a = tensor(destroy(N), identity(2))
    sm = tensor(identity(N), destroy(2))
    psi0 = ket2dm(tensor(basis(N, 1), basis(2, 0)))
    a_ops = [(a + a.dag())]
    e_ops = [a.dag() * a, sm.dag() * sm]

    w0 = 1.0 * 2 * np.pi
    g = 0.05 * 2 * np.pi
    kappa = 0.05
    times = np.linspace(0, 2 * 2 * np.pi / g, 1000)

    c_ops = [np.sqrt(kappa) * a]
    H = w0 * a.dag() * a + w0 * sm.dag() * sm + \
        g * (a + a.dag()) * (sm + sm.dag())

    res_me = mesolve(H, psi0, times, c_ops, e_ops)
    res_brme = brmesolve(H, psi0, times, a_ops, e_ops,
                         spectra_cb=[lambda w: kappa * (w >= 0)])

    for idx, e in enumerate(e_ops):
        diff = abs(res_me.expect[idx] - res_brme.expect[idx]).max()
        assert_(diff < 5e-2)  # accept 5% error
コード例 #7
0
ファイル: test_brmesolve.py プロジェクト: JonathanUlm/qutip
def testHOZeroTemperature():
    """
    brmesolve: harmonic oscillator, zero temperature
    """

    N = 10
    w0 = 1.0 * 2 * np.pi
    g = 0.05 * w0
    kappa = 0.15

    times = np.linspace(0, 25, 1000)
    a = destroy(N)
    H = w0 * a.dag() * a + g * (a + a.dag())
    psi0 = ket2dm((basis(N, 4) + basis(N, 2) + basis(N, 0)).unit())

    c_ops = [np.sqrt(kappa) * a]
    a_ops = [a + a.dag()]
    e_ops = [a.dag() * a, a + a.dag()]

    res_me = mesolve(H, psi0, times, c_ops, e_ops)
    res_brme = brmesolve(H, psi0, times, a_ops, e_ops,
                         spectra_cb=[lambda w: kappa * (w >= 0)])

    for idx, e in enumerate(e_ops):
        diff = abs(res_me.expect[idx] - res_brme.expect[idx]).max()
        assert_(diff < 1e-2)
コード例 #8
0
def eigen(f, a, b):
	if a == 1:
		# returns excited states
		return qt.basis(int(4*(f+1)), int(b+(f+1)))
	elif a == 2:
		# returns ground states
		return qt.basis(int(4*(f+1)), int(b+3*(f+1)))
	else:
		return "Error in function eigen"
コード例 #9
0
ファイル: test_entropy.py プロジェクト: tmng/qutip
def test_EntropyConcurrence():
    "Concurrence"
    # check concurrence = 1 for maximal entangled (Bell) state
    bell = ket2dm(
        (tensor(basis(2), basis(2)) + tensor(basis(2, 1), basis(2, 1))).unit())
    assert_equal(abs(concurrence(bell) - 1.0) < 1e-15, True)

    # check all concurrence values >=0
    rhos = [rand_dm(4, dims=[[2, 2], [2, 2]]) for k in range(10)]
    for k in rhos:
        assert_equal(concurrence(k) >= 0, True)
コード例 #10
0
 def mcsolve(self, ntrajs=500, exps=[], initial_state=None):
     """mcsolve
     Interface to qutip mcsolve for the system
     :param ntrajs: number of quantum trajectories to average.
     Default is QuTiP
     default of 500
     :param exps: List of expectation values to calculate at
     each timestep
     """
     if initial_state is None:
         initial_state = qt.tensor(qt.basis(self.N_field_levels, 0), qt.basis(2, 0))
     return qt.mcsolve(self.hamiltonian()[0], initial_state, self.tlist, self._c_ops(), exps, ntraj=ntrajs)
コード例 #11
0
ファイル: test_operators.py プロジェクト: tmng/qutip
def test_destroy():
    "Destruction operator"
    b4 = basis(5, 4)
    d5 = destroy(5)
    test1 = d5 * b4
    assert_equal(np.allclose(test1.full(), 2.0 * basis(5, 3).full()), True)
    d3 = destroy(3)
    matrix3 = np.array([[0.00000000 + 0.j, 1.00000000 + 0.j, 0.00000000 + 0.j],
                        [0.00000000 + 0.j, 0.00000000 + 0.j, 1.41421356 + 0.j],
                        [0.00000000 + 0.j, 0.00000000 + 0.j, 0.00000000 + 0.j]])

    assert_equal(np.allclose(matrix3, d3.full()), True)
コード例 #12
0
ファイル: test_operators.py プロジェクト: tmng/qutip
def test_create():
    "Creation operator"
    b3 = basis(5, 3)
    c5 = create(5)
    test1 = c5 * b3
    assert_equal(np.allclose(test1.full(), 2.0 * basis(5, 4).full()), True)
    c3 = create(3)
    matrix3 = np.array([[0.00000000 + 0.j, 0.00000000 + 0.j, 0.00000000 + 0.j],
                        [1.00000000 + 0.j, 0.00000000 + 0.j, 0.00000000 + 0.j],
                        [0.00000000 + 0.j, 1.41421356 + 0.j, 0.00000000 + 0.j]])

    assert_equal(np.allclose(matrix3, c3.full()), True)
コード例 #13
0
    def _label_to_ket(self, one_pho_label):
        # return qobj with correct structure of node
        pol       = {'H':0, 'V':1}
        port      = {k:v for v,k in enumerate(ascii_uppercase)}
        node_info = self.get_node_info()

        dof = one_pho_label.split('_')
        if self._is_polarized:
            # create pol vec
            polarization = qt.basis(2, pol[dof[0]])
            port         = qt.basis(node_info[dof[1]], port[dof[2]])
        else:
            port = qt.basis(node_info[dof[0]], port[dof[1]])

        return qt.tensor([polarization, port])
コード例 #14
0
 def compute_item(self, name, model):
     name += "_1"
     fock_dim = self.editor.fock_dim.value()
     timestep = self.editor.timestep.value()
     initial_alpha = self.editor.initial_alpha.value()
     steps = model.get_steps(fock_dim, timestep)
     res0 = coherent_dm(fock_dim, initial_alpha)
     qubit0 = ket2dm((basis(2, 0) + basis(2, 1)) / np.sqrt(2))
     psi0 = tensor(qubit0, res0)
     def add_to_viewer(r):
         item = WignerPlotter(name, r)
         item.wigners_complete.connect(lambda: self.viewer.add_item(item))
         win.statusBar().showMessage("Computing Wigners")
     args = (steps, fock_dim, psi0, timestep)
     run_in_process(to_state_list, add_to_viewer, args)
     #self.thread_is_running.emit()
     win.statusBar().showMessage("Computing States")
コード例 #15
0
ファイル: expdesign.py プロジェクト: YulinWu/python-qinfer
def heisenberg_weyl_operators(d=2):
    w = np.exp(2 * np.pi * 1j / d)
    X = qt.Qobj([
        qt.basis(d, (idx + 1) % d).data.todense().view(np.ndarray)[:, 0] for idx in xrange(d)
    ])
    Z = qt.Qobj(np.diag(w ** np.arange(d)))
    
    return [X**i * Z**j for i in xrange(d) for j in xrange(d)]
コード例 #16
0
 def __init__(self, field, mass=const.MASS_OF_PROTON,
              charge=const.ELECTRON_CHARGE,
              initial_state=qt.basis(2,0)):
     self.mass = mass
     self.charge = charge
     self.parent_field = field
     self.gyromagnetic_ratio = 267.513e6
     self.parent_field.particles.append(self)
     self.state = initial_state
コード例 #17
0
ファイル: test_brmesolve.py プロジェクト: tmng/qutip
    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)
コード例 #18
0
ファイル: test_mcsolve.py プロジェクト: JonathanUlm/qutip
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)
コード例 #19
0
ファイル: test_brmesolve.py プロジェクト: JonathanUlm/qutip
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)
コード例 #20
0
ファイル: test_driven_tls.py プロジェクト: mabuchilab/QNET
def test_driven_tls(datadir):
    hs = local_space('tls', namespace='sys', basis=('g', 'e'))
    w =  symbols(r'\omega', real=True)
    pi = sympy.pi
    cos = sympy.cos
    t, T, E0 = symbols('t, T, E_0', real=True)
    a = 0.16
    blackman = 0.5 * (1 - a - cos(2*pi * t/T) + a*cos(4*pi*t/T))
    H0 =  Destroy(hs).dag() * Destroy(hs)
    H1 = LocalSigma(hs, 'g', 'e') + LocalSigma(hs, 'e', 'g')
    H = w*H0 + 0.5 * E0 * blackman * H1
    circuit = SLH(identity_matrix(0), [], H)
    num_vals = {w: 1.0, T:10.0, E0:1.0*2*np.pi}

    # test qutip conversion
    H_qutip, Ls = circuit.substitute(num_vals).HL_to_qutip(time_symbol=t)
    assert len(Ls) == 0
    assert len(H_qutip) == 3
    times = np.linspace(0, num_vals[T], 201)
    psi0 = qutip.basis(2, 1)
    states = qutip.mesolve(H_qutip, psi0, times, [], []).states
    pop0 = np.array(qutip_population(states, state=0))
    pop1 = np.array(qutip_population(states, state=1))
    datfile = os.path.join(datadir, 'pops.dat')
    #print("DATFILE: %s" % datfile)
    #np.savetxt(datfile, np.c_[times, pop0, pop1, pop0+pop1])
    pop0_expect, pop1_expect = np.genfromtxt(datfile, unpack=True,
                                             usecols=(1,2))
    assert np.max(np.abs(pop0 - pop0_expect)) < 1e-12
    assert np.max(np.abs(pop1 - pop1_expect)) < 1e-12

    # Test QSD conversion
    codegen = QSDCodeGen(circuit, num_vals=num_vals, time_symbol=t)
    codegen.add_observable(LocalSigma(hs, 'e', 'e'), name='P_e')
    psi0 = BasisKet(hs, 'e')
    codegen.set_trajectories(psi_initial=psi0,
            stepper='AdaptiveStep', dt=0.01,
            nt_plot_step=5, n_plot_steps=200, n_trajectories=1)
    scode = codegen.generate_code()
    compile_cmd = _cmd_list_to_str(codegen._build_compile_cmd(
                        qsd_lib='$HOME/local/lib/libqsd.a',
                        qsd_headers='$HOME/local/include/qsd/',
                        executable='test_driven_tls', path='$HOME/bin',
                        compiler='mpiCC', compile_options='-g -O0'))
    print(compile_cmd)
    codefile = os.path.join(datadir, "test_driven_tls.cc")
    #print("CODEFILE: %s" % codefile)
    #with(open(codefile, 'w')) as out_fh:
        #out_fh.write(scode)
        #out_fh.write("\n")
    with open(codefile) as in_fh:
        scode_expected = in_fh.read()
    assert scode.strip()  == scode_expected.strip()
コード例 #21
0
ファイル: test_entropy.py プロジェクト: tmng/qutip
def test_EntropyVN():
    "von-Neumann entropy"
    # verify that entropy_vn gives correct binary entropy
    a = np.linspace(0, 1, 20)
    for k in range(len(a)):
        # a*|0><0|
        x = a[k] * ket2dm(basis(2, 0))
        # (1-a)*|1><1|
        y = (1 - a[k]) * ket2dm(basis(2, 1))
        rho = x + y
        # Von-Neumann entropy (base 2) of rho
        out = entropy_vn(rho, 2)
        if k == 0 or k == 19:
            assert_equal(out, -0.0)
        else:
            assert_(abs(-out - a[k] * np.log2(a[k])
                        - (1. - a[k]) * np.log2((1. - a[k]))) < 1e-12)

    # test_ entropy_vn = 0 for pure state
    psi = rand_ket(10)
    assert_equal(abs(entropy_vn(psi)) <= 1e-13, True)
コード例 #22
0
ファイル: scattering.py プロジェクト: ajgpitch/qutip
def temporal_basis_vector(waveguide_emission_indices, n_time_bins):
    """
    Generate a temporal basis vector for emissions at specified time bins into
    specified waveguides.

    Parameters
    ----------
    waveguide_emission_indices : list or tuple
        List of indices where photon emission occurs for each waveguide,
        e.g. [[t1_wg1], [t1_wg2, t2_wg2], [], [t1_wg4, t2_wg4, t3_wg4]].
    n_time_bins : int
        Number of time bins; the range over which each index can vary.

    Returns
    -------
    temporal_basis_vector : :class: qutip.Qobj
        A basis vector representing photon scattering at the specified indices.
        If there are W waveguides, T times, and N photon emissions, then the
        basis vector has dimensionality (W*T)^N.
    """
    # Cast waveguide_emission_indices to list for mutability
    waveguide_emission_indices = [list(i) for i in waveguide_emission_indices]

    # Calculate total number of waveguides
    W = len(waveguide_emission_indices)

    # Calculate total number of emissions
    num_emissions = sum([len(waveguide_indices) for waveguide_indices in
                         waveguide_emission_indices])
    if num_emissions == 0:
        return basis(W * n_time_bins, 0)

    # Pad the emission indices with zeros
    offset_indices = []
    for i, wg_indices in enumerate(waveguide_emission_indices):
        offset_indices += [index + (i * n_time_bins) for index in wg_indices]

    # Return an appropriate tensor product state
    return tensor([basis(n_time_bins * W, i) for i in offset_indices])
コード例 #23
0
ファイル: test_mcsolve.py プロジェクト: JonathanUlm/qutip
def test_MCCollapseTimesOperators():
    "Monte-carlo: Check for stored collapse operators and times"
    N = 10
    kappa = 5.0
    times = np.linspace(0, 10, 100)
    a = destroy(N)
    H = a.dag() * a
    psi0 = basis(N, 9)
    c_ops = [np.sqrt(kappa) * a, np.sqrt(kappa) * a]
    result = mcsolve(H, psi0, times, c_ops, [], ntraj=1)
    assert_(len(result.col_times[0]) > 0)
    assert_(len(result.col_which) == len(result.col_times))
    assert_(set(result.col_which[0]) == {0, 1})
コード例 #24
0
    def trajectory(self, exps=None, initial_state=None, draw=False):
        """for convenience. Calculates the trajectory of an
        observable for one montecarlo run. Default expectation is
        cavity amplitude, default initial state is bipartite
        vacuum. todo: draw: draw trajectory on bloch sphere.
        Write in terms of mcsolve??"""
        if exps is None or draw is True:
            exps = []
        if initial_state is None:
            initial_state = qt.tensor(qt.basis(self.N_field_levels, 0), qt.basis(2, 0))

        self.one_traj_soln = qt.mcsolve(self.hamiltonian(), initial_state, self.tlist, self._c_ops(), exps, ntraj=1)
        if self.noisy:
            print(self.one_traj_soln.states[0][2].ptrace(1))

        if not draw:
            return self.one_traj_soln
        else:
            self.b_sphere = qt.Bloch()
            self.b_sphere.add_states([state.ptrace(1) for state in self.one_traj_soln.states[0]], "point")
            self.b_sphere.point_markers = ["o"]
            self.b_sphere.size = (10, 10)
            self.b_sphere.show()
コード例 #25
0
ファイル: multimode.py プロジェクト: nelsonleung/Qutip
def fock_state(p, qudit_n, mode_n_entries=[], density_matrix_form=True):
    """
    Creates specific fock states
    p: DictExtended object with sizes of qudit and mode Hilbert spaces
    qubit_n: fock level of the qudit
    mode_n_entries: list of lists, each with an index and a corresponding (nonground) fock state
    For example:
        mode_n_entries=[[0, 2], [4, 1]]
    would mean we want to have the mode with zero index be in the 2nd excited state, and mode with index 4
    be in the 1st excited state. All other modes should be in their ground states.

    """
    mode_states = [q.basis(p.N_m, 0)] * p.mode_count 

    for entry in mode_n_entries:
        mode_states[entry[0]]=q.basis(p.N_m, entry[1])

    state=q.tensor(q.basis(p.N_q, qudit_n), *mode_states)

    if density_matrix_form:
        return q.ket2dm(state)

    return state
コード例 #26
0
ファイル: test_mcsolve.py プロジェクト: JonathanUlm/qutip
def test_MCSimpleSingleExpect():
    """Monte-carlo: Constant H with single expect operator"""
    N = 10  # number of basis states to consider
    a = destroy(N)
    H = a.dag() * a
    psi0 = basis(N, 9)  # initial state
    kappa = 0.2  # coupling to oscillator
    c_op_list = [np.sqrt(kappa) * a]
    tlist = np.linspace(0, 10, 100)
    mcdata = mcsolve(H, psi0, tlist, c_op_list, a.dag() * a, ntraj=ntraj)
    expt = mcdata.expect[0]
    actual_answer = 9.0 * np.exp(-kappa * tlist)
    avg_diff = np.mean(abs(actual_answer - expt) / actual_answer)
    assert_equal(avg_diff < mc_error, True)
コード例 #27
0
ファイル: test_mcsolve.py プロジェクト: JonathanUlm/qutip
def test_MCNoCollExpt():
    "Monte-carlo: Constant H with no collapse ops (expect)"
    error = 1e-8
    N = 10  # number of basis states to consider
    a = destroy(N)
    H = a.dag() * a
    psi0 = basis(N, 9)  # initial state
    c_op_list = []
    tlist = np.linspace(0, 10, 100)
    mcdata = mcsolve(H, psi0, tlist, c_op_list, [a.dag() * a], ntraj=ntraj)
    expt = mcdata.expect[0]
    actual_answer = 9.0 * np.ones(len(tlist))
    diff = np.mean(abs(actual_answer - expt) / actual_answer)
    assert_equal(diff < error, True)
コード例 #28
0
ファイル: test_mcsolve_f90.py プロジェクト: JonathanUlm/qutip
def test_MCSimpleConst():
    "mcsolve_f90: Constant H with constant collapse"
    N = 10  # number of basis states to consider
    a = destroy(N)
    H = a.dag() * a
    psi0 = basis(N, 9)  # initial state
    kappa = 0.2  # coupling to oscillator
    c_op_list = [np.sqrt(kappa) * a]
    tlist = np.linspace(0, 10, 100)
    mcdata = mcsolve_f90(H, psi0, tlist, c_op_list, [a.dag() * a])
    expt = mcdata.expect[0]
    actual_answer = 9.0 * np.exp(-kappa * tlist)
    avg_diff = np.mean(abs(actual_answer - expt) / actual_answer)
    assert_equal(avg_diff < mc_error, True)
コード例 #29
0
ファイル: test_mcsolve.py プロジェクト: JonathanUlm/qutip
def test_MCSimpleConstFunc():
    "Monte-carlo: Collapse terms constant (func format)"
    N = 10  # number of basis states to consider
    a = destroy(N)
    H = a.dag() * a
    psi0 = basis(N, 9)  # initial state
    kappa = 0.2  # coupling to oscillator
    c_op_list = [[a, sqrt_kappa]]
    tlist = np.linspace(0, 10, 100)
    mcdata = mcsolve(H, psi0, tlist, c_op_list, [a.dag() * a], ntraj=ntraj)
    expt = mcdata.expect[0]
    actual_answer = 9.0 * np.exp(-kappa * tlist)
    avg_diff = np.mean(abs(actual_answer - expt) / actual_answer)
    assert_equal(avg_diff < mc_error, True)
コード例 #30
0
ファイル: test_mesolve.py プロジェクト: maxirubikstar/qutip
    def testSuperJC(self):
        "mesolve: super vs. density matrix as initial condition"
        me_error = 1e-6

        use_rwa = True
        N = 4  # number of cavity fock states
        wc = 2 * np.pi * 1.0  # cavity frequency
        wa = 2 * np.pi * 1.0  # atom frequency
        g = 2 * np.pi * 0.1  # coupling strength
        kappa = 0.05  # cavity dissipation rate
        gamma = 0.001  # atom dissipation rate
        pump = 0.25  # atom pump rate

        # start with an excited atom and maximum number of photons
        n = N - 2
        psi0 = tensor(basis(N, n), basis(2, 1))
        rho0vec = operator_to_vector(psi0 * psi0.dag())
        tlist = np.linspace(0, 100, 50)

        out1, out2 = self.jc_integrate(N, wc, wa, g, kappa, gamma, pump, psi0, use_rwa, tlist)

        fid = self.fidelitycheck(out1, out2, rho0vec)
        assert_(max(abs(1.0 - fid)) < me_error, True)
コード例 #31
0
 def multi_index_2_vector(d, num_modes, fock_trunc):
     return tensor(
         [basis(fock_trunc, d.get(i, 0)) for i in range(num_modes)])
     '''this function creates a vector representation a given fock state given the data for excitations per
コード例 #32
0
def prep_K_qutip():
    q = qutip.basis(2)
    K = 1 / np.sqrt(2) * (qutip.sigmay() + qutip.sigmaz())
    return K * q
コード例 #33
0

def createEffects(eigenvectorsPerInput):
    return list(
        map(
            lambda eigenvectors: list(
                map(lambda eigvector: eigvector * eigvector.dag(), eigenvectors
                    )), eigenvectorsPerInput))


if __name__ == '__main__':

    outputsAlice = [2, 2]
    outputsBob = [2, 2]

    qzero = qt.basis(2, 0)
    qone = qt.basis(2, 1)
    plus = 1 / np.sqrt(2) * (qzero + qone)
    minus = 1 / np.sqrt(2) * (-qzero + qone)

    psi = 2 / np.sqrt(3) * (qt.tensor(qzero, qzero) -
                            1 / 2 * qt.tensor(plus, plus))

    aliceEffects = [[qzero * qzero.dag(), qone * qone.dag()],
                    [plus * plus.dag(), minus * minus.dag()]]
    bobEffects = [[qzero * qzero.dag(), qone * qone.dag()],
                  [plus * plus.dag(), minus * minus.dag()]]

    bobPostMeasurmentStates = [[
        1 / ((qt.tensor(effect, qt.qeye(2)) * psi * psi.dag()).tr()) *
        (qt.tensor(effect, qt.qeye(2)) * psi).ptrace(1)
コード例 #34
0
def create_data(time_per_count, num_samples, num_counts, gate_list, time_unit, noise_type=None, walking_amp=None, telegraph_amp=None, \
                res=None, freq_list=None, amp_list=None, phase_list=None, start_f=None, stop_f=None, fluctuators=None, plot_noise=False, \
                add_noise=False, noise_object=None, dc_angle_offset=0, constant_linear_drift=0):
    #time_per_shot: time in seconds for a single (prep-gate-measure+delay)
    #num_samples: how many timestamps and strings of counts you want to have
    #num_counts: how many data points to create (how many ones and zeros) per sample (i.e. per timestamp) --> affects both time of a sample and precision
    #num_shots: how many times (shots) you apply (prep-gate_list-meas) to get one count (a single 0 or 1) --> determines the time of one count, but won't affect precision
    #gate_list: gates you want to do for your operation, entered as a list of strings
    #xerr,yerr,zerr: 2D tuples with overrotation amplitude in radians and frequency in Hz
    #constant linear drift: enter in rads/second
    rho0 = _qt.operator_to_vector(_qt.ket2dm(_qt.basis(2,0)))
    rho1 = _qt.operator_to_vector(_qt.ket2dm(_qt.basis(2,1)))
    zero_counts = []
    one_counts = []
    timestep = num_counts*time_per_count #the time to get a full bitstring of zeros and ones for one sample, i.e. one timestamp
    timestamps = np.arange(timestep, num_samples*timestep, timestep) #array of 1*timestep, 2*timestep,....(num_samples)*timestep
    probs = []
    total_time = (time_per_count*num_counts*num_samples)/time_unit
    
    sig = 0
    if noise_type == "Sine":
        #this function returns the noise object so you can enter it back in as a parameter
        # in the event that you call the function repeatedly for an identical set of parameters
        if noise_object != None:
            sig = noise_object
            #print("REUSING NOISE OBJECT")
            while total_time > sig.times[-1] + timestep:
                sig.next_interval()
                #print("Doing a NEXT INTERVAL")
        else:
            #print("INITIALIZING NEW NOISE")
            sig = _ns.NoiseSignalSine(time_unit=time_unit)
            sig.configure_noise(resolution_factor=res, freq_list=freq_list, amp_list=amp_list, phase_list=phase_list, total_time=total_time)
            sig.init()
            if add_noise != None:  
                sig.add_random_noise(add_noise) #add normal noise with specified std deviation if requested
    elif noise_type == "Random Walk":
        sig = _ns.NoiseSignalRandomWalk(initial_seed=1234, time_unit=time_unit)
        sig.configure_noise(walking_amp, res, total_time)
        sig.init() 
    elif noise_type == "Telegraph":
        sig = _ns.NoiseSignalTelegraph(initial_seed=1234, time_unit=time_unit)
        sig.configure_noise(exponent=1, amplitude=telegraph_amp, total_fluctuators=fluctuators, start_freq=start_f, stop_freq=stop_f, total_time=total_time)
        sig.init()
        sig.interpolation_settings(do_interpolation=True, resolution_factor=res)
    
    if plot_noise==True:
        sig.plot_noise_signal()
        
    angle_list = []
    expected_angle_list = []
        
    compressed_gate_list = compress_gate_list(gate_list)
    for time in timestamps:
        noise_at_time = 0
        if noise_type != None:
            #print(time/time_unit)
            noise_at_time = sig[time/time_unit]
        rho = rho0
        total_angle = 0
        total_ideal_angle = 0
        
        for gate in compressed_gate_list:
            gate_name = gate[0]
            gate_repetitions = gate[1]
            '''
            Next step: calculate change in rotation error within each shot. Currently takes the time at the start of the experiment shot
            and applies that to all gates in one shot. Depending on the timescale of the error and time per shot, this simplification may need
            to be addressed so that each gate, say each Gx in (Gx)^11, has an error associated with its specific time, not the same error for
            all 11 Gx gates.
            '''
            
            if gate_name == 'Gx':
                angle = (np.pi/2 + noise_at_time)*gate_repetitions + dc_angle_offset + constant_linear_drift*time
                ideal_angle = (np.pi/2)*gate_repetitions + dc_angle_offset + constant_linear_drift*time
                rho = (_qt.to_super(_qt.rx(angle))) * rho
                #this section just keeps the angle between 0 and pi
                angle = angle % (2*np.pi)
                ideal_angle = ideal_angle % (2*np.pi)
                if angle > np.pi:
                    angle = 2*np.pi - angle
                if angle < 0:
                    angle = 0 + abs(angle)
                if ideal_angle > np.pi:
                    ideal_angle = 2*np.pi - ideal_angle
                if ideal_angle < 0:
                    ideal_angle = 0 + abs(ideal_angle)
            elif gate_name == 'Gy':
                angle = (np.pi/2 + noise_at_time)*gate_repetitions + dc_angle_offset + constant_linear_drift*time
                ideal_angle = (np.pi/2)*gate_repetitions + dc_angle_offset + constant_linear_drift*time
                rho = (_qt.to_super(_qt.rx(angle))) * rho
                #this section just keeps the angle between 0 and pi
                angle = angle % (2*np.pi)
                ideal_angle = ideal_angle % (2*np.pi)
                if angle > np.pi:
                    angle = 2*np.pi - angle
                if angle < 0:
                    angle = 0 + abs(angle)
                if ideal_angle > np.pi:
                    ideal_angle = 2*np.pi - ideal_angle
                if ideal_angle < 0:
                    ideal_angle = 0 + abs(ideal_angle)
            elif gate_name == 'Gz':
                angle = (np.pi/2 + noise_at_time)*gate_repetitions + dc_angle_offset + constant_linear_drift*time
                ideal_angle = (np.pi/2)*gate_repetitions + dc_angle_offset + constant_linear_drift*time
                rho = (_qt.to_super(_qt.rx(angle))) * rho
                #this section just keeps the angle between 0 and pi
                angle = angle % (2*np.pi)
                ideal_angle = ideal_angle % (2*np.pi)
                if angle > np.pi:
                    angle = 2*np.pi - angle
                if angle < 0:
                    angle = 0 + abs(angle)
                if ideal_angle > np.pi:
                    ideal_angle = 2*np.pi - ideal_angle
                if ideal_angle < 0:
                    ideal_angle = 0 + abs(ideal_angle)
            elif gate_name == "Gi":
                #apply only the oscillating drift angle, don't add it to pi/2
                angle = (noise_at_time)*gate_repetitions + dc_angle_offset + constant_linear_drift*time
                ideal_angle = 0 + dc_angle_offset + constant_linear_drift*time
                rho = (_qt.to_super(_qt.rx(angle))) * rho
                angle = angle % (2*np.pi)
                ideal_angle = ideal_angle % (2*np.pi)
                if angle > np.pi:
                    angle = 2*np.pi - angle
                if angle < 0:
                    angle = 0 + abs(angle)
                if ideal_angle > np.pi:
                    ideal_angle = 2*np.pi - ideal_angle
                if ideal_angle < 0:
                    ideal_angle = 0 + abs(ideal_angle)
            total_angle += angle
            total_ideal_angle += ideal_angle
        
        #append the total rotation angle after timestamp 'time'
        angle_list.append(total_angle)
        expected_angle_list.append(total_ideal_angle)        
        #calculate probabilities of being in 1 after the experiment has been applied
        p1 = (rho.dag()*rho1).norm()
        #fix the p1 if it exceeds 1 due to rounding error
        if p1 > 1:
            #print("p1 exceeds 1 for time {}".format(time))
            #print("prob is {}".format(p1))
            #print("Resetting to {}".format(2-p1))
            p1 = 2 - p1
        probs.append(p1)
        one_count = np.random.binomial(num_counts, p1) #simulates a summation of the number of 1-counts you get in one bitstring sample
        zero_count = num_counts - one_count #simulates summation of the number of 0-counts in one bitstring sample
        one_counts.append(one_count)
        zero_counts.append(zero_count)
            
    
    if plot_noise == True:
        plt.plot(timestamps, np.asarray(expected_angle_list),label="Ideal Angle",ls='dashed',color='orange')
        plt.plot(timestamps, np.asarray(angle_list), label="Drifting Angle")
        plt.legend()
        plt.xlabel("Time, seconds")
        plt.yticks(np.linspace(0, np.pi, 5), ['0', '$\pi/4$', '$\pi/2$', '$3\pi/4$', '$\pi$'])
        plt.ylabel("Angle, radians\n(Displayed between 0 and $\pi$)")
        plt.title("Time-Dependent Rotation Angle after each {}".format(gate_list_to_string(gate_list)))
        plt.grid()
        plt.show()        
        
        plt.plot(timestamps, probs)
        plt.ylim(0,1)
        plt.xlabel("Time, seconds")
        plt.ylabel("Probability of Measuring State {1}")
        plt.title("Simulated {} with {} Noise".format(gate_list_to_string(gate_list), noise_type))
        plt.grid()
        plt.show()
        
    return (np.asarray(one_counts), np.asarray(zero_counts), np.asarray(timestamps), probs,np.asarray(expected_angle_list), np.asarray(angle_list),  sig)
コード例 #35
0
        def get_average_gate_fidelity(self, runs=500, target=None):
            """
            returns average gate fidelity
            Args
                runs (int) : number of runs to compute the average gate fidelity
                target (4x4 numpy array) : target unitary to compute fidelity
            """

            self.solver_obj.calculate_evolution(self.init, self.total_time,
                                                10000, 1)
            U_ideal = self.solver_obj.get_unitary()[0]
            self.solver_obj.add_noise_static(2 * np.pi * self.H_zeeman,
                                             18 * 1e-6)
            self.solver_obj.add_noise_generic(2 * np.pi * self.H_heisenberg,
                                              oneoverfnoise,
                                              self.exchange_dc / 100)
            self.solver_obj.calculate_evolution(self.init, self.total_time,
                                                10000, int(runs))

            U_list = self.solver_obj.get_unitary()

            # Calculate the averaged super operator in the Lioville superoperator form using column convention
            basis = [qt.basis(4, it) for it in range(4)]
            superoperator_basis = [
                basis_it1 * basis_it2.dag() for basis_it2 in basis
                for basis_it1 in basis
            ]
            averaged_map = np.zeros([16, 16], dtype=np.complex)
            for u in U_list:
                temp_U = qt.Qobj(u)
                output_density = list()
                for it in range(len(superoperator_basis)):
                    temp_vec = np.array(
                        qt.operator_to_vector(
                            temp_U * superoperator_basis[it] * temp_U.dag() /
                            float(runs)).full()).flatten()
                    output_density.append(np.array(temp_vec))
                averaged_map = np.add(averaged_map, np.array(output_density))

            # Define the target unitary operation
            if target is None:
                target = sp.linalg.expm(
                    -np.pi / 2. * 1j *
                    sp.sparse.diags([0., -1., -1., 0.]).todense())

            # get phase from optimizing noiseless unitary evolution
            def to_minimize_fidelity(theta):
                temp_z_gate = np.matmul(
                    sp.linalg.expm(-2 * np.pi * 1j * theta * self.H_zeeman),
                    U_ideal)
                temp_m = np.matmul(sp.conjugate(sp.transpose(target)),
                                   temp_z_gate)
                return np.real(1. - (sp.trace(
                    np.matmul(temp_m, sp.conjugate(sp.transpose(temp_m)))) +
                                     np.abs(sp.trace(temp_m))**2.) / 20.)

            ideal_phase = sp.optimize.minimize(
                to_minimize_fidelity,
                [self.delta_z * (self.total_time * 1e-9)],
                method='Nelder-Mead',
                tol=1e-6).x[0]

            target = np.matmul(
                sp.linalg.expm(2 * np.pi * 1j * ideal_phase * self.H_zeeman),
                target)

            # Change the shape of the averaged super operator to match the definitions used in QuTip (row convention)
            target = qt.Qobj(target)
            averaged_map = qt.Qobj(averaged_map).trans()
            averaged_map._type = 'super'
            averaged_map.dims = [[[4], [4]], [[4], [4]]]
            averaged_map.superrep = qt.to_super(target).superrep

            # Calculate the average gate fidelity of the superoperator with the target unitary gate

            fidelity = qt.average_gate_fidelity(averaged_map, target)
            return fidelity
コード例 #36
0
def basic_spin_states():
    '''define some basic spin states'''
    ket0 = qutip.basis(2, 0)
    bra0 = qutip.basis(2, 0).dag()
    ket1 = qutip.basis(2, 1)
    bra1 = qutip.basis(2, 1).dag()
    rho0 = ket0 * bra0
    rho1 = ket1 * bra1
    rhom = (rho0 + rho1) / 2
    ketx = 1 / np.sqrt(2) * (qutip.basis(2, 0) + qutip.basis(2, 1))
    brax = 1 / np.sqrt(2) * (qutip.basis(2, 0).dag() + qutip.basis(2, 1).dag())
    ketmx = 1 / np.sqrt(2) * (qutip.basis(2, 0) - qutip.basis(2, 1))
    bramx = 1 / np.sqrt(2) * (qutip.basis(2, 0).dag() -
                              qutip.basis(2, 1).dag())
    kety = 1 / np.sqrt(2) * (qutip.basis(2, 0) + 1j * qutip.basis(2, 1))
    bray = kety.dag()
    ketmy = 1 / np.sqrt(2) * (qutip.basis(2, 0) - 1j * qutip.basis(2, 1))
    bramy = ketmy.dag()
    rhox = ketx * brax
    rhomx = ketmx * bramx
    rhoy = kety * bray
    rhomy = ketmy * bramy
    return ket0, bra0, ket1, bra1, rho0, rho1, rhom, ketx, brax, ketmx, bramx, rhox, rhomx, kety, bray, ketmy, bramy, rhoy, rhomy
コード例 #37
0
def prep_Z_qutip():
    q = qutip.basis(2)
    Z = qutip.sigmaz()
    return Z * q
L0 = liouvillian(H0, [np.sqrt(gamma) * Sm])

#sigma X control
LC_x = liouvillian(Sx)
#sigma Y control
LC_y = liouvillian(Sy)
#sigma Z control
LC_z = liouvillian(Sz)

E0 = sprepost(Si, Si)
# target map 1
# E_targ = sprepost(had_gate, had_gate)
# target map 2
E_targ = sprepost(Sx, Sx)

psi0 = basis(2, 1)  # ground state
#psi0 = basis(2, 0) # excited state
rho0 = ket2dm(psi0)
print("rho0:\n{}\n".format(rho0))
rho0_vec = operator_to_vector(rho0)
print("rho0_vec:\n{}\n".format(rho0_vec))

# target state 1
# psi_targ = (basis(2, 0) + basis(2, 1)).unit()
# target state 2
#psi_targ = basis(2, 1) # ground state
psi_targ = basis(2, 0)  # excited state
#psi_targ = psi0

rho_targ = ket2dm(psi_targ)
print("rho_targ:\n{}\n".format(rho_targ))
コード例 #39
0
def prep_Y_qutip():
    q = qutip.basis(2)
    Y = qutip.sigmay()
    return Y * q
コード例 #40
0
         
         else:
             all_seeds_alpha.append(data['alpha'][:N_iter][epochs])
             all_seeds_theta.append(data['theta'][:N_iter][epochs])
             all_seeds_cost.append(data['cost'][:N_iter][epochs])
         
     
     all_seeds_alpha = np.array(all_seeds_alpha)
     all_seeds_theta = np.array(all_seeds_theta)
     all_seeds_cost = np.array(all_seeds_cost)
 
     batch_size = 1
     T = 5
     N = 100
     
     target_state = qt.basis(N,fock)
     reward_kwargs = {'reward_mode' : 'overlap',
                      'target_state' : target_state,
                      'postselect_0' : False}
     
     env = env_init(control_circuit='snap_and_displacement', reward_kwargs=reward_kwargs,
                    init='vac', T=T, batch_size=batch_size, N=N, episode_length=T)
     
     def avg_reward(action_script):
     
         policy = plc.ScriptedPolicy(env.time_step_spec(), action_script)
         
         time_step = env.reset()
         policy_state = policy.get_initial_state(env.batch_size)
         while not time_step.is_last()[0]:
             action_step = policy.action(time_step, policy_state)
コード例 #41
0
# helper functions
from helpers import are_close

# functions that generate our circuit and time evolutions
from teleportation import continuousTeleportationSimulation
from teleportation import continuousXXBraidingCorrectionSimulation
from teleportation import continuousZBraidingCorrectionSimulation
from teleportation import continuousDecodingSimulation
from teleportation import circuitTeleportationSimulation
from teleportation import circuitXXBraidingCorrectionSimulation
from teleportation import circuitZBraidingCorrectionSimulation
from teleportation import circuitDecodingSimulation
from teleportation import simulateTeleportation

z0, z1, xp, xm, yp, ym = bloch(basis(2, 0), basis(2, 1))


class TestCZandH(object):
    def testHadamardUnitary(self):
        H = constructHadamardH(1, [0])
        U = snot()
        U2 = deriveUnitary(H, np.pi)
        Ucorr = constructHadamardCorr(1, [0])
        assert Ucorr*U2 == U
        assert H.isherm

    def testHadamardUnitaryMulti(self):
        H = constructHadamardH(2, [0, 1])
        UH1 = snot(N=2, target=0)
        UH2 = snot(N=2, target=1)
コード例 #42
0
    def test_wstate(self):

        filename = "w-state.qasm"
        filepath = Path(__file__).parent / 'qasm_files' / filename
        qc = read_qasm(filepath)

        rand_state = rand_ket(2)
        wstate = (tensor(basis(2, 0), basis(2, 0), basis(2, 1))
                  + tensor(basis(2, 0), basis(2, 1), basis(2, 0))
                  + tensor(basis(2, 1), basis(2, 0), basis(2, 0))).unit()

        state = tensor(tensor(basis(2, 0), basis(2, 0), basis(2, 0)),
                       rand_state)

        fourth = Measurement("test_rand", targets=[3])

        _, probs_initial = fourth.measurement_comp_basis(state)

        simulators = _simulators_sv(qc)

        for simulator in simulators:
            result = simulator.run_statistics(state)
            final_states = result.get_final_states()
            result_cbits = result.get_cbits()

            for i, final_state in enumerate(final_states):
                _, probs_final = fourth.measurement_comp_basis(final_state)
                np.testing.assert_allclose(probs_initial, probs_final)
                assert sum(result_cbits[i]) == 1
コード例 #43
0
 def fock_state_on(d):
     return qutip.tensor(*[
         qutip.basis(fock_trunc, d.get(i, 0)) for i in range(N)
     ])  # give me the value d[i]  or 0 if d[i] does not exist
コード例 #44
0
# Declare Channels
seq.declare_channel('ryd', 'rydberg_local', 'control1')
seq.declare_channel('raman', 'raman_local', 'control1')

d = 0  # Pulse Duration

# Prepare state 'hhh':
seq.add(pi_Y, 'raman')
seq.target('target', 'raman')
seq.add(pi_Y, 'raman')
seq.target('control2', 'raman')
seq.add(pi_Y, 'raman')
d += 3

prep_state = qutip.tensor([qutip.basis(3, 2) for _ in range(3)])

# Write CCZ sequence:
seq.add(pi, 'ryd', protocol='wait-for-all')
seq.target('control2', 'ryd')
seq.add(pi, 'ryd')
seq.target('target', 'ryd')
seq.add(twopi, 'ryd')
seq.target('control2', 'ryd')
seq.add(pi, 'ryd')
seq.target('control1', 'ryd')
seq.add(pi, 'ryd')
d += 5


def test_initialization_and_construction_of_hamiltonian():
コード例 #45
0
def prep_X_qutip():
    q = qutip.basis(2)
    X = qutip.sigmax()
    return X * q
コード例 #46
0
def prep_T_qutip(amount):
    q = qutip.basis(2)
    T = qutip.Qobj([[1, 0], [0, np.exp(amount * np.pi / 4)]], dims=[[2], [2]])
    return T * q
コード例 #47
0
def test_building_basis_and_projection_operators():
    # All three levels:
    sim = Simulation(seq, sampling_rate=0.01)
    assert sim.basis_name == 'all'
    assert sim.dim == 3
    assert sim.basis == {
        'r': qutip.basis(3, 0),
        'g': qutip.basis(3, 1),
        'h': qutip.basis(3, 2)
    }
    assert (sim.op_matrix['sigma_rr'] == qutip.basis(3, 0) *
            qutip.basis(3, 0).dag())
    assert (sim.op_matrix['sigma_gr'] == qutip.basis(3, 1) *
            qutip.basis(3, 0).dag())
    assert (sim.op_matrix['sigma_hg'] == qutip.basis(3, 2) *
            qutip.basis(3, 1).dag())

    # Check local operator building method:
    with pytest.raises(ValueError, match="Duplicate atom"):
        sim._build_operator('sigma_gg', "target", "target")

    # Global ground-rydberg
    seq2 = Sequence(reg, Chadoq2)
    seq2.declare_channel('global', 'rydberg_global')
    seq2.add(pi, 'global')
    sim2 = Simulation(seq2, sampling_rate=0.01)
    assert sim2.basis_name == 'ground-rydberg'
    assert sim2.dim == 2
    assert sim2.basis == {'r': qutip.basis(2, 0), 'g': qutip.basis(2, 1)}
    assert (sim2.op_matrix['sigma_rr'] == qutip.basis(2, 0) *
            qutip.basis(2, 0).dag())
    assert (sim2.op_matrix['sigma_gr'] == qutip.basis(2, 1) *
            qutip.basis(2, 0).dag())

    # Digital
    seq2b = Sequence(reg, Chadoq2)
    seq2b.declare_channel('local', 'raman_local', 'target')
    seq2b.add(pi, 'local')
    sim2b = Simulation(seq2b, sampling_rate=0.01)
    assert sim2b.basis_name == 'digital'
    assert sim2b.dim == 2
    assert sim2b.basis == {'g': qutip.basis(2, 0), 'h': qutip.basis(2, 1)}
    assert (sim2b.op_matrix['sigma_gg'] == qutip.basis(2, 0) *
            qutip.basis(2, 0).dag())
    assert (sim2b.op_matrix['sigma_hg'] == qutip.basis(2, 1) *
            qutip.basis(2, 0).dag())

    # Local ground-rydberg
    seq2c = Sequence(reg, Chadoq2)
    seq2c.declare_channel('local_ryd', 'rydberg_local', 'target')
    seq2c.add(pi, 'local_ryd')
    sim2c = Simulation(seq2c, sampling_rate=0.01)
    assert sim2c.basis_name == 'ground-rydberg'
    assert sim2c.dim == 2
    assert sim2c.basis == {'r': qutip.basis(2, 0), 'g': qutip.basis(2, 1)}
    assert (sim2c.op_matrix['sigma_rr'] == qutip.basis(2, 0) *
            qutip.basis(2, 0).dag())
    assert (sim2c.op_matrix['sigma_gr'] == qutip.basis(2, 1) *
            qutip.basis(2, 0).dag())
コード例 #48
0
Created on Mon Apr  1 14:48:35 2019

@author: Eduardo Villasenor
"""

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

r = 3
print("Mean photon number:", np.sinh(r)**2)

# N = 10
N = 10
a = qt.basis(N, 0)
Sa = qt.squeeze(N, r)

# N = 20
N = 20
b = qt.basis(N, 0)
Sb = qt.squeeze(N, r)

# N = 30
N = 50
c = qt.basis(N, 0)
Sc = qt.squeeze(N, r)

fig, axes = plt.subplots(1, 3, figsize=(12, 3))
qt.plot_fock_distribution(Sa * a,
                          fig=fig,
コード例 #49
0
    noise_operator_meas_op = unitary_channel(4, 0.8, 0.01)
    noise_operator_state_prep.dims = [[[2, 2], [2, 2]], [[2, 2], [2, 2]]]
    noise_operator_meas_op.dims = [[[2, 2], [2, 2]], [[2, 2], [2, 2]]]

    # Set the number of runs
    number_of_seq = 5000
    seq_length = 25

    # Set observable Q
    Q = qt.tensor(qt.sigmay() - qt.sigmaz(), qt.sigmay() - qt.sigmaz())
    Q.dims = [[2, 2], [2, 2]]
    Q = qt.operator_to_vector(Q)
    Q = noise_operator_meas_op * Q

    # Set initial state
    rho = qt.basis(4, 0) * qt.basis(4, 0).dag()
    rho.dims = [[2, 2], [2, 2]]
    rho = qt.operator_to_vector(rho)
    rho = noise_operator_state_prep * rho

    def fixed_func(m, c0, c1, c2, c3, e1):
        return (c0 + c1 * e1**(m - 1.) + c2 *
                (sub_unitarity_A_to_A(two_qubit_noise))**(m - 1.) + c3 *
                (sub_unitarity_B_to_B(two_qubit_noise))**(m - 1.))

    # Run!
    reference_standard_data = protocol(noisy_cliffords, rho, Q, seq_length,
                                       number_of_seq)

    reference_optimal_standard = opt.curve_fit(fixed_func,
                                               np.arange(1, seq_length),
コード例 #50
0
 def basis(self, *ns):
     return q.tensor(
         *[q.basis(N, n) for N, n in zip(self.modes_levels, ns)])
コード例 #51
0
spin_n = 2
clock_n = 7

################################################################################

spin_initial = qt.rand_ket(spin_n)
spin_H = qt.rand_herm(spin_n)
dt = (2 * np.pi) / clock_n
spin_U = (-1j * spin_H * dt).expm()
psi_t = lambda t: (-1j * spin_H * t).expm() * spin_initial
spin_history = [psi_t(t * dt) for t in range(clock_n)]

################################################################################

H = sum([-qt.tensor(spin_U, qt.basis(clock_n, t+1)*qt.basis(clock_n, t).dag())\
      -qt.tensor(spin_U.dag(), qt.basis(clock_n, t)*qt.basis(clock_n, t+1).dag())\
   +qt.tensor(qt.identity(spin_n), qt.basis(clock_n, t)*qt.basis(clock_n, t).dag())\
    +qt.tensor(qt.identity(spin_n), qt.basis(clock_n, t+1)*qt.basis(clock_n, t+1).dag())\
   +qt.tensor(qt.identity(spin_n) - spin_initial*spin_initial.dag(), qt.basis(clock_n, 0)*qt.basis(clock_n,0).dag())\
  for t in range(clock_n-1)])
HL, HV = H.eigenstates()
H_projs = [v * v.dag() for v in HV]

Z = qt.sigmaz()
ZL, ZV = Z.eigenstates()
Z_projs = [qt.tensor(v * v.dag(), qt.identity(clock_n)) for v in ZV]

TIME_projs = [
    qt.basis(clock_n, i) * qt.basis(clock_n, i).dag() for i in range(clock_n)
]
コード例 #52
0
def prep_I_qutip():
    q = qutip.basis(2)
    return q
コード例 #53
0
 def basis(self, n):
     return q.basis(self.levels, n)
コード例 #54
0
    def plot_expect(self):
        XI = np.array(
            list(
                qt.basis(4, 1) * qt.basis(4, 3).dag() +
                qt.basis(4, 0) * qt.basis(4, 2).dag() +
                qt.basis(4, 2) * qt.basis(4, 0).dag() +
                qt.basis(4, 3) * qt.basis(4, 1).dag()))[:, 0]
        IX = np.array(
            list(
                qt.basis(4, 0) * qt.basis(4, 1).dag() +
                qt.basis(4, 1) * qt.basis(4, 0).dag() +
                qt.basis(4, 2) * qt.basis(4, 3).dag() +
                qt.basis(4, 3) * qt.basis(4, 2).dag()))[:, 0]
        XX = np.array(
            list(
                qt.basis(4, 0) * qt.basis(4, 3).dag() +
                qt.basis(4, 1) * qt.basis(4, 2).dag() +
                qt.basis(4, 2) * qt.basis(4, 1).dag() +
                qt.basis(4, 3) * qt.basis(4, 0).dag()))[:, 0]
        ZZ = np.array(
            list(
                qt.basis(4, 0) * qt.basis(4, 0).dag() -
                qt.basis(4, 1) * qt.basis(4, 1).dag() -
                qt.basis(4, 2) * qt.basis(4, 2).dag() +
                qt.basis(4, 3) * qt.basis(4, 3).dag()))[:, 0]
        ZI = np.array(
            list(
                qt.basis(4, 0) * qt.basis(4, 0).dag() +
                qt.basis(4, 1) * qt.basis(4, 1).dag() -
                qt.basis(4, 2) * qt.basis(4, 2).dag() -
                qt.basis(4, 3) * qt.basis(4, 3).dag()))[:, 0]
        IZ = np.array(
            list(
                qt.basis(4, 0) * qt.basis(4, 0).dag() -
                qt.basis(4, 1) * qt.basis(4, 1).dag() +
                qt.basis(4, 2) * qt.basis(4, 2).dag() -
                qt.basis(4, 3) * qt.basis(4, 3).dag()))[:, 0]
        YY = qt.tensor(qt.sigmay(), qt.sigmay())[:, :]

        operators = np.array([ZI, IZ, ZZ, XI, IX, XX, YY], dtype=complex)

        label = ["ZI", "IZ", "ZZ", "XI", "IX", "XX", "YY"]
        self.solver_obj.plot_expectation(operators, label, 2)
コード例 #55
0
 def get_expect(self):
     XI = np.array(
         list(
             qt.basis(4, 1) * qt.basis(4, 3).dag() +
             qt.basis(4, 0) * qt.basis(4, 2).dag() +
             qt.basis(4, 2) * qt.basis(4, 0).dag() +
             qt.basis(4, 3) * qt.basis(4, 1).dag()))[:, 0]
     IX = np.array(
         list(
             qt.basis(4, 0) * qt.basis(4, 1).dag() +
             qt.basis(4, 1) * qt.basis(4, 0).dag() +
             qt.basis(4, 2) * qt.basis(4, 3).dag() +
             qt.basis(4, 3) * qt.basis(4, 2).dag()))[:, 0]
     return self.solver_obj.return_expectation_values(
         np.array([XI, IX], dtype=complex))
コード例 #56
0
#For anaharmonicities

N=50
omega=1
Xbb=0.09
g=0.2*omega
F=0.1*omega
HA=omega/2*(-qt.sigmaz()+qt.qeye(2))
HB=omega*qt.create(N)*qt.destroy(N)- Xbb/2*(qt.create(N)*qt.destroy(N)*qt.create(N)*qt.destroy(N))
HAB=g*(qt.tensor(qt.create(2),qt.destroy(N))+qt.tensor(qt.destroy(2), qt.create(N)))
H1=qt.tensor(F*qt.create(2),qt.qeye(N))
H2=qt.tensor(F*qt.destroy(2),qt.qeye(N))
H0=qt.tensor(HA, qt.qeye(N))+qt.tensor(qt.qeye(2),HB)+HAB
H=[H0, [H1, H1_coeff], [H2, H2_coeff]]
t=np.linspace(0,30*math.pi/g,10000)
psi0=qt.basis(2*N,0)
output = qt.mesolve(H, psi0, t, [qt.tensor(np.sqrt(0.05*omega)*qt.destroy(2),qt.qeye(N))], [])
Energy=np.zeros(10000)
Ergotropy=np.zeros(10000)
v=eigenvectors(HB)
EntropyB=np.zeros(10000)

for i in range(0,10000):
  A=np.array(output.states[i])
  FinalRho=np.trace(A.reshape(2,N,2,N), axis1=0, axis2=2)
  Rho_f=np.zeros((N,N))
  for j in range(0,N):
      Rho_f=eigenvalues(FinalRho)[N-1-j]*v[:,j]+Rho_f
  Energy[i-1]=np.real(np.matrix.trace(omega*np.dot(np.array(HB),FinalRho)))
  Ergotropy[i-1]=-np.real(np.matrix.trace(omega*np.dot(np.array(HB),(Rho_f-FinalRho)))) 
  EntropyB[i-1]=qt.entropy_vn(qt.Qobj(FinalRho),2)
コード例 #57
0
    'control_circuit': 'ECD_control_remote',
    'init': 'vac',
    'T': 8,
    'N': 100
}

# Evaluation environment params
eval_env_kwargs = {
    'control_circuit': 'ECD_control_remote',
    'init': 'vac',
    'T': 8,
    'N': 100
}

# Params for reward function
target_state = qt.tensor(qt.basis(2, 0), qt.basis(100, 4))

reward_kwargs = {
    'reward_mode': 'tomography_remote',
    'tomography': 'wigner',
    'target_state': target_state,
    'window_size': 16,
    'server_socket': server_socket,
    'amplitude_type': 'displacement',
    'epoch_type': 'training',
    'N_alpha': 100,
    'N_msmt': 10,
    'sampling_type': 'abs'
}

reward_kwargs_eval = {
コード例 #58
0
os.environ["CUDA_VISIBLE_DEVICES"] = "0"

import qutip as qt
import tensorflow as tf
import numpy as np
from math import sqrt, pi
from gkp.agents import PPO
from tf_agents.networks import actor_distribution_network
from gkp.agents import actor_distribution_network_gkp
from gkp.gkp_tf_env import helper_functions as hf

root_dir = r'E:\VladGoogleDrive\Qulab\GKP\sims\PPO\tomography_reward'
root_dir = os.path.join(root_dir, 'fock2_beta3_N40_B100_tomo10_lr3e-4_avg')

N = 40
target_state = qt.tensor(qt.basis(2, 0), qt.basis(N, 2))
reward_kwargs = {
    'reward_mode': 'tomography',
    'target_state': target_state,
    'window_size': 12
}

kwargs = {'N': N}

PPO.train_eval(
    root_dir=root_dir,
    random_seed=0,
    # Params for collect
    num_iterations=100000,
    train_batch_size=100,
    replay_buffer_capacity=15000,
コード例 #59
0
#math related packages
import scipy
import scipy as sc
from scipy import stats
import qutip as qt
#further packages
from time import time
from random import sample
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import random

#ket states
qubit0 = qt.basis(2, 0)
qubit1 = qt.basis(2, 1)
#density matrices
qubit0mat = qubit0 * qubit0.dag()
qubit1mat = qubit1 * qubit1.dag()


def partialTraceRem(obj, rem):
    #prepare keep list
    rem.sort(reverse=True)
    keep = list(range(len(obj.dims[0])))
    for x in rem:
        keep.pop(x)
    res = obj
    #return partial trace:
    if len(keep) != len(obj.dims[0]):
コード例 #60
0
def prep_H_qutip():
    q = qutip.basis(2)
    H = 1 / np.sqrt(2) * (qutip.sigmax() + qutip.sigmaz())
    return H * q