def TestBasicPulse(): """ 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).ops[0].qobj, tensor(identity(2), sigmaz())) 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, 2 * sigmay()) pulse1.qobj = ham pulse1.targets = 3 assert_allclose(pulse1.targets, 3) pulse1.targets = 1 assert_allclose(pulse1.get_ideal_qobj(2), tensor(identity(2), sigmaz()))
def TestPulseConstructor(): """ Test for creating empty Pulse, Pulse with constant coefficients etc. """ coeff = np.array([0.1, 0.2, 0.3, 0.4]) tlist = np.array([0., 1., 2., 3.]) ham = sigmaz() # Special ways of initializing pulse pulse2 = Pulse(sigmax(), 0, tlist, True) assert_allclose(pulse2.get_ideal_qobjevo(2).ops[0].qobj, tensor(sigmax(), identity(2))) pulse3 = Pulse(sigmay(), 0) assert_allclose(pulse3.get_ideal_qobjevo(2).cte.norm(), 0.) pulse4 = Pulse(None, None) # Dummy empty ham assert_allclose(pulse4.get_ideal_qobjevo(2).cte.norm(), 0.) tlist_noise = np.array([1., 2.5, 3.]) coeff_noise = np.array([0.5, 0.1, 0.5]) tlist_noise2 = np.array([0.5, 2, 3.]) coeff_noise2 = np.array([0.1, 0.2, 0.3]) # Pulse with different dims random_qobj = Qobj(np.random.random((3, 3))) pulse5 = Pulse(sigmaz(), 1, tlist, True) pulse5.add_coherent_noise(sigmay(), 1, tlist_noise, coeff_noise) pulse5.add_lindblad_noise( random_qobj, 0, tlist=tlist_noise2, coeff=coeff_noise2) qu, c_ops = pulse5.get_noisy_qobjevo(dims=[3, 2]) assert_allclose(qu.ops[0].qobj, tensor([identity(3), sigmaz()])) assert_allclose(qu.ops[1].qobj, tensor([identity(3), sigmay()])) assert_allclose(c_ops[0].ops[0].qobj, tensor([random_qobj, identity(2)]))
def TestPlot(self): """ Test for plotting functions """ try: import matplotlib.pyplot as plt except Exception: return True # step_func tlist = np.linspace(0., 2*np.pi, 20) processor = Processor(N=1, spline_kind="step_func") processor.add_control(sigmaz()) processor.pulses[0].tlist = tlist processor.pulses[0].coeff = np.array([np.sin(t) for t in tlist]) processor.plot_pulses() plt.clf() # cubic spline tlist = np.linspace(0., 2*np.pi, 20) processor = Processor(N=1, spline_kind="cubic") processor.add_control(sigmaz()) processor.pulses[0].tlist = tlist processor.pulses[0].coeff = np.array([np.sin(t) for t in tlist]) processor.plot_pulses() plt.clf()
def test_save_read(self): """ Test for saving and reading a pulse matrix """ proc = Processor(N=2) proc.add_ctrl(sigmaz(), cyclic_permutation=True) proc1 = Processor(N=2) proc1.add_ctrl(sigmaz(), cyclic_permutation=True) proc2 = Processor(N=2) proc2.add_ctrl(sigmaz(), cyclic_permutation=True) tlist = [0., 0.1, 0.2, 0.3, 0.4, 0.5] amp1 = np.arange(0, 5, 1) amp2 = np.arange(5, 0, -1) proc.tlist = tlist proc.coeffs = np.array([amp1, amp2]) proc.save_coeff("qutip_test_CircuitProcessor.txt") proc1.read_coeff("qutip_test_CircuitProcessor.txt") os.remove("qutip_test_CircuitProcessor.txt") assert_allclose(proc1.coeffs, proc.coeffs) assert_allclose(proc1.tlist, proc.tlist) proc.save_coeff("qutip_test_CircuitProcessor.txt", inctime=False) proc2.read_coeff("qutip_test_CircuitProcessor.txt", inctime=False) os.remove("qutip_test_CircuitProcessor.txt") assert_allclose(proc2.coeffs, proc.coeffs) assert_(proc2.tlist is None)
def add_states(self, state, kind='vector', alpha=1.0): """Add a state vector Qobj to Bloch sphere. Parameters ---------- state : qobj Input state vector. kind : str {'vector','point'} Type of object to plot. alpha : float, default=1. Transparency value for the vectors. Values between 0 and 1. """ if isinstance(state, Qobj): state = [state] for st in state: if kind == 'vector': vec = [ expect(sigmax(), st), expect(sigmay(), st), expect(sigmaz(), st) ] self.add_vectors(vec, alpha=alpha) elif kind == 'point': pnt = [ expect(sigmax(), st), expect(sigmay(), st), expect(sigmaz(), st) ] self.add_points(pnt, alpha=alpha)
def TestPlot(self): try: import matplotlib.pyplot as plt except: return True # step_func tlist = np.linspace(0., 2 * np.pi, 20) processor = Processor(N=1, spline_kind="step_func") processor.add_ctrl(sigmaz()) processor.tlist = tlist processor.coeffs = np.array([[np.sin(t) for t in tlist]]) processor.plot_pulses(noisy=False) plt.clf() # cubic spline tlist = np.linspace(0., 2 * np.pi, 20) processor = Processor(N=1, spline_kind="cubic") processor.add_ctrl(sigmaz()) processor.tlist = tlist processor.coeffs = np.array([[np.sin(t) for t in tlist]]) processor.plot_pulses(noisy=False) plt.clf() # noisy processor = Processor(N=1) processor.add_ctrl(sigmaz(), targets=0) processor.add_ctrl(sigmay(), targets=0) processor.coeffs = np.array([[0.5, 0., 0.5], [0., 0.5, 0.]]) processor.tlist = np.array( [0., np.pi / 2., 2 * np.pi / 2, 3 * np.pi / 2]) processor.plot_pulses(noisy=False) plt.clf() processor.plot_pulses(noisy=True) plt.clf()
def test_save_read(self): """ Test for saving and reading a pulse matrix """ proc = Processor(N=2) proc.add_control(sigmaz(), cyclic_permutation=True) proc1 = Processor(N=2) proc1.add_control(sigmaz(), cyclic_permutation=True) proc2 = Processor(N=2) proc2.add_control(sigmaz(), cyclic_permutation=True) # TODO generalize to different tlist tlist = [0., 0.1, 0.2, 0.3, 0.4, 0.5] amp1 = np.arange(0, 5, 1) amp2 = np.arange(5, 0, -1) proc.pulses[0].tlist = tlist proc.pulses[0].coeff = amp1 proc.pulses[1].tlist = tlist proc.pulses[1].coeff = amp2 proc.save_coeff("qutip_test_CircuitProcessor.txt") proc1.read_coeff("qutip_test_CircuitProcessor.txt") os.remove("qutip_test_CircuitProcessor.txt") assert_allclose(proc1.get_full_coeffs(), proc.get_full_coeffs()) assert_allclose(proc1.get_full_tlist(), proc.get_full_tlist()) proc.save_coeff("qutip_test_CircuitProcessor.txt", inctime=False) proc2.read_coeff("qutip_test_CircuitProcessor.txt", inctime=False) proc2.set_all_tlist(tlist) os.remove("qutip_test_CircuitProcessor.txt") assert_allclose(proc2.get_full_coeffs(), proc.get_full_coeffs())
def add_states(self, state, kind='vector'): """Add a state vector Qobj to Bloch sphere. Parameters ---------- state : qobj Input state vector. kind : str {'vector','point'} Type of object to plot. """ if isinstance(state, Qobj): state = [state] for st in state: if kind == 'vector': vec = [ expect(sigmax(), st), expect(sigmay(), st), expect(sigmaz(), st) ] self.add_vectors(vec) elif kind == 'point': pnt = [ expect(sigmax(), st), expect(sigmay(), st), expect(sigmaz(), st) ] self.add_points(pnt)
def TestDecoherenceNoise(self): """ Test for the decoherence noise """ tlist = np.array([1, 2, 3, 4, 5, 6]) coeffs = [np.array([1, 1, 1, 1, 1, 1])] # Time-dependent decnoise = DecoherenceNoise(sigmaz(), coeffs=coeffs, tlist=tlist, targets=[1]) noise_list = decnoise.get_noise(2) assert_allclose(noise_list[0].ops[0].qobj, tensor(qeye(2), sigmaz())) assert_allclose(noise_list[0].ops[0].coeff, coeffs[0]) assert_allclose(noise_list[0].tlist, tlist) # Time-indenpendent and all qubits decnoise = DecoherenceNoise(sigmax(), all_qubits=True) noise_list = decnoise.get_noise(2) assert_(tensor([qeye(2), sigmax()]) in noise_list) assert_(tensor([sigmax(), qeye(2)]) in noise_list) # Time-denpendent and all qubits decnoise = DecoherenceNoise(sigmax(), all_qubits=True, coeffs=coeffs * 2, tlist=tlist) noise_list = decnoise.get_noise(2) assert_allclose(noise_list[0].ops[0].qobj, tensor(sigmax(), qeye(2))) assert_allclose(noise_list[0].ops[0].coeff, coeffs[0]) assert_allclose(noise_list[0].tlist, tlist) assert_allclose(noise_list[1].ops[0].qobj, tensor(qeye(2), sigmax()))
def testPlot(self): """ Test for plotting functions """ try: import matplotlib.pyplot as plt except Exception: return True # step_func tlist = np.linspace(0., 2 * np.pi, 20) processor = Processor(N=1, spline_kind="step_func") processor.add_control(sigmaz()) processor.pulses[0].tlist = tlist processor.pulses[0].coeff = np.array([np.sin(t) for t in tlist]) fig, _ = processor.plot_pulses() # testing under Xvfb with pytest-xvfb complains if figure windows are # left open, so we politely close it: plt.close(fig) # cubic spline tlist = np.linspace(0., 2 * np.pi, 20) processor = Processor(N=1, spline_kind="cubic") processor.add_control(sigmaz()) processor.pulses[0].tlist = tlist processor.pulses[0].coeff = np.array([np.sin(t) for t in tlist]) fig, _ = processor.plot_pulses() # testing under Xvfb with pytest-xvfb complains if figure windows are # left open, so we politely close it: plt.close(fig)
def TestRandomNoise(self): """ Test for the white noise """ tlist = np.array([1, 2, 3, 4, 5, 6]) coeff = np.array([1, 1, 1, 1, 1, 1]) dummy_qobjevo = QobjEvo(sigmaz(), tlist=tlist) mean = 0. std = 0.5 ops = [sigmaz(), sigmax()] proc_qobjevo = QobjEvo( [[sigmaz(), coeff], [sigmax(), coeff], [sigmay(), coeff]], tlist=tlist) # random noise with external operators gaussnoise = RandomNoise(ops=ops, loc=mean, scale=std) noise = gaussnoise.get_noise(N=1, proc_qobjevo=dummy_qobjevo) assert_allclose(noise.ops[1].qobj, sigmax()) assert_allclose(len(noise.ops[1].coeff), len(tlist)) assert_allclose(len(noise.ops), len(ops)) # random noise with operators from proc_qobjevo gaussnoise = RandomNoise(loc=mean, scale=std) noise = gaussnoise.get_noise(N=1, proc_qobjevo=proc_qobjevo) assert_allclose(noise.ops[1].qobj, sigmax()) assert_(len(noise.ops[0].coeff) == len(tlist)) assert_(len(noise.ops) == len(proc_qobjevo.ops)) # random noise with dt and other random number generator gaussnoise = RandomNoise(lam=0.1, dt=0.2, rand_gen=np.random.poisson) assert_(gaussnoise.rand_gen is np.random.poisson) noise = gaussnoise.get_noise(N=1, proc_qobjevo=proc_qobjevo) assert_allclose(noise.tlist, np.linspace(1, 6, int(5 / 0.2) + 1))
def TestDrift(): """ Test for Drift """ drift = Drift() assert_allclose(drift.get_ideal_qobjevo(2).cte.norm(), 0) drift.add_drift(sigmaz(), targets=1) assert_allclose( drift.get_ideal_qobjevo(dims=[3, 2]).cte, tensor(identity(3), sigmaz()))
def TestDrift(self): """ Test for the drift Hamiltonian """ processor = Processor(N=1) processor.add_drift(sigmaz(), 0) tlist = np.array([0., 1., 2.]) processor.add_pulse(Pulse(identity(2), 0, tlist, False)) ideal_qobjevo, _ = processor.get_qobjevo(noisy=True) assert_equal(ideal_qobjevo.cte, sigmaz())
def TestGetObjevo(self): tlist = np.array([1, 2, 3, 4, 5, 6], dtype=float) coeffs = np.array([[1, 1, 1, 1, 1, 1]], dtype=float) processor = Processor(N=1) processor.add_ctrl(sigmaz()) processor.tlist = tlist processor.coeffs = coeffs # without noise unitary_qobjevo = processor.get_unitary_qobjevo(args={"test": True}) assert_allclose(unitary_qobjevo.ops[0].qobj, sigmaz()) assert_allclose(unitary_qobjevo.tlist, tlist) assert_allclose(unitary_qobjevo.ops[0].coeff, coeffs[0]) assert_(unitary_qobjevo.args["test"], msg="Arguments not correctly passed on") # with decoherence noise dec_noise = DecoherenceNoise(c_ops=sigmax(), coeffs=coeffs, tlist=tlist) processor.add_noise(dec_noise) assert_equal(unitary_qobjevo.to_list(), processor.get_unitary_qobjevo().to_list()) noisy_qobjevo, c_ops = processor.get_noisy_qobjevo(args={"test": True}) assert_(noisy_qobjevo.args["_step_func_coeff"], msg="Spline type not correctly passed on") assert_(noisy_qobjevo.args["test"], msg="Arguments not correctly passed on") assert_(sigmaz() in [pair[0] for pair in noisy_qobjevo.to_list()]) assert_equal(c_ops[0].ops[0].qobj, sigmax()) assert_equal(c_ops[0].tlist, tlist) # with amplitude noise processor.spline_kind = "cubic" new_tlist = np.linspace(1, 6, int(5 / 0.2)) new_coeffs = np.random.rand(1, len(new_tlist)) # noise with a different operator amp_noise = ControlAmpNoise(ops=sigmax(), coeffs=coeffs, tlist=tlist) processor.add_noise(amp_noise) noisy_qobjevo, c_ops = processor.get_noisy_qobjevo(args={"test": True}) assert_(not noisy_qobjevo.args["_step_func_coeff"], msg="Spline type not correctly passed on") assert_(sigmax() in [pair[0] for pair in noisy_qobjevo.to_list()]) # noise with operators in the processor # Since the noise operator is also sigmaz, # it should be merged with the original operator amp_noise2 = ControlAmpNoise(coeffs=coeffs, tlist=tlist) processor.noise[1] = amp_noise2 noisy_qobjevo, c_ops = processor.get_noisy_qobjevo(args={"test": True}) assert_(not noisy_qobjevo.args["_step_func_coeff"], msg="Spline type not correctly passed on") assert_equal(len(noisy_qobjevo.ops), 1) assert_equal(sigmaz(), noisy_qobjevo.ops[0].qobj) assert_equal(coeffs[0] * 2, noisy_qobjevo.ops[0].coeff)
def testOperatorListState(self): """ expect: operator list and state """ res = expect([sigmax(), sigmay(), sigmaz()], fock(2, 0)) assert_(len(res) == 3) assert_(all(abs(res - [0, 0, 1]) < 1e-12)) res = expect([sigmax(), sigmay(), sigmaz()], fock_dm(2, 1)) assert_(len(res) == 3) assert_(all(abs(res - [0, 0, -1]) < 1e-12))
def TestGetObjevo(self): tlist = np.array([1, 2, 3, 4, 5, 6], dtype=float) coeff = np.array([1, 1, 1, 1, 1, 1], dtype=float) processor = Processor(N=1) processor.add_control(sigmaz()) processor.pulses[0].tlist = tlist processor.pulses[0].coeff = coeff # without noise unitary_qobjevo, _ = processor.get_qobjevo( args={"test": True}, noisy=False) assert_allclose(unitary_qobjevo.ops[0].qobj, sigmaz()) assert_allclose(unitary_qobjevo.tlist, tlist) assert_allclose(unitary_qobjevo.ops[0].coeff, coeff[0]) assert_(unitary_qobjevo.args["test"], msg="Arguments not correctly passed on") # with decoherence noise dec_noise = DecoherenceNoise( c_ops=sigmax(), coeff=coeff, tlist=tlist) processor.add_noise(dec_noise) assert_equal(unitary_qobjevo.to_list(), processor.get_qobjevo(noisy=False)[0].to_list()) noisy_qobjevo, c_ops = processor.get_qobjevo( args={"test": True}, noisy=True) assert_(noisy_qobjevo.args["_step_func_coeff"], msg="Spline type not correctly passed on") assert_(noisy_qobjevo.args["test"], msg="Arguments not correctly passed on") assert_(sigmaz() in [pair[0] for pair in noisy_qobjevo.to_list()]) assert_equal(c_ops[0].ops[0].qobj, sigmax()) assert_equal(c_ops[0].tlist, tlist) # with amplitude noise processor = Processor(N=1, spline_kind="cubic") processor.add_control(sigmaz()) tlist = np.linspace(1, 6, int(5/0.2)) coeff = np.random.rand(len(tlist)) processor.pulses[0].tlist = tlist processor.pulses[0].coeff = coeff amp_noise = ControlAmpNoise(coeff=coeff, tlist=tlist) processor.add_noise(amp_noise) noisy_qobjevo, c_ops = processor.get_qobjevo( args={"test": True}, noisy=True) assert_(not noisy_qobjevo.args["_step_func_coeff"], msg="Spline type not correctly passed on") assert_(noisy_qobjevo.args["test"], msg="Arguments not correctly passed on") assert_equal(len(noisy_qobjevo.ops), 2) assert_equal(sigmaz(), noisy_qobjevo.ops[0].qobj) assert_allclose(coeff, noisy_qobjevo.ops[0].coeff, rtol=1.e-10)
def TestControlAmpNoise(self): """ Test for the control amplitude noise """ tlist = np.array([1, 2, 3, 4, 5, 6]) coeff = np.array([1, 1, 1, 1, 1, 1]) # use proc_qobjevo pulses = [Pulse(sigmaz(), 0, tlist, coeff)] connoise = ControlAmpNoise(coeff=coeff, tlist=tlist) noisy_pulses = connoise.get_noisy_dynamics(pulses=pulses) assert_allclose(noisy_pulses[0].coherent_noise[0].qobj, sigmaz()) assert_allclose(noisy_pulses[0].coherent_noise[0].coeff, coeff)
def u_W_deltaa_T_g(W, deltaa, T, g): omega1 = W + deltaa omega2 = W - deltaa # build the bare hamiltonian H0 = (omega1 / 2) * tensor(sigmaz(), Q) + (omega2 / 2) * tensor( Q, sigmaz()) # build the interaction hamiltonians Hi = tensor(sigmax(), sigmax()) # print(g) H = H0 + g * Hi U = (-1j * H * T).expm() return U
def set_up_ops(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. """ # single qubit terms for m in range(num_qubits): self.add_control(sigmax(), [m + 1], label="sx" + str(m)) for m in range(num_qubits): self.add_control(sigmaz(), [m + 1], label="sz" + str(m)) # coupling terms a = tensor([destroy(self.num_levels)] + [identity(2) for n in range(num_qubits)]) for n in range(num_qubits): sm = tensor([identity(self.num_levels)] + [ destroy(2) if m == n else identity(2) for m in range(num_qubits) ]) self.add_control(a.dag() * sm + a * sm.dag(), list(range(num_qubits + 1)), label="g" + str(n))
def set_up_ops(self, N): """ Generate the Hamiltonians for the spinchain model and save them in the attribute `ctrls`. Parameters ---------- N: int The number of qubits in the system. """ # sx_ops self.ctrls += [ tensor([sigmax() if m == n else identity(2) for n in range(N)]) for m in range(N) ] # sz_ops self.ctrls += [ tensor([sigmaz() if m == n else identity(2) for n in range(N)]) for m in range(N) ] # sxsy_ops for n in range(N - 1): x = [identity(2)] * N x[n] = x[n + 1] = sigmax() y = [identity(2)] * N y[n] = y[n + 1] = sigmay() self.ctrls.append(tensor(x) + tensor(y))
def dict_to_qutip(dictrep, encoded_params=None): """ Takes a DictRep Ising Hamiltonian and converts it to a QuTip Ising Hamiltonian. Encoded params must be passed if dictrep weights are variables (abstract) and not actual numbers. """ # make useful operators sigmaz = qto.sigmaz() nqbits = len(dictrep.qubits) zeros = [qto.qzero(2) for m in range(nqbits)] finalH = qt.tensor(*zeros) for key, value in dictrep.H.items(): if key[0] == key[1]: if encoded_params: finalH += encoded_params[value] * nqubit_1pauli( sigmaz, key[0], nqbits) else: finalH += value * nqubit_1pauli(sigmaz, key[0], nqbits) else: if encoded_params: finalH += encoded_params[value] * nqubit_2pauli( sigmaz, sigmaz, key[0], key[1], nqbits) else: finalH += value * nqubit_2pauli(sigmaz, sigmaz, key[0], key[1], nqbits) return finalH
def add_annotation(self, state_or_vector, text, **kwargs): """Add a text or LaTeX annotation to Bloch sphere, parametrized by a qubit state or a vector. Parameters ---------- state_or_vector : Qobj/array/list/tuple Position for the annotaion. Qobj of a qubit or a vector of 3 elements. text : str/unicode Annotation text. You can use LaTeX, but remember to use raw string e.g. r"$\\langle x \\rangle$" or escape backslashes e.g. "$\\\\langle x \\\\rangle$". **kwargs : Options as for mplot3d.axes3d.text, including: fontsize, color, horizontalalignment, verticalalignment. """ if isinstance(state_or_vector, Qobj): vec = [expect(sigmax(), state_or_vector), expect(sigmay(), state_or_vector), expect(sigmaz(), state_or_vector)] elif isinstance(state_or_vector, (list, ndarray, tuple)) \ and len(state_or_vector) == 3: vec = state_or_vector else: raise Exception("Position needs to be specified by a qubit " + "state or a 3D vector.") self.annotations.append({'position': vec, 'text': text, 'opts': kwargs})
def set_up_ops(self, N): """ Generate the Hamiltonians for the spinchain model and save them in the attribute `ctrls`. Parameters ---------- N: int The number of qubits in the system. """ # single qubit terms self.a = tensor([destroy(self.num_levels)] + [identity(2) for n in range(N)]) self.ctrls.append(self.a.dag() * self.a) self.ctrls += [ tensor([identity(self.num_levels)] + [sigmax() if m == n else identity(2) for n in range(N)]) for m in range(N) ] self.ctrls += [ tensor([identity(self.num_levels)] + [sigmaz() if m == n else identity(2) for n in range(N)]) for m in range(N) ] # interaction terms for n in range(N): sm = tensor( [identity(self.num_levels)] + [destroy(2) if m == n else identity(2) for m in range(N)]) self.ctrls.append(self.a.dag() * sm + self.a * sm.dag()) self.psi_proj = tensor([basis(self.num_levels, 0)] + [identity(2) for n in range(N)])
def set_up_ops(self, N): """ Generate the Hamiltonians for the spinchain model and save them in the attribute `ctrls`. Parameters ---------- N: int The number of qubits in the system. """ self.pulse_dict = {} index = 0 # sx_ops for m in range(N): self.pulses.append( Pulse(sigmax(), m, spline_kind=self.spline_kind)) self.pulse_dict["sx" + str(m)] = index index += 1 # sz_ops for m in range(N): self.pulses.append( Pulse(sigmaz(), m, spline_kind=self.spline_kind)) self.pulse_dict["sz" + str(m)] = index index += 1 # sxsy_ops operator = tensor([sigmax(), sigmax()]) + tensor([sigmay(), sigmay()]) for n in range(N - 1): self.pulses.append( Pulse(operator, [n, n+1], spline_kind=self.spline_kind)) self.pulse_dict["g" + str(n)] = index index += 1
def test_multi_gates(self): N = 2 H_d = tensor([sigmaz()]*2) H_c = [] test = OptPulseProcessor(N, H_d, H_c) test.add_ctrl(sigmax(), cyclic_permutation=True) test.add_ctrl(sigmay(), cyclic_permutation=True) test.add_ctrl(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)
def test_simple_hadamard(self): """ Test for optimizing a simple hadamard gate """ N = 1 H_d = sigmaz() H_c = sigmax() qc = QubitCircuit(N) qc.add_gate("SNOT", 0) # test load_circuit, with verbose info num_tslots = 10 evo_time = 10 test = OptPulseProcessor(N, drift=H_d) test.add_control(H_c, targets=0) tlist, coeffs = test.load_circuit(qc, num_tslots=num_tslots, evo_time=evo_time, verbose=True) # test run_state rho0 = qubit_states(1, [0]) plus = (qubit_states(1, [0]) + qubit_states(1, [1])).unit() result = test.run_state(rho0) assert_allclose(fidelity(result.states[-1], plus), 1, rtol=1.0e-6) # test add/remove ctrl test.add_control(sigmay()) test.remove_pulse(0) assert_(len(test.pulses) == 1, msg="Method of remove_pulse could be wrong.") assert_allclose(test.drift.drift_hamiltonians[0].qobj, H_d) assert_(sigmay() in test.ctrls, msg="Method of remove_pulse could be wrong.")
def set_up_ops(self, N): """ Generate the Hamiltonians for the spinchain model and save them in the attribute `ctrls`. Parameters ---------- N: int The number of qubits in the system. """ # single qubit terms self.a = tensor(destroy(self.num_levels)) self.pulses.append( Pulse(self.a.dag() * self.a, [0], spline_kind=self.spline_kind)) for m in range(N): self.pulses.append( Pulse(sigmax(), [m + 1], spline_kind=self.spline_kind)) for m in range(N): self.pulses.append( Pulse(sigmaz(), [m + 1], spline_kind=self.spline_kind)) # interaction terms a_full = tensor([destroy(self.num_levels)] + [identity(2) for n in range(N)]) for n in range(N): sm = tensor( [identity(self.num_levels)] + [destroy(2) if m == n else identity(2) for m in range(N)]) self.pulses.append( Pulse(a_full.dag() * sm + a_full * sm.dag(), list(range(N + 1)), spline_kind=self.spline_kind)) self.psi_proj = tensor([basis(self.num_levels, 0)] + [identity(2) for n in range(N)])
def set_up_ops(self, N): """ Generate the Hamiltonians for the circuitqed model and save them in the attribute `ctrls`. Parameters ---------- N: int The number of qubits in the system. """ # single qubit terms for m in range(N): self.pulses.append( Pulse(sigmax(), [m + 1], spline_kind=self.spline_kind)) for m in range(N): self.pulses.append( Pulse(sigmaz(), [m + 1], spline_kind=self.spline_kind)) # coupling terms a = tensor([destroy(self.num_levels)] + [identity(2) for n in range(N)]) for n in range(N): sm = tensor( [identity(self.num_levels)] + [destroy(2) if m == n else identity(2) for m in range(N)]) self.pulses.append( Pulse(a.dag() * sm + a * sm.dag(), list(range(N + 1)), spline_kind=self.spline_kind))
def test_multi_qubits(self): """ Test for multi-qubits system. """ N = 3 H_d = tensor([sigmaz()] * 3) H_c = [] # test empty ctrls num_tslots = 30 evo_time = 10 test = OptPulseProcessor(N) test.add_drift(H_d, [0, 1, 2]) test.add_control(tensor([sigmax(), sigmax()]), cyclic_permutation=True) # test periodically adding ctrls sx = sigmax() iden = identity(2) # print(test.ctrls) # print(Qobj(tensor([sx, iden, sx]))) assert_(Qobj(tensor([sx, iden, sx])) in test.ctrls) assert_(Qobj(tensor([iden, sx, sx])) in test.ctrls) assert_(Qobj(tensor([sx, sx, iden])) in test.ctrls) test.add_control(sigmax(), cyclic_permutation=True) test.add_control(sigmay(), cyclic_permutation=True) # test pulse genration for cnot gate, with kwargs qc = [tensor([identity(2), cnot()])] test.load_circuit(qc, num_tslots=num_tslots, evo_time=evo_time, min_fid_err=1.0e-6) rho0 = qubit_states(3, [1, 1, 1]) rho1 = qubit_states(3, [1, 1, 0]) result = test.run_state(rho0, options=Options(store_states=True)) assert_(fidelity(result.states[-1], rho1) > 1 - 1.0e-6)
def test_simple_hadamard(self): N = 1 H_d = sigmaz() H_c = [sigmax()] qc = QubitCircuit(N) qc.add_gate("SNOT", 0) # test load_circuit, with verbose info num_tslots = 10 evo_time = 10 test = OptPulseProcessor(N, H_d, H_c) tlist, coeffs = test.load_circuit( qc, num_tslots=num_tslots, evo_time=evo_time, verbose=True) # test run_state rho0 = qubit_states(1, [0]) plus = (qubit_states(1, [0]) + qubit_states(1, [1])).unit() result = test.run_state(rho0) assert_allclose(fidelity(result.states[-1], plus), 1, rtol=1.0e-6) # test add/remove ctrl test.add_ctrl(sigmay()) test.remove_ctrl(0) assert_( len(test.ctrls) == 1, msg="Method of remove_ctrl could be wrong.") assert_allclose(test.drift, H_d) assert_( sigmay() in test.ctrls, msg="Method of remove_ctrl could be wrong.")
def case_is_clifford(self, U): paulis = (identity(2), sigmax(), sigmay(), sigmaz()) for P in paulis: U_P = U * P * U.dag() out = (np.any( np.array([self._prop_identity(U_P * Q) for Q in paulis]) )) return out
def case_is_clifford(self, U): paulis = (identity(2), sigmax(), sigmay(), sigmaz()) for P in paulis: U_P = U * P * U.dag() assert_(any( self._prop_identity(U_P * Q) for Q in paulis ))
def add_states(self, state, kind="vector"): """Add a state vector Qobj to Bloch sphere. Parameters ---------- state : qobj Input state vector. kind : str {'vector','point'} Type of object to plot. """ if isinstance(state, Qobj): state = [state] for st in state: if kind == "vector": vec = [expect(sigmax(), st), expect(sigmay(), st), expect(sigmaz(), st)] self.add_vectors(vec) elif kind == "point": pnt = [expect(sigmax(), st), expect(sigmay(), st), expect(sigmaz(), st)] self.add_points(pnt)
def __init__(self, N, correct_global_phase=True, sx=None, sz=None, sxsy=None): """ Parameters ---------- sx: Integer/List The delta for each of the qubits in the system. sz: Integer/List The epsilon for each of the qubits in the system. sxsy: Integer/List The interaction strength for each of the qubit pair in the system. """ super(SpinChain, self).__init__(N, correct_global_phase) self.sx_ops = [tensor([sigmax() if m == n else identity(2) for n in range(N)]) for m in range(N)] self.sz_ops = [tensor([sigmaz() if m == n else identity(2) for n in range(N)]) for m in range(N)] self.sxsy_ops = [] for n in range(N - 1): x = [identity(2)] * N x[n] = x[n + 1] = sigmax() y = [identity(2)] * N y[n] = y[n + 1] = sigmay() self.sxsy_ops.append(tensor(x) + tensor(y)) if sx is None: self.sx_coeff = [0.25 * 2 * np.pi] * N elif not isinstance(sx, list): self.sx_coeff = [sx * 2 * np.pi] * N else: self.sx_coeff = sx if sz is None: self.sz_coeff = [1.0 * 2 * np.pi] * N elif not isinstance(sz, list): self.sz_coeff = [sz * 2 * np.pi] * N else: self.sz_coeff = sz if sxsy is None: self.sxsy_coeff = [0.1 * 2 * np.pi] * (N - 1) elif not isinstance(sxsy, list): self.sxsy_coeff = [sxsy * 2 * np.pi] * (N - 1) else: self.sxsy_coeff = sxsy
def testExpectSolverCompatibility(self): """ expect: operator list and state list """ c_ops = [0.0001 * sigmaz()] e_ops = [sigmax(), sigmay(), sigmaz(), sigmam(), sigmap()] times = np.linspace(0, 10, 100) res1 = mesolve(sigmax(), fock(2, 0), times, c_ops, e_ops) res2 = mesolve(sigmax(), fock(2, 0), times, c_ops, []) e1 = res1.expect e2 = expect(e_ops, res2.states) assert_(len(e1) == len(e2)) for n in range(len(e1)): assert_(len(e1[n]) == len(e2[n])) assert_(isinstance(e1[n], np.ndarray)) assert_(isinstance(e2[n], np.ndarray)) assert_(e1[n].dtype == e2[n].dtype) assert_(all(abs(e1[n] - e2[n]) < 1e-12))
def test_unitarity_known(): """ Metrics: Unitarity for known cases. """ def case(q_oper, known_unitarity): assert_almost_equal(unitarity(q_oper), known_unitarity) yield case, to_super(sigmax()), 1.0 yield case, sum(map( to_super, [qeye(2), sigmax(), sigmay(), sigmaz()] )) / 4, 0.0 yield case, sum(map( to_super, [qeye(2), sigmax()] )) / 2, 1 / 3.0
def _spin_hamiltonian(N): from qutip.tensor import tensor from qutip.operators import qeye, sigmax, sigmay, sigmaz # array of spin energy splittings and coupling strengths. here we use # uniform parameters, but in general we don't have too h = 1.0 * 2 * np.pi * np.ones(N) Jz = 0.1 * 2 * np.pi * np.ones(N) Jx = 0.1 * 2 * np.pi * np.ones(N) Jy = 0.1 * 2 * np.pi * np.ones(N) # dephasing rate gamma = 0.01 * np.ones(N) si = qeye(2) sx = sigmax() sy = sigmay() sz = sigmaz() sx_list = [] sy_list = [] sz_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)) op_list[n] = sz sz_list.append(tensor(op_list)) # construct the hamiltonian H = 0 # energy splitting terms for n in range(N): H += - 0.5 * h[n] * sz_list[n] # interaction terms for n in range(N-1): H += - 0.5 * Jx[n] * sx_list[n] * sx_list[n+1] H += - 0.5 * Jy[n] * sy_list[n] * sy_list[n+1] H += - 0.5 * Jz[n] * sz_list[n] * sz_list[n+1] return H
def testOperatorListStateList(self): """ expect: operator list and state list """ operators = [sigmax(), sigmay(), sigmaz(), sigmam(), sigmap()] states = [fock(2, 0), fock(2, 1), fock_dm(2, 0), fock_dm(2, 1)] res = expect(operators, states) assert_(len(res) == len(operators)) for r_idx, r in enumerate(res): assert_(isinstance(r, np.ndarray)) if operators[r_idx].isherm: assert_(r.dtype == np.float64) else: assert_(r.dtype == np.complex128) for s_idx, s in enumerate(states): assert_(r[s_idx] == expect(operators[r_idx], states[s_idx]))
CPTP, expand to arbitrary dimensional systems, etc. """ return Qobj(dims=[[[2], [2]], [[2], [2]]], inpt=array([[1. - pe / 2., 0., 0., 1. - pe], [0., pe / 2., 0., 0.], [0., 0., pe / 2., 0.], [1. - pe, 0., 0., 1. - pe / 2.]]), superrep='choi') # CHANGE OF BASIS FUNCTIONS --------------------------------------------------- # These functions find change of basis matrices, and are useful in converting # between (for instance) Choi and chi matrices. At some point, these should # probably be moved out to another module. _SINGLE_QUBIT_PAULI_BASIS = (identity(2), sigmax(), sigmay(), sigmaz()) def _pauli_basis(nq=1): # NOTE: This is slow as can be. # TODO: Make this sparse. CSR format was causing problems for the [idx, :] # slicing below. B = zeros((4 ** nq, 4 ** nq), dtype=complex) dims = [[[2] * nq] * 2] * 2 for idx, op in enumerate(starmap(tensor, product(_SINGLE_QUBIT_PAULI_BASIS, repeat=nq))): B[:, idx] = operator_to_vector(op).dag().data.todense() return Qobj(B, dims=dims)