Ejemplo n.º 1
0
    def test_basic_pulse(self):
        """
        Test for basic pulse generation and attributes.
        """
        coeff = np.array([0.1, 0.2, 0.3, 0.4])
        tlist = np.array([0., 1., 2., 3.])
        ham = sigmaz()

        # Basic tests
        pulse1 = Pulse(ham, 1, tlist, coeff)
        assert_allclose(
            pulse1.get_ideal_qobjevo(2)(0).full(),
            tensor(identity(2), sigmaz()).full() * coeff[0])
        pulse1.tlist = 2 * tlist
        assert_allclose(pulse1.tlist, 2 * tlist)
        pulse1.tlist = tlist
        pulse1.coeff = 2 * coeff
        assert_allclose(pulse1.coeff, 2 * coeff)
        pulse1.coeff = coeff
        pulse1.qobj = 2 * sigmay()
        assert_allclose(pulse1.qobj.full(), 2 * sigmay().full())
        pulse1.qobj = ham
        pulse1.targets = 3
        assert_allclose(pulse1.targets, 3)
        pulse1.targets = 1
        qobjevo = pulse1.get_ideal_qobjevo(2)
        if parse_version(qutip.__version__) >= parse_version('5.dev'):
            expected = QobjEvo([tensor(identity(2), sigmaz()), coeff],
                               tlist=tlist,
                               order=0)
        else:
            expected = QobjEvo([tensor(identity(2), sigmaz()), coeff],
                               tlist=tlist,
                               args={"_step_func_coeff": True})
        _compare_qobjevo(qobjevo, expected, 0, 3)
Ejemplo n.º 2
0
def test_diagHamiltonian2():
    """
    Diagonalization of composite systems
    """

    H1 = scipy.rand() * sigmax() + scipy.rand() * sigmay() +\
        scipy.rand() * sigmaz()
    H2 = scipy.rand() * sigmax() + scipy.rand() * sigmay() +\
        scipy.rand() * sigmaz()

    H = tensor(H1, H2)

    evals, ekets = H.eigenstates()

    for n in range(len(evals)):
        # assert that max(H * ket - e * ket) is small
        assert_equal(
            amax(abs((H * ekets[n] - evals[n] * ekets[n]).full())) < 1e-10,
            True)

    N1 = 10
    N2 = 2

    a1 = tensor(destroy(N1), qeye(N2))
    a2 = tensor(qeye(N1), destroy(N2))
    H = scipy.rand() * a1.dag() * a1 + scipy.rand() * a2.dag() * a2 + \
        scipy.rand() * (a1 + a1.dag()) * (a2 + a2.dag())
    evals, ekets = H.eigenstates()

    for n in range(len(evals)):
        # assert that max(H * ket - e * ket) is small
        assert_equal(
            amax(abs((H * ekets[n] - evals[n] * ekets[n]).full())) < 1e-10,
            True)
Ejemplo n.º 3
0
def keyboard(event):
    global field
    key = event.key
    qubit = field.qubit
    if key == "a":
        #field.energy = 0.5*field.energy+qutip.sigmax()
        field.energy = field.energy - 0.5 * qutip.sigmax()
        #qubit.evolve(qutip.sigmax(), inverse=True)
    elif key == "d":
        #field.energy = 0.5*field.energy*qutip.sigmax()
        field.energy = field.energy + 0.5 * qutip.sigmax()
        #qubit.evolve(qutip.sigmax(), inverse=False)
    elif key == "s":
        #field.energy = 0.5*field.energy*qutip.sigmaz()
        field.energy = field.energy - 0.5 * qutip.sigmaz()
        #qubit.evolve(qutip.sigmaz(), inverse=True)
    elif key == "w":
        #field.energy = 0.5*field.energy*qutip.sigmaz()
        field.energy = field.energy + 0.5 * qutip.sigmaz()
        #qubit.evolve(qutip.sigmaz(), inverse=False)
    elif key == "z":
        #field.energy = 0.5*field.energy*qutip.sigmay()
        field.energy = field.energy - 0.5 * qutip.sigmay()
        #qubit.evolve(qutip.sigmay(), inverse=True)
    elif key == "x":
        #field.energy = 0.5*field.energy*qutip.sigmay()
        field.energy = field.energy + 0.5 * qutip.sigmay()
        #qubit.evolve(qutip.sigmay(), inverse=False)
    elif key == "p":
        field.qubit.state = qutip.rand_ket(2).ptrace(0)
        field.photon.state = qutip.rand_ket(2).ptrace(0)
        field.energy = qutip.identity(2)
    field.energy = field.energy
def least_eig(r, theta, a_z):
    rho=(1/4)*(qt.tensor(qt.qeye(2), qt.qeye(2)) + qt.tensor(a_z*qt.sigmaz(), qt.qeye(2))\
               - r*np.sin(theta)/np.sqrt(2)*qt.tensor(qt.sigmax(),qt.sigmax())\
                   - r*np.sin(theta)/np.sqrt(2)*qt.tensor(qt.sigmay(),qt.sigmay())\
                       - r*np.cos(theta)*qt.tensor(qt.sigmaz(),qt.sigmaz()))
    eigs = np.linalg.eigvalsh(rho.full())
    return min(eigs)
Ejemplo n.º 5
0
def standard_qubit_pulses_to_rotations(pulse_list: List[Tuple]) \
        -> List[qtp.Qobj]:
    """
    Converts lists of n-tuples of standard PycQED single-qubit pulse names to
    the corresponding rotation matrices on the n-qubit Hilbert space.
    """
    standard_pulses = {
        'I': qtp.qeye(2),
        'X0': qtp.qeye(2),
        'Z0': qtp.qeye(2),
        'X180': qtp.rotation(qtp.sigmax(), np.pi),
        'mX180': qtp.rotation(qtp.sigmax(), -np.pi),
        'Y180': qtp.rotation(qtp.sigmay(), np.pi),
        'mY180': qtp.rotation(qtp.sigmay(), -np.pi),
        'X90': qtp.rotation(qtp.sigmax(), np.pi/2),
        'mX90': qtp.rotation(qtp.sigmax(), -np.pi/2),
        'Y90': qtp.rotation(qtp.sigmay(), np.pi/2),
        'mY90': qtp.rotation(qtp.sigmay(), -np.pi/2),
        'Z90': qtp.rotation(qtp.sigmaz(), np.pi/2),
        'mZ90': qtp.rotation(qtp.sigmaz(), -np.pi/2),
        'Z180': qtp.rotation(qtp.sigmaz(), np.pi),
        'mZ180': qtp.rotation(qtp.sigmaz(), -np.pi),
    }
    rotations = [qtp.tensor(*[standard_pulses[pulse] for pulse in qb_pulses])
                 for qb_pulses in pulse_list]
    for i in range(len(rotations)):
        rotations[i].dims = [[d] for d in rotations[i].shape]
    return rotations
Ejemplo n.º 6
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()
Ejemplo n.º 7
0
def keyboard(event):
    global field
    global qubit_selected
    global evolution
    key = event.key
    if key.isdigit():
        i = int(key)
        if i < field.n_qubits:
            qubit_selected = i
    if key == "a":
        field.evolve(qubit_selected, qutip.sigmax(), inverse=True)
    elif key == "d":
        field.evolve(qubit_selected, qutip.sigmax(), inverse=False)
    elif key == "s":
        field.evolve(qubit_selected, qutip.sigmaz(), inverse=True)
    elif key == "w":
        field.evolve(qubit_selected, qutip.sigmaz(), inverse=False)
    elif key == "z":
        field.evolve(qubit_selected, qutip.sigmay(), inverse=True)
    elif key == "x":
        field.evolve(qubit_selected, qutip.sigmay(), inverse=False)
    elif key == "p":
        for i in range(field.n_qubits):
            field.state = qutip.rand_ket(field.n)
    elif key == "t":
        if evolution:
            evolution = False
        else:
            evolution = True
def heisenberg_1d(param_dict):
    """ A heisenberg model in one dimension.
        H = -J sum si . s_i+1
    """

    L = param_dict['L']
    J = param_dict['J']
    bc = param_dict.get('bc', 'closed')

    coupmax = L - 1 if bc == 'open' else L
    pauli_x = [
        embed([qt.sigmax(), qt.sigmax()], L, [i, (i + 1) % 2])
        for i in range(coupmax)
    ]
    pauli_y = [
        embed([qt.sigmay(), qt.sigmay()], L, [i, (i + 1) % 2])
        for i in range(coupmax)
    ]
    pauli_z = [
        embed([qt.sigmaz(), qt.sigmaz()], L, [i, (i + 1) % 2])
        for i in range(coupmax)
    ]

    if bc == 'closed' and L == 2:
        J = J / 2

    return -J * (1 / 4) * (sum(pauli_x) + sum(pauli_y) + sum(pauli_z))
Ejemplo n.º 9
0
def keyboard(event):
    global A
    global B
    key = event.key
    operator = None
    if key == "a":  #-x for A
        A.apply(qutip.sigmax(), True)
    elif key == "d":  #+x for A
        A.apply(qutip.sigmax(), False)
    elif key == "s":  #-z for A
        A.apply(qutip.sigmaz(), True)
    elif key == "w":  #+z for A
        A.apply(qutip.sigmaz(), False)
    elif key == "z":  #-y for A
        A.apply(qutip.sigmay(), True)
    elif key == "x":  #+y for A
        A.apply(qutip.sigmay(), False)
    elif key == "j":  #-x for B
        B.apply(qutip.sigmax(), True)
    elif key == "l":  #+x for B
        B.apply(qutip.sigmax(), False)
    elif key == "k":  #-z for B
        B.apply(qutip.sigmaz(), True)
    elif key == "i":  #+z for B
        B.apply(qutip.sigmaz(), False)
    elif key == "m":  #-y for B
        B.apply(qutip.sigmay(), True)
    elif key == ",":  #+y for B
        B.apply(qutip.sigmay(), False)
Ejemplo n.º 10
0
    def test_multi_gates(self):
        N = 2
        H_d = tensor([sigmaz()]*2)
        H_c = []

        test = OptPulseProcessor(N)
        test.add_drift(H_d, [0, 1])
        test.add_control(sigmax(), cyclic_permutation=True)
        test.add_control(sigmay(), cyclic_permutation=True)
        test.add_control(tensor([sigmay(), sigmay()]))

        # qubits circuit with 3 gates
        setting_args = {"SNOT": {"num_tslots": 10, "evo_time": 1},
                        "SWAP": {"num_tslots": 30, "evo_time": 3},
                        "CNOT": {"num_tslots": 30, "evo_time": 3}}
        qc = QubitCircuit(N)
        qc.add_gate("SNOT", 0)
        qc.add_gate("SWAP", targets=[0, 1])
        qc.add_gate('CNOT', controls=1, targets=[0])
        test.load_circuit(qc, setting_args=setting_args,
                          merge_gates=False)

        rho0 = rand_ket(4)  # use random generated ket state
        rho0.dims = [[2, 2], [1, 1]]
        U = gate_sequence_product(qc.propagators())
        rho1 = U * rho0
        result = test.run_state(rho0)
        assert_(fidelity(result.states[-1], rho1) > 1-1.0e-6)
Ejemplo n.º 11
0
def keyboard(event):
    global n_qubits
    global qubits
    global qubit_selected
    key = event.key
    qubit = qubits[qubit_selected]
    if key.isdigit():
        i = int(key)
        if i < n_qubits:
            qubit_selected = i
    if key == "a":
        qubits[qubit_selected].evolve(qutip.sigmax(), inverse=True)
    elif key == "d":
        qubits[qubit_selected].evolve(qutip.sigmax(), inverse=False)
    elif key == "s":
        qubits[qubit_selected].evolve(qutip.sigmaz(), inverse=True)
    elif key == "w":
        qubits[qubit_selected].evolve(qutip.sigmaz(), inverse=False)
    elif key == "z":
        qubits[qubit_selected].evolve(qutip.sigmay(), inverse=True)
    elif key == "x":
        qubits[qubit_selected].evolve(qutip.sigmay(), inverse=False)
    elif key == "p":
        qubits[0].state = qutip.rand_herm(2)
        qubits[1].state = qutip.rand_herm(2)
Ejemplo n.º 12
0
    def _set_up_controls(self, num_qubits):
        """
        Generate the Hamiltonians for the spinchain model and save them in the
        attribute `ctrls`.

        Parameters
        ----------
        num_qubits: int
            The number of qubits in the system.
        """
        controls = {}
        # sx_controls
        for m in range(num_qubits):
            controls["sx" + str(m)] = (2 * np.pi * sigmax(), m)
        # sz_controls
        for m in range(num_qubits):
            controls["sz" + str(m)] = (2 * np.pi * sigmaz(), m)
        # sxsy_controls
        num_coupling = self._get_num_coupling()
        if num_coupling == 0:
            return controls
        operator = tensor([sigmax(), sigmax()]) + tensor([sigmay(), sigmay()])
        for n in range(num_coupling):
            controls["g" + str(n)] = (
                2 * np.pi * operator,
                [n, (n + 1) % num_qubits],
            )
        return controls
Ejemplo n.º 13
0
    def compare_evolution(self,
                          H,
                          psi0,
                          tlist,
                          normalize=False,
                          td_args={},
                          tol=5e-5):
        """
        Compare integrated evolution of unitary operator with state evo
        """
        U0 = qeye(2)
        options = Options(store_states=True, normalize_output=normalize)
        out_s = sesolve(H,
                        psi0,
                        tlist,
                        [sigmax(), sigmay(), sigmaz()],
                        options=options,
                        args=td_args)
        xs, ys, zs = out_s.expect[0], out_s.expect[1], out_s.expect[2]

        out_u = sesolve(H, U0, tlist, options=options, args=td_args)
        xu = [expect(sigmax(), U * psi0) for U in out_u.states]
        yu = [expect(sigmay(), U * psi0) for U in out_u.states]
        zu = [expect(sigmaz(), U * psi0) for U in out_u.states]

        if normalize:
            msg_ext = ". (Normalized)"
        else:
            msg_ext = ". (Not normalized)"
        assert_(max(abs(xs - xu)) < tol, msg="expect X not matching" + msg_ext)
        assert_(max(abs(ys - yu)) < tol, msg="expect Y not matching" + msg_ext)
        assert_(max(abs(zs - zu)) < tol, msg="expect Z not matching" + msg_ext)
Ejemplo n.º 14
0
def test_diagHamiltonian2():
    """
    Diagonalization of composite systems
    """

    H1 = scipy.rand() * sigmax() + scipy.rand() * sigmay() +\
        scipy.rand() * sigmaz()
    H2 = scipy.rand() * sigmax() + scipy.rand() * sigmay() +\
        scipy.rand() * sigmaz()

    H = tensor(H1, H2)

    evals, ekets = H.eigenstates()

    for n in range(len(evals)):
        # assert that max(H * ket - e * ket) is small
        assert_equal(amax(
            abs((H * ekets[n] - evals[n] * ekets[n]).full())) < 1e-10, True)

    N1 = 10
    N2 = 2

    a1 = tensor(destroy(N1), qeye(N2))
    a2 = tensor(qeye(N1), destroy(N2))
    H = scipy.rand() * a1.dag() * a1 + scipy.rand() * a2.dag() * a2 + \
        scipy.rand() * (a1 + a1.dag()) * (a2 + a2.dag())
    evals, ekets = H.eigenstates()

    for n in range(len(evals)):
        # assert that max(H * ket - e * ket) is small
        assert_equal(amax(
            abs((H * ekets[n] - evals[n] * ekets[n]).full())) < 1e-10, True)
Ejemplo n.º 15
0
    def check_evolution(self, H, delta, psi0, tlist, analytic_func,
                        U0=None, td_args={}, tol=5e-3):
        """
        Compare integrated evolution with analytical result
        If U0 is not None then operator evo is checked
        Otherwise state evo
        """

        if U0 is None:
            output = sesolve(H, psi0, tlist, [sigmax(), sigmay(), sigmaz()],
                            args=td_args)
            sx, sy, sz = output.expect[0], output.expect[1], output.expect[2]
        else:
            output = sesolve(H, U0, tlist, args=td_args)
            sx = [expect(sigmax(), U*psi0) for U in output.states]
            sy = [expect(sigmay(), U*psi0) for U in output.states]
            sz = [expect(sigmaz(), U*psi0) for U in output.states]

        sx_analytic = np.zeros(np.shape(tlist))
        sy_analytic = np.array([-np.sin(delta*analytic_func(t, td_args))
                                for t in tlist])
        sz_analytic = np.array([np.cos(delta*analytic_func(t, td_args))
                                for t in tlist])

        assert_(max(abs(sx - sx_analytic)) < tol,
                msg="expect X not matching analytic")
        assert_(max(abs(sy - sy_analytic)) < tol,
                msg="expect Y not matching analytic")
        assert_(max(abs(sz - sz_analytic)) < tol,
                msg="expect Z not matching analytic")
def least_ent_eig(r, theta, a_z):
    rho=(1/4)*(qt.tensor(qt.qeye(2), qt.qeye(2)) + qt.tensor(a_z*qt.sigmaz(), qt.qeye(2))\
               - r*np.sin(theta)/np.sqrt(2)*qt.tensor(qt.sigmax(),qt.sigmax())\
                   - r*np.sin(theta)/np.sqrt(2)*qt.tensor(qt.sigmay(),qt.sigmay())\
                       - r*np.cos(theta)*qt.tensor(qt.sigmaz(),qt.sigmaz()))
    rho_pt = qt.partial_transpose(rho, [0, 1])
    eigs = np.linalg.eigvalsh(rho_pt.full())
    return min(eigs)
Ejemplo n.º 17
0
def P1H(B):
    P1muB = 0.0280427 / 2. * B
    A = [0.08133, 0.08133, 0.11403]
    muBH = tensor(
        P1muB[0] * sigmax() + P1muB[1] * sigmay() + P1muB[2] * sigmaz(),
        qeye(3))
    ASIH = tensor(sigmax() / 2., A[0] * jmat(1, 'x')) + tensor(
        sigmay() / 2., A[1] * jmat(1, 'y')) + tensor(sigmaz() / 2.,
                                                     A[2] * jmat(1, 'z'))
    return muBH + ASIH
Ejemplo n.º 18
0
def QubitDM_to_R4(qubitDM):
    eigenvalues, eigenvectors = qubitDM.eigenstates()
    star = np.array([[qutip.expect(qutip.sigmax(), eigenvectors[0])],\
                      [qutip.expect(qutip.sigmay(), eigenvectors[0])],\
                      [qutip.expect(qutip.sigmaz(), eigenvectors[0])],\
                      [qutip.expect(qutip.identity(2), eigenvectors[0])]])
    anti_star = np.array([[qutip.expect(qutip.sigmax(), eigenvectors[1])],\
                          [qutip.expect(qutip.sigmay(), eigenvectors[1])],\
                          [qutip.expect(qutip.sigmaz(), eigenvectors[1])],\
                          [qutip.expect(qutip.identity(2), eigenvectors[1])]])
    return (1. / 2.) * (eigenvalues[0] * star + eigenvalues[1] * anti_star)
Ejemplo n.º 19
0
	def keyboard(self, event):
		key = event.key
		if key == "a":
			self.evolve(qt.sigmax(), inverse=True)
		elif key == "d":
			self.evolve(qt.sigmax(), inverse=False)
		elif key == "s":
			self.evolve(qt.sigmay(), inverse=True)
		elif key == "w":
			self.evolve(qt.sigmay(), inverse=False)
		elif key == "z":
			self.evolve(qt.sigmaz(), inverse=True)
		elif key == "x":
			self.evolve(qt.sigmaz(), inverse=False)
		elif key == "1":
			l, v = qt.sigmax().eigenstates()
			self.state = v[0]
			self.touched = True
		elif key == "2":
			l, v = qt.sigmax().eigenstates()
			self.state = v[1]
			self.touched = True
		elif key == "3":
			l, v = qt.sigmay().eigenstates()
			self.state = v[0]
			self.touched = True
		elif key == "4":
			l, v = qt.sigmay().eigenstates()
			self.state = v[1]
			self.touched = True
		elif key == "5":
			l, v = qt.sigmaz().eigenstates()
			self.state = v[0]
			self.touched = True
		elif key == "6":
			l, v = qt.sigmaz().eigenstates()
			self.state = v[1]
			self.touched = True
		elif key == "q":
			self.done = True
		elif key == "e":
			if self.evolving:
				self.evolving = False
			else:
				self.evolving = True
		elif key == "p":
			self.energy = qt.rand_herm(2)
		elif key == "[":
			self.dt -= 0.01
		elif key == "]":
			self.dt += 0.01
Ejemplo n.º 20
0
 def test_parameterization(self, angle):
     block = VQABlock(qutip.sigmax())
     assert (
         block.get_unitary([angle]) == (-1j * angle * qutip.sigmax()).expm()
     )
     assert block.get_free_parameters_num() == 1
     block = VQABlock(qutip.sigmaz())
     assert (
         block.get_unitary([angle]) == (-1j * angle * qutip.sigmaz()).expm()
     )
     block = VQABlock(qutip.sigmay())
     assert (
         block.get_unitary([angle]) == (-1j * angle * qutip.sigmay()).expm()
     )
Ejemplo n.º 21
0
def test_measurement_statistics_sigmay():
    """ measurement statistics: sigmay applied to basis states. """
    check_measurement_statistics(
        sigmay(),
        basis(2, 0),
        SIGMAY,
        [0.5, 0.5],
    )
    check_measurement_statistics(
        sigmay(),
        ket2dm(basis(2, 0)),
        SIGMAY,
        [0.5, 0.5],
    )
Ejemplo n.º 22
0
def two_level_ham(config, subsystem_list, add_y, no_control):
    # TODO fix 2q version


    bigy1 = Qobj(tensor(sigmay(), identity(2)).full())
    bigy2 = Qobj(tensor(identity(2), sigmay()).full())
    bigx1 = Qobj(tensor(sigmax(), identity(2)).full())
    bigx2 = Qobj(tensor(identity(2), sigmax()).full())
    hamiltonian = {}
    hamiltonian_backend = config.hamiltonian
    hamiltonian_dict = HamiltonianModel.from_dict(
        hamiltonian_backend, subsystem_list=subsystem_list)
    hamiltonian = {'H_c': {}, 'H_d': 0}
    for i, control_field in enumerate(hamiltonian_dict._system):
        matrix = (control_field[0])
        prefactor, control = prefactor_parser(control_field[1], hamiltonian_dict._variables)
        if prefactor == 0:
            continue
        if control:
            # prefactor = prefactor * 2
            if 'D' in control:
                # print("Double check that sigx2 and  sigy2 are right")
                if len(subsystem_list) == 1:
                    hamiltonian['H_c'][control] = sigmax() * prefactor
                if add_y:
                    if len(subsystem_list) == 1:
                        hamiltonian['H_c'][control + 'y'] = sigmay() * prefactor
                    elif len(subsystem_list) == 2:
                        if control == 'D0':
                            hamiltonian['H_c'][control] = Qobj(bigx1 * prefactor)
                            hamiltonian['H_c'][control + 'y'] = Qobj(bigy1 * prefactor)
                        elif control == 'D1':
                            hamiltonian['H_c'][control] = Qobj(bigx2 * prefactor)
                            hamiltonian['H_c'][control + 'y'] = Qobj(bigy2 * prefactor)
                        else:
                            raise NotImplementedError("Only q0 and q1 rn")
                    else:
                        raise NotImplementedError("Only 1-2q operations supported")
                else:
                    raise NotImplementedError("need to use y right now")
            elif no_control:
                print('not using control channels, skippping...')
            else:
                raise NotImplementedError("No use for control channels currently")
    if len(subsystem_list) == 1:
        hamiltonian['H_d'] = identity(2) * 0
    elif len(subsystem_list) == 2:
        hamiltonian['H_d'] = identity(4) * 0
    return hamiltonian
Ejemplo n.º 23
0
 def test_2q_op_simple(self):
     """ Test a smple 2-qubit operator. """
     H = (
         tensor(qeye(2), qeye(2))
         + 2 * tensor(sigmax(), sigmay())
         + 3 * tensor(sigmay(), sigmaz())
         + 4 * tensor(qeye(2), sigmaz())
     )
     coeffs = decompose(H)
     assert coeffs == {
         "II": 1.0,
         "XY": 2.0,
         "YZ": 3.0,
         "IZ": 4.0,
     }
Ejemplo n.º 24
0
def test_eigenbasis_transformation_makes_diagonal_operator():
    """Check diagonalization via eigenbasis transformation."""
    cx, cy, cz = np.random.random_sample((3,))
    H = cx*qutip.sigmax() + cy*qutip.sigmay() + cz*qutip.sigmaz()
    _, ekets = H.eigenstates()
    Heb = H.transform(ekets).tidyup()  # Heb should be diagonal
    assert abs(Heb.full() - np.diag(Heb.full().diagonal())).max() < 1e-6
Ejemplo n.º 25
0
def pauli():
    '''Define pauli spin matrices'''
    identity = qutip.qeye(2)
    sx = qutip.sigmax()/2
    sy = qutip.sigmay()/2
    sz = qutip.sigmaz()/2
    return identity, sx, sy, sz
Ejemplo n.º 26
0
def testCOPSwithAOPS():
    """
    brmesolve: c_ops with a_ops
    """

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

    for idx, e in enumerate(e_ops):
        diff = abs(res_me.expect[idx] - res_brme.expect[idx]).max()
        assert_(diff < 1e-2)
Ejemplo n.º 27
0
    def __init__(self, N_field_levels, coupling=None, N_qubits=1):

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

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

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

        # 1 atom 1 cavity operators
        self.jc_a = qt.tensor(self.a_bare, self.idqubit)
        self.jc_sm = qt.tensor(self.idcavity, self.sm_bare)
        self.jc_sx = qt.tensor(self.idcavity, self.sx_bare)
        self.jc_sy = qt.tensor(self.idcavity, self.sy_bare)
        self.jc_sz = qt.tensor(self.idcavity, self.sz_bare)
Ejemplo n.º 28
0
    def test_02_2_qft_bounds(self):
        """
        control.pulseoptim: QFT gate with linear initial pulses (bounds)
        assert that amplitudes remain in bounds
        """
        Sx = sigmax()
        Sy = sigmay()
        Sz = sigmaz()
        Si = 0.5 * identity(2)

        H_d = 0.5 * (tensor(Sx, Sx) + tensor(Sy, Sy) + tensor(Sz, Sz))
        H_c = [tensor(Sx, Si), tensor(Sy, Si), tensor(Si, Sx), tensor(Si, Sy)]
        U_0 = identity(4)
        # Target for the gate evolution - Quantum Fourier Transform gate
        U_targ = qft.qft(2)

        n_ts = 10
        evo_time = 10

        result = cpo.optimize_pulse_unitary(H_d,
                                            H_c,
                                            U_0,
                                            U_targ,
                                            n_ts,
                                            evo_time,
                                            fid_err_targ=1e-9,
                                            amp_lbound=-1.0,
                                            amp_ubound=1.0,
                                            init_pulse_type='LIN',
                                            gen_stats=True)
        assert_((result.final_amps >= -1.0).all()
                and (result.final_amps <= 1.0).all(),
                msg="Amplitude bounds exceeded for QFT")
Ejemplo n.º 29
0
    def test_02_2_qft_bounds(self):
        """
        control.pulseoptim: QFT gate with linear initial pulses (bounds)
        assert that amplitudes remain in bounds
        """
        Sx = sigmax()
        Sy = sigmay()
        Sz = sigmaz()
        Si = 0.5*identity(2)

        H_d = 0.5*(tensor(Sx, Sx) + tensor(Sy, Sy) + tensor(Sz, Sz))
        H_c = [tensor(Sx, Si), tensor(Sy, Si), tensor(Si, Sx), tensor(Si, Sy)]
        U_0 = identity(4)
        # Target for the gate evolution - Quantum Fourier Transform gate
        U_targ = qft.qft(2)

        n_ts = 10
        evo_time = 10

        result = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ,
                        n_ts, evo_time,
                        fid_err_targ=1e-9,
                        amp_lbound=-1.0, amp_ubound=1.0,
                        init_pulse_type='LIN',
                        gen_stats=True)
        assert_((result.final_amps >= -1.0).all() and
                    (result.final_amps <= 1.0).all(),
                    msg="Amplitude bounds exceeded for QFT")
Ejemplo n.º 30
0
def _qubit_integrate(tlist, psi0, epsilon, delta, g1, g2, solver):

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

    c_op_list = []

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

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

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

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

    return output.expect[0], output.expect[1], output.expect[2]
Ejemplo n.º 31
0
def _qubit_integrate(tlist, psi0, epsilon, delta, g1, g2, solver):

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

    c_op_list = []

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

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

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

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

    return output.expect[0], output.expect[1], output.expect[2]
Ejemplo n.º 32
0
 def U_rot(self, theta, ion_index=[1, 1], phi=0):
     # ion_index=[i1,i2], go gate on ion ii if ii==1, else, do identity
     if ion_index[0] == 1:
         op_1 = (cos(theta / 2) * qeye(self.nq)) - (
             1j * sin(theta / 2) *
             (cos(phi) * sigmax() + sin(phi) * sigmay()))
     else:
         op_1 = qeye(self.nq)
     if ion_index[1] == 1:
         op_2 = (cos(theta / 2) * qeye(self.nq)) - (
             1j * sin(theta / 2) *
             (cos(phi) * sigmax() + sin(phi) * sigmay()))
     else:
         op_2 = qeye(self.nq)
     rot = tensor(op_1, op_2, qeye(self.nHO))
     return rot
def pauli():
	'''Return the Pauli spin matrices for S=1/2'''
	identity = qutip.qeye(2)
	sx = qutip.sigmax()/2
	sy = qutip.sigmay()/2
	sz = qutip.sigmaz()/2
	return identity, sx, sy, sz
Ejemplo n.º 34
0
def rand_scrambler(q, klocal=3):
    #if q == 2:
    #    Q = qt.rand_herm(4)
    #    Q.dims = [[2,2], [2,2]]
    #    return Q
    X = [
        qt.tensor(
            *[qt.sigmax() if i == j else qt.identity(2) for j in range(q)])
        for i in range(q)
    ]
    Y = [
        qt.tensor(
            *[qt.sigmay() if i == j else qt.identity(2) for j in range(q)])
        for i in range(q)
    ]
    Z = [
        qt.tensor(
            *[qt.sigmaz() if i == j else qt.identity(2) for j in range(q)])
        for i in range(q)
    ]
    return sum([reduce(lambda x, y: x*y,\
                    [np.random.randn(1)[0]*X[i] +\
                     np.random.randn(1)[0]*Y[i] +\
                     np.random.randn(1)[0]*Z[i]\
                             for i in p])
                                  for p in permutations(list(range(q)), klocal)])
    def construct_hamiltonian(self, number_of_spins, alpha):
        """
following example
http://qutip.googlecode.com/svn/doc/2.0.0/html/examples/me/ex-24.html
returns H0 - hamiltonian without the B field
and y_list - list of sigma_y operators
"""
        N = number_of_spins
        si = qeye(2)
        sx = sigmax()
        sy = sigmay()
        # constructing a list of operators sx_list and sy_list where
        # the operator sx_list[i] applies sigma_x on the ith particle and
        # identity to the rest
        sx_list = []
        sy_list = []
        for n in range(N):
            op_list = []
            for m in range(N):
                op_list.append(si)
            op_list[n] = sx
            sx_list.append(tensor(op_list))
            op_list[n] = sy
            sy_list.append(tensor(op_list))
        # construct the hamiltonian
        H0 = 0
        # ising coupling term, time independent
        for i in range(N):
            for j in range(N):
                if i < j:
                    H0 -= abs(i - j) ** -alpha * sx_list[i] * sx_list[j]
        H1 = 0
        for i in range(N):
            H1 -= sy_list[i]
        return H0, H1
def n_sigmay(n_qubits, qubit_pos):
    """
    This method generates a tensor(Qobj) wich perform a single-qubit sigmay operation
    on a state of n-qubits

    Parameters
    ----------
    n_qubits : int
        number of qubits the states is composed of.
    qubit_pos : int
        qubit on which the sigmax operator acts (position starts at '0').

    Raises
    ------
    ValueError
        if number of qubits is less than 2
    ValueError
        if qubit position is < 0 or > n_qubits-1

    Returns
    -------
    n_sigmaz: tensor (Qobj)
        a tensor that apply sigmay on the nth-qubit of a n-qubits state.

    """
    if n_qubits < 1:
        raise ValueError('number of vertices must be > 0, but is {}'.format(n_qubits))
    if qubit_pos < 0 or qubit_pos > n_qubits-1:
        raise ValueError('qubit position must be > 0 or < n_qubits-1, but is {}'.format(qubit_pos))
    list_n_sigmay = []
    for i in range(n_qubits):
        list_n_sigmay.append(qu.tensor([qu.qeye(2)]*i+[qu.sigmay()]+[qu.qeye(2)]*(n_qubits-i-1)))
    return list_n_sigmay[qubit_pos]
def pauli_product(*args):
    """
    Return sympy.Matrix object represing product of Pauli matrices.

    Examples
    --------
    >>> pauli_product(1, 1)
    Matrix([[0, 0, 0, 1],
            [0, 0, 1, 0],
            [0, 1, 0, 0],
            [1, 0, 0, 0]])
    """
    for arg in args:
        try:
            if not 0 <= arg <= 3:
                raise ValueError('Each argument must be between 0 and 3.')
        except TypeError:
            raise ValueError('The inputs must be integers.')
    n_qubits = len(args)
    sigmas = [qutip.qeye(2), qutip.sigmax(), qutip.sigmay(), qutip.sigmaz()]
    output_matrix = [None] * n_qubits
    for idx, arg in enumerate(args):
        output_matrix[idx] = sigmas[arg]
    output_matrix = qutip.tensor(*output_matrix).data.toarray()
    return sympy.Matrix(output_matrix)
 def construct_hamiltonian(self, number_of_spins, alpha, B):
     '''
     following example
     http://qutip.googlecode.com/svn/doc/2.0.0/html/examples/me/ex-24.html
     '''
     N = number_of_spins
     si = qeye(2)
     sx = sigmax()
     sy = sigmay()
     #constructing a list of operators sx_list and sy_list where
     #the operator sx_list[i] applies sigma_x on the ith particle and 
     #identity to the rest
     sx_list = []
     sy_list = []
     for n in range(N):
         op_list = []
         for m in range(N):
             op_list.append(si)
         op_list[n] = sx
         sx_list.append(tensor(op_list))
         op_list[n] = sy
         sy_list.append(tensor(op_list))
     #construct the hamiltonian
     H = 0
     #magnetic field term, hamiltonian is in units of J0
     for i in range(N):
         H-= B * sy_list[i]
     #ising coupling term
     for i in range(N):
         for j in range(N):
             if i < j:
                 H+= abs(i - j)**-alpha * sx_list[i] * sx_list[j]
     return H
 def setUp(self):
     TestRotatingFrame.setUp(self)
     self.times_to_calc = np.array([0, np.pi/2])
     self.expected_result =np.array(
         np.cos(self.frequency * self.times_to_calc) * q.qeye(2) + \
          1j* np.sin(self.frequency * self.times_to_calc) * q.sigmay()
     )
Ejemplo n.º 40
0
def test_Transformation6():
    "Check diagonalization via eigenbasis transformation"

    cx, cy, cz = np.random.rand(), np.random.rand(), np.random.rand()
    H = cx * sigmax() + cy * sigmay() + cz * sigmaz()
    evals, evecs = H.eigenstates()
    Heb = H.transform(evecs).tidyup()  # Heb should be diagonal
    assert_(abs(Heb.full() - np.diag(Heb.full().diagonal())).max() < 1e-6)
Ejemplo n.º 41
0
def test_Transformation1():
    "Transform 2-level to eigenbasis and back"
    H1 = scipy.rand() * sigmax() + scipy.rand() * sigmay() + \
        scipy.rand() * sigmaz()
    evals, ekets = H1.eigenstates()
    Heb = H1.transform(ekets)        # eigenbasis (should be diagonal)
    H2 = Heb.transform(ekets, True)  # back to original basis
    assert_equal((H1 - H2).norm() < 1e-6, True)
Ejemplo n.º 42
0
def Hfred(x,N) : # A possible Hamiltonian for the Fredkin gate
    k = 0
    H = 0
    sx = qt.sigmax()/2
    sy = qt.sigmay()/2
    sz = qt.sigmaz()/2
    Id = qt.qeye(2)

    for q in [sx, sy, sz] :
        temp = 0
        OpChain = [Id]*N
        OpChain[2] = q
        OpChain[1] = q
        temp += x[k]*qt.tensor(OpChain)
        H += temp 
    k+=1        

    for q in [sx,sz]:
        
        temp = 0
        OpChain = [Id]*N
        OpChain[2] = q
        OpChain[0] = q
        temp += x[k]*qt.tensor(OpChain)
    
        OpChain = [Id]*N
        OpChain[1] = q
        OpChain[0] = q
        temp += x[k]*qt.tensor(OpChain)
        k += 1
        H += temp 
    
    for q in [1,2]:
        temp = 0
        OpChain = [Id]*N
        OpChain[q] = sx
        OpChain[3] = sx
        temp += x[k]*qt.tensor(OpChain)
        H += temp 
    k+=1        

    temp = 0
    OpChain = [Id]*N
    OpChain[0] = sz
    temp += x[k]*qt.tensor(OpChain)
    H += temp 
    k += 1
    
    temp = 0
    OpChain = [Id]*N
    OpChain[3] = sx
    temp += x[k]*qt.tensor(OpChain)#last one

    H += temp 

    
    return H
Ejemplo n.º 43
0
    def local_hamiltonian(self):
        field_vector = self.parent_field.field_vector.values()
        pauli_basis = [qt.sigmax(), qt.sigmay(), qt.sigmaz()]

        b_field = sum(
            [field_vector[i] * pauli_basis[i]
             for i in xrange(0, len(field_vector))
             ]
        )
        return self.gyromagnetic_ratio * b_field * const.HBAR / 2
Ejemplo n.º 44
0
def test_qpt_snot():
    "quantum process tomography for snot gate"

    U_psi = snot()
    U_rho = spre(U_psi) * spost(U_psi.dag())
    N = 1
    op_basis = [[qeye(2), sigmax(), 1j * sigmay(), sigmaz()] for i in range(N)]
    # op_label = [["i", "x", "y", "z"] for i in range(N)]
    chi1 = qpt(U_rho, op_basis)

    chi2 = np.zeros((2 ** (2 * N), 2 ** (2 * N)), dtype=complex)
    chi2[1, 1] = chi2[1, 3] = chi2[3, 1] = chi2[3, 3] = 0.5

    assert_(norm(chi2 - chi1) < 1e-8)
Ejemplo n.º 45
0
def test_diagHamiltonian1():
    """
    Diagonalization of random two-level system
    """

    H = scipy.rand() * sigmax() + scipy.rand() * sigmay() +\
        scipy.rand() * sigmaz()

    evals, ekets = H.eigenstates()

    for n in range(len(evals)):
        # assert that max(H * ket - e * ket) is small
        assert_equal(amax(
            abs((H * ekets[n] - evals[n] * ekets[n]).full())) < 1e-10, True)
Ejemplo n.º 46
0
 def as_qobj(self):
     """
     Returns a representation of the given Pauli operator as a QuTiP
     Qobj instance.
     """
     if qt is None:
         raise RuntimeError("Requires QuTiP.")
     if self == Pauli.I:
         return qt.qeye(2)
     elif self == Pauli.X:
         return qt.sigmax()
     elif self == Pauli.Y:
         return qt.sigmay()
     else:
         return qt.sigmaz()
Ejemplo n.º 47
0
def ptracetest():
    gamma = 1.
    neq = 2
    psi0 = qt.basis(neq,neq-1)
    psi0 = qt.tensor(psi0,psi0)
    H = qt.tensor(qt.sigmax(),qt.sigmay())
    c1 = np.sqrt(gamma)*qt.sigmax()
    e1 = np.sqrt(gamma)*qt.sigmaz()
    c_ops = [qt.tensor(c1,c1)]
    e_ops = [qt.tensor(e1,e1),qt.tensor(c1,c1)]
    #e_ops = []
    tlist = np.linspace(0,10,100)
    ntraj = 2000
    ptrace_sel = [0]
    sol_f90 = mcf90.mcsolve_f90(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,
            ptrace_sel=ptrace_sel,calc_entropy=True)
Ejemplo n.º 48
0
    def qubit_integrate(self, tlist, psi0, epsilon, delta, g1, g2):

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

        c_op_list = []

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

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

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

        return expt_list[0], expt_list[1], expt_list[2]
Ejemplo n.º 49
0
    def testTLS(self):
        "brmesolve: qubit"

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

        for idx, e in enumerate(e_ops):
            diff = abs(res_me.expect[idx] - res_brme.expect[idx]).max()
            assert_(diff < 1e-2)
 def get_reduced_dms(self, states, spin):
     """
     takes a number of states and returns a list of bloch vector of the 0th spin coordinates for each
     """
     sz = sigmaz()
     sy = sigmay()
     sx = sigmax()
     zs = []
     ys = []
     xs = []
     for state in states:
         ptrace = state.ptrace(spin)
         zval = abs(expect(sz, ptrace))
         yval = abs(expect(sy, ptrace))
         xval = abs(expect(sx, ptrace))
         zs.append(zval)
         ys.append(yval)
         xs.append(xval)
     return xs, ys, zs
Ejemplo n.º 51
0
def testCOPS():
    """
    brmesolve: c_ops alone
    """

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

    for idx, e in enumerate(e_ops):
        diff = abs(res_me.expect[idx] - res_brme.expect[idx]).max()
        assert_(diff < 1e-2)
def get_dms(states):
    '''
    takes a number of states and returns a list of bloch vector coordinates for each
    '''
    si = qeye(2)
    sz = sigmaz()
    sy = sigmay()
    sx = sigmax()
    zs = []
    ys = []
    xs = []
    for state in states:
        ptrace = state.ptrace(0)
        zval = expect(sz, ptrace )
        yval = expect(sy, ptrace )
        xval = expect(sx, ptrace )
        zs.append(zval)
        ys.append(yval)
        xs.append(xval)
    return xs,ys,zs
Ejemplo n.º 53
0
    def test_02_1_qft(self):
        """
        control.pulseoptim: QFT gate with linear initial pulses
        assert that goal is achieved and fidelity error is below threshold
        """
        Sx = sigmax()
        Sy = sigmay()
        Sz = sigmaz()
        Si = 0.5*identity(2)

        H_d = 0.5*(tensor(Sx, Sx) + tensor(Sy, Sy) + tensor(Sz, Sz))
        H_c = [tensor(Sx, Si), tensor(Sy, Si), tensor(Si, Sx), tensor(Si, Sy)]
        U_0 = identity(4)
        # Target for the gate evolution - Quantum Fourier Transform gate
        U_targ = qft.qft(2)

        n_ts = 10
        evo_time = 10

        result = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ,
                        n_ts, evo_time,
                        fid_err_targ=1e-9,
                        init_pulse_type='LIN',
                        gen_stats=True)

        assert_(result.goal_achieved, msg="QFT goal not achieved. "
                    "Terminated due to: {}, with infidelity: {}".format(
                    result.termination_reason, result.fid_err))
        assert_almost_equal(result.fid_err, 0.0, decimal=7,
                            err_msg="QFT infidelity too high")

        # check bounds
        result2 = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ,
                        n_ts, evo_time,
                        fid_err_targ=1e-9,
                        amp_lbound=-1.0, amp_ubound=1.0,
                        init_pulse_type='LIN',
                        gen_stats=True)
        assert_((result2.final_amps >= -1.0).all() and
                    (result2.final_amps <= 1.0).all(),
                    msg="Amplitude bounds exceeded for QFT")
Ejemplo n.º 54
0
def excitation(args):
    H0 = args['parity']*args['vFermi']*(args['kpoint'][0]*qp.sigmax() + args['kpoint'][1]*qp.sigmay())
    H1 = qp.sigmax()
    H2 = qp.sigmay()
    Hamiltonian = [H0,[H1,HCoeff]]
    states = H0.eigenstates()  
    psi0 = states[1][0]
    psi1 = states[1][1]
    import hashlib
    label = hashlib.sha224(str(args)).hexdigest()
    import os
    if os.path.exists('Data/'+label+'.qu'):
      result = qp.qload('Data/'+label)
      print 'Loading'
    else:
      result = qp.mesolve(Hamiltonian, psi0, args['times'], [], [], args=args)
      print 'Recalculate'
      qp.qsave(result, 'Data/'+   label)
    proj0 =  np.array([(state.dag()*psi0).norm() for state in result.states])
    proj1 =  np.array([(state.dag()*psi1).norm() for state in result.states])
    return result, proj0, proj1
Ejemplo n.º 55
0
    def get_rotation_operator(self, time):
        r"""
        Return the rotation matrix to move from the Lab frame to this
        rotating frame. In :math:`SU(2)`, this matrix is given as

        .. math::
            \left(\begin{array}{c c}
                \cos(\Omega t) & \sin(\Omega t) \\
                -\sin(\Omega t) & \cos(\Omega t)
            \end{array}\right)

        Or

        .. math::
            \cos(\Omega t) \mathbb{I} + i \sin(\Omega t)\sigma_y

        :param array-like time: The times for which the rotation operator is
            to be calculated
        :return:
        """

        return np.cos(self.frequency * time) * q.qeye(2) + \
            1j * np.sin(self.frequency * time) * q.sigmay()
#QuTiP
from qutip import Qobj, identity, sigmax, sigmay, sigmaz, tensor
import qutip.logging_utils as logging
logger = logging.get_logger()
#QuTiP control modules
import qutip.control.pulseoptim as cpo
import qutip.control.pulsegen as pulsegen
from qutip.qip.algorithms import qft

example_name = 'QFT-dump'
log_level=logging.INFO
# ****************************************************************
# Define the physics of the problem
Sx = sigmax()
Sy = sigmay()
Sz = sigmaz()
Si = 0.5*identity(2)

# Drift Hamiltonian
H_d = 0.5*(tensor(Sx, Sx) + tensor(Sy, Sy) + tensor(Sz, Sz))
print("drift {}".format(H_d))
# The (four) control Hamiltonians
H_c = [tensor(Sx, Si), tensor(Sy, Si), tensor(Si, Sx), tensor(Si, Sy)]
j = 0
for c in H_c:
    j += 1
    print("ctrl {} \n{}".format(j, c))

n_ctrls = len(H_c)
# start point for the gate evolution
Ejemplo n.º 57
0
   102,   131,   119,   148, # counts for XZ for outcomes (+1, +1), (+1, -1), (-1, +1), (-1, -1)
     7,   252,   240,     1, # counts for YX for outcomes (+1, +1), (+1, -1), (-1, +1), (-1, -1)
   125,   135,   127,   113, # counts for YY for outcomes (+1, +1), (+1, -1), (-1, +1), (-1, -1)
   140,   124,   118,   118, # counts for YZ for outcomes (+1, +1), (+1, -1), (-1, +1), (-1, -1)
   122,   119,   135,   124, # counts for ZX for outcomes (+1, +1), (+1, -1), (-1, +1), (-1, -1)
   126,   123,   134,   117, # counts for ZY for outcomes (+1, +1), (+1, -1), (-1, +1), (-1, -1)
     9,   233,   253,     5, # counts for ZZ for outcomes (+1, +1), (+1, -1), (-1, +1), (-1, -1)
]);


# In[4]:

# An entanglement witness which is appropriate for our target state, as a qutip.Qobj
EntglWitness = (- qutip.qeye(4)
    # how do you "collapse systems together" with qutip?? we could do this with np.kron() also...
    - qutip.Qobj(qutip.tensor(qutip.sigmax(),qutip.sigmay()).data,dims=[[4],[4]])
    + qutip.Qobj(qutip.tensor(qutip.sigmay(),qutip.sigmax()).data,dims=[[4],[4]])
    - qutip.Qobj(qutip.tensor(qutip.sigmaz(),qutip.sigmaz()).data,dims=[[4],[4]]) )
display(EntglWitness)


# In[5]:

# Value for rho_target_Bell maximally entangled state: +2
display(qutip.expect(EntglWitness, rho_target_Bell))


# In[6]:

# but you can show that for any separable state this value is <= 0. For example:
display(qutip.expect(EntglWitness, qutip.qeye(4)/4))
Ejemplo n.º 58
0
def P1H(B):
    P1muB=0.0280427/2.*B
    A=[0.08133, 0.08133, 0.11403]
    muBH=tensor(P1muB[0]*sigmax()+P1muB[1]*sigmay()+P1muB[2]*sigmaz(),qeye(3))
    ASIH=tensor(sigmax()/2.,A[0]*jmat(1,'x'))+tensor(sigmay()/2.,A[1]*jmat(1,'y'))+tensor(sigmaz()/2.,A[2]*jmat(1,'z'))
    return muBH+ASIH
Ejemplo n.º 59
0
    def test_unitary(self):
        """
        Optimise pulse for Hadamard and QFT gate with linear initial pulses
        assert that goal is achieved and fidelity error is below threshold
        """
        # Hadamard
        H_d = sigmaz()
        H_c = [sigmax()]
        U_0 = identity(2)
        U_targ = hadamard_transform(1)

        n_ts = 10
        evo_time = 6
        
        # Run the optimisation
        result = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ, 
                        n_ts, evo_time, 
                        fid_err_targ=1e-10, 
                        init_pulse_type='LIN', 
                        gen_stats=True)
        assert_(result.goal_achieved, msg="Hadamard goal not achieved")
        assert_almost_equal(result.fid_err, 0.0, decimal=10, 
                            err_msg="Hadamard infidelity too high")
                            
        #Try without stats
        result = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ, 
                        n_ts, evo_time, 
                        fid_err_targ=1e-10, 
                        init_pulse_type='LIN', 
                        gen_stats=False)
        assert_(result.goal_achieved, msg="Hadamard goal not achieved "
                                            "(no stats)")
                                            
        #Try with Qobj propagation
        result = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ, 
                        n_ts, evo_time, 
                        fid_err_targ=1e-10, 
                        init_pulse_type='LIN', 
                        dyn_params={'oper_dtype':Qobj},
                        gen_stats=True)
        assert_(result.goal_achieved, msg="Hadamard goal not achieved "
                                            "(Qobj propagation)")
        
        # Check same result is achieved using the create objects method
        optim = cpo.create_pulse_optimizer(H_d, H_c, U_0, U_targ, 
                        n_ts, evo_time, 
                        fid_err_targ=1e-10, 
                        dyn_type='UNIT', 
                        init_pulse_type='LIN', 
                        gen_stats=True)
        dyn = optim.dynamics

        init_amps = optim.pulse_generator.gen_pulse().reshape([-1, 1])
        dyn.initialize_controls(init_amps)

        # Check the exact gradient
        func = optim.fid_err_func_wrapper
        grad = optim.fid_err_grad_wrapper
        x0 = dyn.ctrl_amps.flatten()
        grad_diff = check_grad(func, grad, x0)
        assert_almost_equal(grad_diff, 0.0, decimal=7,
                            err_msg="Unitary gradient outside tolerance")

        result2 = optim.run_optimization()
        assert_almost_equal(result.fid_err, result2.fid_err, decimal=10, 
                            err_msg="Direct and indirect methods produce "
                                    "different results for Hadamard")
                                    
        # QFT
        Sx = sigmax()
        Sy = sigmay()
        Sz = sigmaz()
        Si = 0.5*identity(2)
        
        H_d = 0.5*(tensor(Sx, Sx) + tensor(Sy, Sy) + tensor(Sz, Sz))
        H_c = [tensor(Sx, Si), tensor(Sy, Si), tensor(Si, Sx), tensor(Si, Sy)]
        #n_ctrls = len(H_c)
        U_0 = identity(4)
        # Target for the gate evolution - Quantum Fourier Transform gate
        U_targ = qft.qft(2)
        result = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ, 
                        n_ts, evo_time, 
                        fid_err_targ=1e-9, 
                        init_pulse_type='LIN', 
                        gen_stats=True)
                        
        assert_(result.goal_achieved, msg="QFT goal not achieved")
        assert_almost_equal(result.fid_err, 0.0, decimal=7, 
                            err_msg="QFT infidelity too high")
                            
        # check bounds
        result2 = cpo.optimize_pulse_unitary(H_d, H_c, U_0, U_targ, 
                        n_ts, evo_time, 
                        fid_err_targ=1e-9, 
                        amp_lbound=-1.0, amp_ubound=1.0,
                        init_pulse_type='LIN', 
                        gen_stats=True)
        assert_((result2.final_amps >= -1.0).all() and 
                    (result2.final_amps <= 1.0).all(), 
                    msg="Amplitude bounds exceeded for QFT")
Ejemplo n.º 60
0
def P1_transition_weights(ekets):
    weights=[]
    for ii in range(len(ekets)):
        for jj in range (ii+1,len(ekets)):
            weights.append([ii,jj,abs((ekets[ii].dag()*tensor(sigmax(),qeye(3))*ekets[jj]).tr())+abs((ekets[ii].dag()*tensor(sigmay(),qeye(3))*ekets[jj]).tr()) +abs((ekets[ii].dag()*tensor(sigmaz(),qeye(3))*ekets[jj]).tr())])
    return weights