def test_Transformation8():
    "Check Qobj eigs and direct eig solver reverse transformations match"

    N = 10
    H = rand_herm(N)

    # generate a random basis
    rand = rand_dm(N, density=1)
    
    evals, rand_basis = rand.eigenstates()
    evals2, rand_basis2 = sp_eigs(rand.data, isherm=1)
    
    H1 = H.transform(rand_basis, True)
    H2 = H.transform(rand_basis2, True)
    assert_((H1 - H2).norm() < 1e-6)
    
    ket = rand_ket(N)
    K1 = ket.transform(rand_basis,1)
    K2 = ket.transform(rand_basis2,1)
    assert_((K1 - K2).norm() < 1e-6)
    
    bra = rand_ket(N).dag()
    B1 = bra.transform(rand_basis,1)
    B2 = bra.transform(rand_basis2,1)
    assert_((B1 - B2).norm() < 1e-6)
예제 #2
0
파일: test_rand.py 프로젝트: ajgpitch/qutip
    def testRandketSeed(self):
        "random ket with seed"

        seed = 12345
        U0 = rand_ket(5, seed=seed)
        U1 = rand_ket(5, seed=None)
        U2 = rand_ket(5, seed=seed)
        assert_(U0 != U1)
        assert_(U0 == U2)
예제 #3
0
    def testFloquetUnitary(self):
        """
        Floquet: test unitary evolution of time-dependent two-level system
        """

        delta = 1.0 * 2 * np.pi
        eps0 = 1.0 * 2 * np.pi
        A = 0.5 * 2 * np.pi
        omega = np.sqrt(delta ** 2 + eps0 ** 2)
        T = (2 * np.pi) / omega
        tlist = np.linspace(0.0, 2 * T, 101)
        psi0 = rand_ket(2)
        H0 = - eps0 / 2.0 * sigmaz() - delta / 2.0 * sigmax()
        H1 = A / 2.0 * sigmax()
        args = {'w': omega}
        H = [H0, [H1, lambda t, args: np.sin(args['w'] * t)]]
        e_ops = [num(2)]

        # solve schrodinger equation with floquet solver
        sol = fsesolve(H, psi0, tlist, e_ops, T, args)

        # compare with results from standard schrodinger equation
        sol_ref = mesolve(H, psi0, tlist, [], e_ops, args)

        assert_(max(abs(sol.expect[0] - sol_ref.expect[0])) < 1e-4)
예제 #4
0
파일: test_entropy.py 프로젝트: tmng/qutip
def test_EntropyLinear():
    "Linear entropy"
    # test_ entropy_vn = 0 for pure state
    psi = rand_ket(10)
    assert_equal(abs(entropy_linear(psi)) <= 1e-13, True)

    # test_ linear entropy always less than or equal to VN entropy
    rhos = [rand_dm(6) for k in range(10)]
    for k in rhos:
        assert_equal(entropy_linear(k) <= entropy_vn(k), True)
def test_Transformation5():
    "Consistency between transformations of kets and density matrices"

    N = 4
    psi0 = rand_ket(N)

    # generate a random basis
    evals, rand_basis = rand_dm(N, density=1).eigenstates()

    rho1 = ket2dm(psi0).transform(rand_basis, True)
    rho2 = ket2dm(psi0.transform(rand_basis, True))

    assert_((rho1 - rho2).norm() < 1e-6)
예제 #6
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)
예제 #7
0
 def random_state(self):
     self.state = qt.rand_ket(self.n())
     self.refresh()
     return self.state
예제 #8
0
    return [qutip.expect(spin_ops["X"], state),\
            qutip.expect(spin_ops["Y"], state),\
            qutip.expect(spin_ops["Z"], state)]


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

vpython.scene.width = 500
vpython.scene.height = 500

n_qubits = 2

dt = 0.001
n_points = 50

state = qutip.rand_ket(2**n_qubits)
energy = qutip.rand_herm(2**n_qubits)
unitary = qutip.Qobj(scipy.linalg.expm(-2 * math.pi * im * energy.full() * dt))
qubits = None
qubit_colors = [
    vpython.vector(random.random(), random.random(), random.random())
    for i in range(n_qubits)
]
vsphere = vpython.sphere(pos=vpython.vector(0,0,0),\
                         radius=1.0,\
                         color=vpython.color.blue,\
                         opacity=0.4)
vspin = vpython.arrow(shaftwidth=0.01, headwidth=0.001, headlength=0.001)
vstars = [vpython.sphere(radius=0.05,\
                         color=vpython.color.white,\
                         opacity=0.8,\
예제 #9
0
                            tau=1e-8,
                            progress_bar=True)
    return np.max([qt.fidelity(target, s) for s in states])


def random_purity_benchmark(state, **kwargs):
    target = root_iSWAP * state.ptrace([1, 2])
    sim = Simulation(do_qt_mesolve, state=state, fname='time_dependent.yaml')
    states = sim.run_solver(nsteps=2000, steps=10000, tau=1e-7, rhs_reuse=True)
    print('Done a state')
    return qt.fidelity(target, states[-1].ptrace([1, 2]))


if __name__ == '__main__':
    n = thermal_state(5e9, 20e-3, 5)
    state = qt.tensor(n, qt.rand_ket(2), qt.rand_ket(2))
    sim = Simulation(do_qt_mesolve, state=state, fname='time_dependent.yaml')
    ls = get_lind_list(sim.w_c, 1e4, 20e-3, 1, 1e2, sim.dims)
    sim.lindblads = ls
    res = sim.run_solver(nsteps=1000, steps=10000, tau=1e-7, progress_bar=True)
    # bvs, ns = sim.parse_states(res)
    b = qt.Bloch()
    for i in range(10000):
        b.clear()
        b.add_states(res[i].ptrace(1))
        b.add_states(res[i].ptrace(2))
        b.render()
        b.save(dirc='temp')
    # plt.hist(ns, 50)
    # plt.show()
    # targets = [[qt.tensor(qt.rand_ket(2), qt.rand_ket(2))] for i in range(100)]
예제 #10
0
        if np.allclose(eigs[i], complex(1)):
            stab_states.append(qt.Qobj(vecs[:,i], dims=[[2],[1]]))

basis = [np.matrix('1;0;0;0'), np.matrix('0;1;0;0'), 
         np.matrix('0;0;1;0'), np.matrix('0;0;0;1')]
A = np.matrix(np.zeros((4, 60), dtype=np.complex_))
for i in range(4):
    for j, state in enumerate(stab_states):
        A[i, j] = np.sum(basis[i].H * np.matrix(state.full()))
b = np.matrix(np.zeros((4,1), dtype=np.complex_))

norm_0 = np.zeros(500)
truthy = []
print("Benchmarking 500 random states")
for i in range(500):
    state = qt.rand_ket(4, dims=[[2,2],[1,1]])
    for j in range(4):
        b[j] = np.sum(basis[j].H*np.matrix(state.full()))
    norm_0[i] = np.count_nonzero(SL0(A,b, 1e-12))
print("Average L0 norm is " + str(np.mean(norm_0)))
norm_0 = np.zeros(len(magic_states))
for i, state in enumerate(magic_states):
    for j in range(4):
        b[j] = np.sum(basis[j].H*qt.tensor([state,state]).full())
    norm_0[i] = np.count_nonzero(SL0(A,b,1e-12))
print("Norm for edge type states is "+str(np.mean(norm_0)))
norm_0 = np.zeros(len(face_states))
for i, state in enumerate(face_states):
    for j in range(4):
        b[j] = np.sum(basis[j].H*qt.tensor([state,state]).full())
    norm_0[i] = np.count_nonzero(SL0(A,b,1e-12))
예제 #11
0
import operator
import numpy as np
import sympy
import mpmath
import scipy
import qutip 
import vpython
import random

def im():
    return complex(0, 1)

vpython.scene.height = 600
vpython.scene.width = 800

alice = qutip.rand_ket(2)
bob = qutip.rand_ket(2)

alice_center = vpython.vector(-1,0,0)
valice = vpython.sphere(pos=alice_center,\
                         radius=1.0,\
                         color=vpython.color.blue,\
                         opacity=0.3)
valice_star = vpython.sphere(radius=0.1,\
							 color=vpython.color.white,\
							 opacity=0.7, emissive=True)
valice_arrow = vpython.arrow(color=vpython.color.blue,\
							 shaftwidth=0.06)

bob_center = vpython.vector(1,0,0)
vbob = vpython.sphere(pos=bob_center,\
예제 #12
0
#F = fp.Fidelity(Ham,G,N,dCS)
#print("The initial Fidelity is: "+str(F))


# Opitimization parameters 
delta = 0.001 # : for the derivative 
check = 0      # : to check convergence
s = 0          # : intermediate value of the optimization 
time = step    # : time steps

startTime = datetime.now() # : to check running time
while True :
    
    time += step
    
    rho_0 = qt.rand_ket(N = 8, dims = [[2,2,2], [1,1,1]]) # Initial random state of the system
    index = randrange(len(J)) # pick the derivative direction: We do not compute the gradient.
                              # Rather, each step, we compute 
                              # the derivative with respect to a random direction 
    
    JdJ = [x for x in J]
    JdJ[index] += delta
    
    HJ = H(J,N) # We compute the Hamiltonian for J 
    HJdJ = H(JdJ,N) #and for a little perturbation of J: JdJ
    
    grad = (fp.Likelihood3(JdJ, rho_0,G,dCS,HJdJ) - fp.Likelihood3(J, rho_0,G,dCS,HJ))/delta # The gradient of the Likelihood
    J[index] = J[index] + grad/sqrt(time) # Updating step 
    
    # One could drop the following 4 lines if not interested in the optimization behaviour 
    HJ = H(J,N)
예제 #13
0
파일: test_rand.py 프로젝트: ajgpitch/qutip
 def testRandket(self):
     "random ket"
     P = [rand_ket(5) for k in range(5)]
     for p in P:
         assert_equal(p.type == 'ket', True)
예제 #14
0
def keyboard(event):
    global clock_probs, TIME_projs, state, Z_projs, ZV, ZL, HL, H_projs, SHIFT, display_proj, pointing_to, clock_n, evolving, initial
    key = event.key

    if key == "c":
        choice = np.random.choice(list(range(clock_n)),
                                  p=np.array(clock_probs) /
                                  sum(np.array(clock_probs)))
        state = (qt.tensor(qt.identity(spin_n), TIME_projs[choice]) *
                 state).unit()
        print("clock time: %.4f" % (choice))
    elif key == "v":
        probs = np.array([(state * state.dag() * proj).tr()
                          for proj in Z_projs]).real
        choice = np.random.choice(list(range(len(ZV))), p=probs / sum(probs))
        state = (Z_projs[choice] * state).unit()
        print("spin Z eigenvalue: %.4f" % (ZL[choice]))
    elif key == "b":
        probs = np.array([(state * state.dag() * proj).tr()
                          for proj in H_projs]).real
        choice = np.random.choice(list(range(len(H_projs))),
                                  p=probs / sum(probs))
        state = (H_projs[choice] * state).unit()
        print("energy eigenvalue: %.4f" % (HL[choice]))
    elif key == "9":
        state = (SHIFT * state).unit()
    elif key == "0":
        state = (SHIFT.dag() * state).unit()
    elif key == "r":
        if display_proj == False:
            display_proj = True
        else:
            display_proj = False
    elif key == "e":
        pointing_to -= 1
        if pointing_to < 0:
            pointing_to = clock_n - 1
    elif key == "t":
        pointing_to += 1
        if pointing_to >= clock_n:
            pointing_to = 0
    elif key == "a":
        state = qt.tensor(
            (-1j * qt.sigmax() * 0.1).expm(), qt.identity(clock_n)) * state
    elif key == "d":
        state = qt.tensor(
            (1j * qt.sigmax() * 0.1).expm(), qt.identity(clock_n)) * state
    elif key == "s":
        state = qt.tensor(
            (-1j * qt.sigmay() * 0.1).expm(), qt.identity(clock_n)) * state
    elif key == "w":
        state = qt.tensor(
            (1j * qt.sigmay() * 0.1).expm(), qt.identity(clock_n)) * state
    elif key == "z":
        state = qt.tensor(
            (-1j * qt.sigmaz() * 0.1).expm(), qt.identity(clock_n)) * state
    elif key == "x":
        state = qt.tensor(
            (1j * qt.sigmaz() * 0.1).expm(), qt.identity(clock_n)) * state
    elif key == "q":
        if evolving == True:
            evolving = False
        else:
            evolving = True
    elif key == "p":
        state = initial
    elif key == "o":
        state_ = qt.rand_ket(state.shape[0])
        state_.dims = state.dims
        state = state_
    elif key == "h":
        display_help()
예제 #15
0
 def test_known_cases_pure_states(self, dimension):
     left = rand_ket(dimension)
     right = rand_ket(dimension)
     expected = np.sqrt(2 * (1 - np.abs(left.overlap(right))**2))
     assert hellinger_dist(left, right) == pytest.approx(expected, abs=1e-7)
예제 #16
0
def rand_su2n_state(n):
    return su2n_state([qt.rand_ket(2) for i in range(n)])
예제 #17
0

def qubit_xyz(spin):
    return [qt.expect(qt.sigmax(), spin),\
      qt.expect(qt.sigmay(), spin),\
      qt.expect(qt.sigmaz(), spin)]


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

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()
예제 #18
0
                           for o in ["X", "Y", "Z"]])))
    for i in range(len(E)):
        print("%s : %s" % (annotations[i], e[i]))


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

inverted = True
show_originals = True

n = 4
#pts = [3*np.random.randn(3) for i in range(n)]
pts = [np.array([0, 0, 4 * i - n / 2]) for i in range(n)]

views = make_views(pts)
spinors = [qt.rand_ket(2) for i in range(n)]
state = su2n_state(spinors)
S, E, annotations = su2(n)
P = constellations_matrix(views_constellations(views))
phases = su2n_phases(state)

initial_state = P * state if inverted else P.dag() * state

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

vp.scene = vp.canvas(background=vp.color.white, width=1000, height=800)
vcolors = [vp.vector(*np.random.rand(3)) for i in range(n)]
pieces = split_su2n_state(state)

if show_originals:
    vspheres_ = [vp.sphere(color=vcolors[i], radius=pieces[i].norm(), opacity=0.05,\
        res.append(np.count_nonzero(x))
        print('SL0 done for target')
    return res

FILE_NAME = datetime.datetime.now().strftime('%d%m%Y_%H%M%S')+".txt"
OUT_STRING_1 = "For the {0} state on {1} qubits,"
OUT_STRING_2 = "the SL0 estimate gives a sparsenes of {}"
OUT_STRING_3 = "the brute force search returns a sparseness of {}."
OUT_STRING_4 = "The resulting basis states found were:"

if __name__ == '__main__':
    FILE_NAME = 'RandSparse.txt'
    # ns = [1,2,3,4]
    # strs = ['H', 'F']
    # strs = ['Root T', 'Root Root T']
    r = qt.rand_ket(2)
    r2 = qt.rand_ket(4)
    targets = [r, qt.tensor(r,r), r2, qt.tensor(r,r,r)]
    ns = [1, 2, 2, 3]
    strs = ['Random', '2fold product', '2 qubit random', '3 fold product']
    for i, n in enumerate(ns):
        # targets = [qt.tensor([H]*n), qt.tensor([F]*n)]
        # targets = [qt.tensor([RT]*n), qt.tensor([RRT]*n)]
        stabs = stab_states(n)
        SL0s = SL0_estimate([targets[i]], stabs, n)
        basis, val = brute_force_sparseness(targets[i], stabs)
        with open(FILE_NAME, 'a') as f:
            out = OUT_STRING_1.format(strs[i], n)+"\n"
            out += OUT_STRING_2.format(SL0s[0])
            out += OUT_STRING_3.format(val) + "\n"
            out += "\n".join(str(b) for b in basis) +"\n"
예제 #20
0
        if self.other != None:
            other_according_to_self = self.other.state.transform(self.state)
            self.local_other.state = other_according_to_self
            xyz = state_xyz(other_according_to_self, self.other.n)
            self.local_other.center = [self.vstars[II].pos.x-1*xyz[0], self.vstars[II].pos.y-1*xyz[1], self.vstars[II].pos.z-1*xyz[2]]
            #self.local_other.center = [self.vsphere.pos.x+1*xyz[0], self.vsphere.pos.y+1*xyz[1], self.vsphere.pos.z+1*xyz[2]]
            self.local_other.update()
        
    def apply(self, operator, inverse=False, dt=0.01):
        unitary = qutip.Qobj(scipy.linalg.expm(-2*math.pi*complex(0,1)*operator.full()*dt))
        if inverse:
            unitary = unitary.dag()
        self.state = unitary*self.state*unitary.dag()

n = 2
A = Sphere(n, qutip.rand_ket(n).ptrace(0), [-1.5, 0, 0], vpython.color.red)
B = Sphere(n, qutip.rand_ket(n).ptrace(0), [1.5, 0, 0], vpython.color.blue)

A.set_other(B)
B.set_other(A)

energy = qutip.rand_herm(n)
energy_unitary = qutip.Qobj(scipy.linalg.expm(-2*math.pi*complex(0,1)*energy.full()*0.01))

def keyboard(event):
    global A
    global B
    global n
    key = event.key
    operator = None
    X, Y, Z = qutip.jmat((n-1.)/2.)
예제 #21
0
class TestHusimiQ:
    @pytest.mark.parametrize('xs', ["", 1, None], ids=['str', 'int', 'none'])
    def test_failure_if_non_arraylike_coordinates(self, xs):
        state = qutip.rand_ket(4)
        valid = np.linspace(-1, 1, 5)
        with pytest.raises(TypeError) as e:
            qutip.qfunc(state, xs, valid)
        assert "must be array-like" in e.value.args[0]
        with pytest.raises(TypeError) as e:
            qutip.qfunc(state, valid, xs)
        assert "must be array-like" in e.value.args[0]
        with pytest.raises(TypeError) as e:
            qutip.QFunc(xs, valid)
        assert "must be array-like" in e.value.args[0]
        with pytest.raises(TypeError) as e:
            qutip.QFunc(valid, xs)
        assert "must be array-like" in e.value.args[0]

    @pytest.mark.parametrize('ndim', [2, 3])
    def test_failure_if_coordinates_not_1d(self, ndim):
        state = qutip.rand_ket(4)
        valid = np.linspace(-1, 1, 5)
        bad = valid.reshape((-1, ) + (1, ) * (ndim - 1))
        with pytest.raises(ValueError) as e:
            qutip.qfunc(state, bad, valid)
        assert "must be 1D" in e.value.args[0]
        with pytest.raises(ValueError) as e:
            qutip.qfunc(state, valid, bad)
        assert "must be 1D" in e.value.args[0]
        with pytest.raises(ValueError) as e:
            qutip.QFunc(bad, valid)
        assert "must be 1D" in e.value.args[0]
        with pytest.raises(ValueError) as e:
            qutip.QFunc(valid, bad)
        assert "must be 1D" in e.value.args[0]

    @pytest.mark.parametrize('dm', [True, False], ids=['dm', 'ket'])
    def test_failure_if_tensor_hilbert_space(self, dm):
        if dm:
            state = qutip.rand_dm(4, dims=[[2, 2], [2, 2]])
        else:
            state = qutip.rand_ket(4, dims=[[2, 2], [1, 1]])
        xs = np.linspace(-1, 1, 5)
        with pytest.raises(ValueError) as e:
            qutip.qfunc(state, xs, xs)
        assert "must not have tensor structure" in e.value.args[0]
        with pytest.raises(ValueError) as e:
            qutip.QFunc(xs, xs)(state)
        assert "must not have tensor structure" in e.value.args[0]

    def test_QFunc_raises_if_insufficient_memory(self):
        xs = np.linspace(-1, 1, 11)
        state = qutip.rand_ket(4)
        qfunc = qutip.QFunc(xs, xs, memory=0)
        with pytest.raises(MemoryError) as e:
            qfunc(state)
        assert e.value.args[0].startswith("Refusing to precompute")

    def test_qfunc_warns_if_insufficient_memory(self):
        xs = np.linspace(-1, 1, 11)
        state = qutip.rand_dm(4)
        with pytest.warns(UserWarning) as e:
            qutip.qfunc(state, xs, xs, precompute_memory=0)
        assert (e[0].message.args[0].startswith(
            "Falling back to iterative algorithm"))

    @pytest.mark.parametrize('obj', [
        pytest.param(np.eye(2, dtype=np.complex128), id='ndarray'),
        pytest.param([[1, 0], [0, 1]], id='list'),
        pytest.param(1, id='int'),
    ])
    def test_failure_if_not_a_Qobj(self, obj):
        xs = np.linspace(-1, 1, 11)
        with pytest.raises(TypeError) as e:
            qutip.qfunc(obj, xs, xs)
        assert e.value.args[0].startswith("state must be Qobj")
        qfunc = qutip.QFunc(xs, xs)
        with pytest.raises(TypeError) as e:
            qfunc(obj)
        assert e.value.args[0].startswith("state must be Qobj")

    # Use indirection so that the tests can still be collected if there's a bug
    # in the generating QuTiP functions.
    @pytest.mark.parametrize('state', [
        pytest.param(lambda: qutip.rand_super(2), id='super'),
        pytest.param(lambda: qutip.rand_ket(2).dag(), id='bra'),
        pytest.param(lambda: 1j * qutip.rand_dm(2), id='non-dm operator'),
        pytest.param(lambda: qutip.Qobj([[1, 0], [0, 0]], dims=[[2], [2, 1]]),
                     id='nonsquare dm'),
        pytest.param(lambda: qutip.operator_to_vector(qutip.qeye(2)),
                     id='operator-ket'),
        pytest.param(lambda: qutip.operator_to_vector(qutip.qeye(2)).dag(),
                     id='operator-bra'),
    ])
    def test_failure_if_not_a_state(self, state):
        xs = np.linspace(-1, 1, 11)
        state = state()
        with pytest.raises(ValueError) as e:
            qutip.qfunc(state, xs, xs)
        assert (e.value.args[0].startswith(
            "state must be a ket or density matrix"))
        qfunc = qutip.QFunc(xs, xs)
        with pytest.raises(ValueError) as e:
            qfunc(state)
        assert (e.value.args[0].startswith(
            "state must be a ket or density matrix"))

    @pytest.mark.parametrize('g', [
        pytest.param(np.sqrt(2), id='natural units'),
        pytest.param(1, id='arb units'),
    ])
    @pytest.mark.parametrize('n_ys', [5, 101])
    @pytest.mark.parametrize('n_xs', [5, 101])
    @pytest.mark.parametrize('dm', [True, False], ids=['dm', 'ket'])
    @pytest.mark.parametrize('size', [5, 32])
    def test_function_and_class_are_equivalent(self, size, dm, n_xs, n_ys, g):
        xs = np.linspace(-1, 1, n_xs)
        ys = np.linspace(0, 2, n_ys)
        state = qutip.rand_dm(size) if dm else qutip.rand_ket(size)
        function = qutip.qfunc(state, xs, ys, g)
        class_ = qutip.QFunc(xs, ys, g)(state)
        np.testing.assert_allclose(function, class_)

    @pytest.mark.parametrize('g', [
        pytest.param(np.sqrt(2), id='natural units'),
        pytest.param(1, id='arb units'),
    ])
    @pytest.mark.parametrize('n_ys', [5, 101])
    @pytest.mark.parametrize('n_xs', [5, 101])
    @pytest.mark.parametrize('size', [5, 32])
    def test_iterate_and_precompute_are_equivalent(self, size, n_xs, n_ys, g):
        xs = np.linspace(-1, 1, n_xs)
        ys = np.linspace(0, 2, n_ys)
        state = qutip.rand_dm(size)
        iterate = qutip.qfunc(state, xs, ys, g, precompute_memory=None)
        precompute = qutip.qfunc(state, xs, ys, g, precompute_memory=np.inf)
        np.testing.assert_allclose(iterate, precompute)

    @pytest.mark.parametrize('initial_size', [5, 8])
    @pytest.mark.parametrize('dm', [True, False], ids=['dm', 'ket'])
    def test_same_class_can_take_many_sizes(self, dm, initial_size):
        xs = np.linspace(-1, 1, 11)
        ys = np.linspace(0, 2, 11)
        shape = np.meshgrid(xs, ys)[0].shape
        sizes = initial_size + np.array([0, 1, -1, 4])
        qfunc = qutip.QFunc(xs, ys)
        for size in sizes:
            state = qutip.rand_dm(size) if dm else qutip.rand_ket(size)
            out = qfunc(state)
            assert isinstance(out, np.ndarray)
            assert out.shape == shape

    @pytest.mark.parametrize('dm_first', [True, False])
    def test_same_class_can_mix_ket_and_dm(self, dm_first):
        dms = [True, False, True, False]
        if not dm_first:
            dms = dms[::-1]
        xs = np.linspace(-1, 1, 11)
        ys = np.linspace(0, 2, 11)
        shape = np.meshgrid(xs, ys)[0].shape
        qfunc = qutip.QFunc(xs, ys)
        for dm in dms:
            state = qutip.rand_dm(4) if dm else qutip.rand_ket(4)
            out = qfunc(state)
            assert isinstance(out, np.ndarray)
            assert out.shape == shape

    @pytest.mark.parametrize('n_ys', [5, 101])
    @pytest.mark.parametrize('n_xs', [5, 101])
    @pytest.mark.parametrize('mix', [0.1, 0.5])
    def test_qfunc_is_linear(self, n_xs, n_ys, mix):
        xs = np.linspace(-1, 1, n_xs)
        ys = np.linspace(-1, 1, n_ys)
        qfunc = qutip.QFunc(xs, ys)
        left, right = qutip.rand_dm(5), qutip.rand_dm(5)
        qleft, qright = qfunc(left), qfunc(right)
        qboth = qfunc(mix * left + (1 - mix) * right)
        np.testing.assert_allclose(mix * qleft + (1 - mix) * qright, qboth)

    @pytest.mark.parametrize('n_ys', [5, 101])
    @pytest.mark.parametrize('n_xs', [5, 101])
    @pytest.mark.parametrize('size', [5, 32])
    def test_ket_and_dm_give_same_result(self, n_xs, n_ys, size):
        xs = np.linspace(-1, 1, n_xs)
        ys = np.linspace(-1, 1, n_ys)
        state = qutip.rand_ket(size)
        qfunc = qutip.QFunc(xs, ys)
        np.testing.assert_allclose(qfunc(state), qfunc(state.proj()))

    @pytest.mark.parametrize('g', [
        pytest.param(np.sqrt(2), id='natural units'),
        pytest.param(1, id='arb units'),
    ])
    @pytest.mark.parametrize('ys', [
        pytest.param(np.linspace(-1, 1, 5), id='(-1,1,5)'),
        pytest.param(np.linspace(0, 2, 3), id='(0,2,3)'),
    ])
    @pytest.mark.parametrize('xs', [
        pytest.param(np.linspace(-1, 1, 5), id='(-1,1,5)'),
        pytest.param(np.linspace(0, 2, 3), id='(0,2,3)'),
    ])
    @pytest.mark.parametrize('size', [3, 5])
    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))
예제 #22
0
    new_state = unitary * qubit * unitary.dag()

    old_vector = qubit_to_vector(old_state)
    new_vector = qubit_to_vector(new_state)

    old_angles, r0 = vector_to_angles(old_vector)
    new_angles, r1 = vector_to_angles(new_vector)
    angle_delta = new_angles[0] - old_angles[0]

    vector_delta = new_vector - old_vector
    vector_delta = vector_delta.T[0].tolist()

    gauge_delta = []
    for i in range(4):
        if vector_delta[i] != 0:
            delta.append([angle_delta / vector_delta[i]])
        else:
            delta.append([0])
    gauge_delta = np.array(delta)

    return (new_state*cmath.exp(-im()*angle_delta),\
            vector_to_qubit(normalize(qubit_to_vector(photon) + (1./gauge_charge)*gauge_delta)))


qubit = qutip.rand_ket(2).ptrace(0)
photon = qutip.rand_ket(2).ptrace(0)

unitary = (-2 * math.pi * im() * qutip.rand_herm(2) * 0.001).expm()

qubit1, qubit2 = evolve(qubit, photon, unitary, 2)
예제 #23
0
 def test_ket_and_dm_give_same_result(self, n_xs, n_ys, size):
     xs = np.linspace(-1, 1, n_xs)
     ys = np.linspace(-1, 1, n_ys)
     state = qutip.rand_ket(size)
     qfunc = qutip.QFunc(xs, ys)
     np.testing.assert_allclose(qfunc(state), qfunc(state.proj()))
예제 #24
0
 def testRandket(self):
     "random ket"
     P = [rand_ket(5) for k in range(5)]
     for p in P:
         assert_equal(p.type == 'ket', True)
예제 #25
0
                for i in range(len(WHICH_IS)):
                    j, m = WHICH_IS[i]
                    if j == 0:  # No spin-0 for now
                        probabilities[i] = 0

                probabilities = np.array(probabilities)
                probabilities = probabilities / probabilities.sum()

                j_probs = []
                for i, B in enumerate(boundaries):
                    if i == len(boundaries) - 1:
                        j_probs.append(sum(probabilities[B:]))
                    else:
                        j_probs.append(sum(probabilities[B:boundaries[i + 1]]))

                probs = {"up": j_probs[0], "down": j_probs[1]}
                theta = math.acos(2 * probs["up"] -
                                  1)  #math.acos(1-2*probs["down"])
                return theta


if __name__ == '__main__':
    spheres = Spheres()
    a = spheres.add_child(qt.rand_ket(10))
    b = spheres.add_child(qt.rand_ket(12))
    #spheres.state = qt.rand_ket(6*7)
    #spheres.state.dims = [[6,7], [1,1]]
    #spheres.split_child(a,0.5,0.5)
    spheres.penrose_angle(a, b)
예제 #26
0
    Z_ = qt.rz(-np.pi, N=3, target=2)
    state_array = state.full()

    if result == 1:
        state = -1j * X_ * state
        amp = [state_array[3], state_array[2]]
        return qt.Qobj(amp).unit()

    if result == 2:
        state = -1j * Z_ * state
        amp = [state_array[4], -state_array[5]]
        return qt.Qobj(amp).unit()
    if result == 3:

        state = -1 * Z_ * X_ * state
        amp = [state_array[7], -state_array[6]]
        return qt.Qobj(amp).unit()

    amp = [state_array[0], state_array[1]]
    return qt.Qobj(amp).unit()



if __name__=='__main__':
    state = qt.rand_ket(N=2)
    result = evolute(initialize(state))
    teleport_state = teleport(result, measure(result))
    
    print(state.full())
    print(teleport_state.full())
예제 #27
0
    def __init__(self):
        self.qubit = Qubit(qutip.rand_ket(2).ptrace(0), self)
        self.photon = Qubit(qutip.rand_ket(2).ptrace(0), self, emissive=True)

        self.charge = 1
        self.energy = qutip.identity(2)
예제 #28
0
    xyz = np.array([[x],\
                    [y],\
                    [z]])
    if w == 1:
        return xyz
    else:
        return (1./(1.-w))*xyz

def normalize(v):
    norm = np.linalg.norm(v)
    if norm == 0: 
       return v
    return v / norm

dt = 0.01
qubit = qutip.rand_ket(2).ptrace(0)
photon = np.array([[0],[0],[0],[0]], dtype='complex128')

vsphere = vpython.sphere(pos=vpython.vector(0,0,0),\
                         radius=1,\
                         opacity=0.4,\
                         color=vpython.color.blue)
vbase = vpython.sphere(radius=0.1,\
                       opacity=0.8,\
                       color=vpython.color.white, emissive=True)
vphoton = vpython.sphere(radius=0.2,\
                         color=vpython.color.yellow,\
                         opacity=0.2)


def apply(transformation):
예제 #29
0
 def test_pure_state(self):
     assert abs(qutip.entropy_linear(qutip.rand_ket(10))) < 1e-12
예제 #30
0
n_samples = 10000  # Number of samples for each type

for i in range(n_samples):
    # Random States
    dm = q.rand_dm(2**n_qubits, density=0.75, pure=True).full()
    if n_qubits == 2:
        wigner = wf.wigner_2qb_ea(dm, rotation_operator)
    elif n_qubits == 3:
        wigner = wf.wigner_3qb_ea(dm, rotation_operator)
    elif n_qubits == 4:
        wigner = wf.wigner_4qb_ea(dm, rotation_operator)
    elif n_qubits == 5:
        wigner = wf.wigner_5qb_ea(dm, rotation_operator)
    wigners.append(wigner.flatten())
    # Random Separable States
    psi = np.matrix(q.rand_ket(2, density=0.75).full())
    for i in range(n_qubits - 1):
        psi = np.kron(psi, np.matrix(q.rand_ket(2, density=0.75).full()))
    dm = psi * psi.getH()
    if n_qubits == 2:
        wigner = wf.wigner_2qb_ea(dm, rotation_operator)
    elif n_qubits == 3:
        wigner = wf.wigner_3qb_ea(dm, rotation_operator)
    elif n_qubits == 4:
        wigner = wf.wigner_4qb_ea(dm, rotation_operator)
    elif n_qubits == 5:
        wigner = wf.wigner_5qb_ea(dm, rotation_operator)
    wigners.append(wigner.flatten())
    # Random Entangled States
    dm = np.zeros((2**n_qubits, 2**n_qubits))
    dm[0, 0] = 0.5
    sim = Simulation(do_qt_mesolve, state=state, fname='2qtest.yaml')
    states = sim.run_solver(nsteps=1000, steps=1000, tau=1e-8,
                            progress_bar=True)
    return np.max([qt.fidelity(target, s) for s in states])

def random_purity_benchmark(state, **kwargs):
    target = root_iSWAP * state.ptrace([1,2])
    sim = Simulation(do_qt_mesolve, state=state, fname='time_dependent.yaml')
    states = sim.run_solver(nsteps=2000, steps=10000, tau=1e-7, rhs_reuse=True)
    print('Done a state')
    return qt.fidelity(target, states[-1].ptrace([1,2]))


if __name__ == '__main__':
    n = thermal_state(5e9, 20e-3, 5)
    state = qt.tensor(n, qt.rand_ket(2), qt.rand_ket(2))
    sim = Simulation(do_qt_mesolve, state=state, fname='time_dependent.yaml')
    ls = get_lind_list(sim.w_c, 1e4, 20e-3, 1, 1e2, sim.dims)
    sim.lindblads = ls
    res = sim.run_solver(nsteps=1000, steps=10000, tau=1e-7, progress_bar=True)
    # bvs, ns = sim.parse_states(res)
    b = qt.Bloch()
    for i in range(10000):
        b.clear()
        b.add_states(res[i].ptrace(1))
        b.add_states(res[i].ptrace(2))
        b.render()
        b.save(dirc='temp')
    # plt.hist(ns, 50)
    # plt.show()
    # targets = [[qt.tensor(qt.rand_ket(2), qt.rand_ket(2))] for i in range(100)]
예제 #32
0
파일: ttt.py 프로젝트: insanj/stars
def angle_to_qubit(angle):
    theta, phi = angle
    qubit = [math.cos(theta/2.), math.sin(theta/2.)*cmath.exp(complex(0,1)*phi)]
    return qutip.Qobj(np.array(qubit))

def qubit_to_angle(qubit):
	dm = qubit.ptrace(0).full()
	x = float(2*dm[0][1].real)
	y = float(2*dm[1][0].imag)
	z = float((dm[0][0] - dm[1][1]).real)
	return xyz_to_angle([x, y, z])

if True:
	print("\nqubit -> angle test")
	qubit = qutip.rand_ket(2)
	angle = qubit_to_angle(qubit)
	qubit2 = angle_to_qubit(angle)
	print("qubit:\n%s" % str(qubit))
	print("angle:\n%s" % str(angle))
	print("qubit2:\n%s" % str(qubit2))

	print(angle_to_xyz(qubit_to_angle(qubit)))
	print(angle_to_xyz(qubit_to_angle(qubit2)))

if False:
	print("\nangle -> qubit test")
	angle = (random.uniform(0, math.pi), random.uniform(0, 2*math.pi))
	qubit = angle_to_qubit(angle)
	angle2 = qubit_to_angle(qubit)
	print("angle:\n%s" % str(angle))