def test_invariant_under_unitary_transformation(self, dimension): rho1 = rand_dm(dimension, 0.25) rho2 = rand_dm(dimension, 0.25) U = rand_unitary(dimension, 0.25) F = fidelity(rho1, rho2) FU = fidelity(U * rho1 * U.dag(), U * rho2 * U.dag()) assert F == pytest.approx(FU, rel=1e-5)
def testNoise(self): """ Test for Processor with noise """ # setup and fidelity without noise init_state = qubit_states(2, [0, 0, 0, 0]) tlist = np.array([0., np.pi / 2.]) a = destroy(2) proc = Processor(N=2) proc.add_control(sigmax(), targets=1, label="sx") proc.set_all_coeffs({"sx": np.array([1.])}) proc.set_all_tlist(tlist) result = proc.run_state(init_state=init_state) assert_allclose(fidelity(result.states[-1], qubit_states(2, [0, 1, 0, 0])), 1, rtol=1.e-7) # decoherence noise dec_noise = DecoherenceNoise([0.25 * a], targets=1) proc.add_noise(dec_noise) result = proc.run_state(init_state=init_state) assert_allclose(fidelity(result.states[-1], qubit_states(2, [0, 1, 0, 0])), 0.981852, rtol=1.e-3) # white random noise proc.model._noise = [] white_noise = RandomNoise(0.2, np.random.normal, loc=0.1, scale=0.1) proc.add_noise(white_noise) result = proc.run_state(init_state=init_state)
def test_hadamard_pulse(self): system = self.system q0 = system.q0 q1 = system.q1 init_state = system.fock() target_fidelity = 1 - 1e-6 for i, qubit in enumerate([q0, q1]): seq = QasmSequence(system) # h ideal = qubit.hadamard() seq.qasm(f"h q[{i}];", unitary=False, append=True) result = seq.run(init_state) state = result.states[-1] self.assertGreater( fidelity(state, ideal * init_state) ** 2, target_fidelity ) seq.clear() # U2(0, \pi) = H ideal = qubit.hadamard() seq.qasm(f"u2(0,pi) q[{i}];", unitary=False, append=True) result = seq.run(init_state) state = result.states[-1] self.assertGreater( fidelity(state, ideal * init_state) ** 2, target_fidelity ) seq.clear()
def test_ry_pulse(self): system = self.system q0 = system.q0 q1 = system.q1 init_state = system.fock() target_fidelity = 1 - 1e-6 for i, qubit in enumerate([q0, q1]): seq = QasmSequence(system) for denom in [1, 2, 3, 4]: ideal = qubit.Ry(-np.pi / denom) seq.qasm(f"ry(-pi/{denom}) q[{i}];", unitary=False, append=True) result = seq.run(init_state) state = result.states[-1] self.assertGreater( fidelity(state, ideal * init_state) ** 2, target_fidelity ) seq.clear() # U(\theta, 0, 0) = R_y(\theta) ideal = qubit.Ry(np.pi / denom) seq.qasm(f"U(pi/{denom},0,0) q[{i}];", unitary=False, append=True) result = seq.run(init_state) state = result.states[-1] self.assertGreater( fidelity(state, ideal * init_state) ** 2, target_fidelity ) seq.clear()
def get_fidelity_with(self, target_state: Union[str, Qobj] = "ghz") -> float: """ :param target_state: One of "ghz", "ghz_antisymmetric", "ground", and "excited" :return: """ assert (self.solve_result is not None ), "solve_result attribute cannot be None (call solve method)" final_state = self.solve_result.states[-1] if target_state == "ghz": return fidelity(final_state, self.ghz_state.get_state_tensor(symmetric=True))**2 elif target_state == "ghz_antisymmetric": return fidelity( final_state, self.ghz_state.get_state_tensor(symmetric=False))**2 elif target_state == "ground": return fidelity(final_state, tensor(*get_ground_states(self.N)))**2 elif target_state == "excited": return fidelity(final_state, tensor(*get_excited_states(self.N)))**2 elif isinstance(target_state, Qobj): return fidelity(final_state, target_state)**2 else: raise ValueError( f"target_state has to be one of 'ghz', 'ground', or 'excited', not {target_state}." )
def test_rotations_pulse(self): q0 = Transmon("q0", levels=2) q1 = Transmon("q1", levels=3, kerr=-200e-3) q0.gaussian_pulse.sigma = 40 q1.gaussian_pulse.sigma = 40 system = System("system", modes=[q0, q1]) init_state = system.fock() for qubit in [q0, q1]: for _ in range(1): _ = tune_rabi(system, init_state=init_state, mode_name=qubit.name, verify=False) angles = np.linspace(-np.pi, np.pi, 5) for angle in angles: for qubit in [q0, q1]: seq = get_sequence(system) qubit.rotate_x(angle) unitary = qubit.rotate_x(angle, unitary=True) result = seq.run(init_state) fidelity = qutip.fidelity(result.states[-1], unitary * init_state)**2 self.assertGreater(fidelity, 1 - 1e-2) seq = get_sequence(system) qubit.rotate_y(angle) unitary = qubit.rotate_y(angle, unitary=True) result = seq.run(init_state) fidelity = qutip.fidelity(result.states[-1], unitary * init_state)**2 self.assertGreater(fidelity, 1 - 1e-2)
def test_env_error(self): print("----------Test env dephasing-----------") n_steps = 10 rho_noise1 = errs.env_error(rho_test, 20, .3, 25e-6, 2, [0, 1]) rho_noise2 = errs.env_error(rho_test, 0, .3, 25e-6, 2, [0, 1]) # print(rho_noise1) # print(rho_noise.tr()) print(qt.fidelity(rho_noise1, psi_test)) print(qt.fidelity(rho_noise2, psi_test))
def fitfunc(x): L = len(x) / 3 x_noinit = x[0:L] x_up = x[L:2 * L] x_down = x[2 * L:3 * L] ### Initial states rho_c1 = F1() * rho0 + (1 - F1()) * rho1 rho_c2_up = F2() * rho0 + (1 - F2()) * rho1 rho_c2_down = (1 - F2()) * rho0 + F2() * rho1 rho_c2_noinit = 0.5 * rho0 + 0.5 * rho1 rho_up = qutip.tensor(rhox, rho_c1, rho_c2_up) rho_down = qutip.tensor(rhox, rho_c1, rho_c2_down) rho_noinit = qutip.tensor(rhox, rho_c1, rho_c2_noinit) ### Hamiltonian H = 2 * np.pi * (det() * qutip.tensor(szz, Id, Id) + 430e3 * (qutip.tensor(Id, sz, Id) + qutip.tensor(Id, Id, sz)) + A_par_1() * qutip.tensor(szz, sz, Id) + A_perp_1() * qutip.tensor(szz, sx, Id) + A_par_2() * qutip.tensor(szz, Id, sz) + A_perp_2() * qutip.tensor(szz, Id, sx)) Fid_up = np.zeros(len(x_up)) Fid_down = np.zeros(len(x_down)) Fid_noinit = np.zeros(len(x_noinit)) for ii, tau in enumerate(x_up): expH = (-1j * H * tau).expm() ### State evolution rho_final_up = expH * rho_up * expH.dag() rho_final_down = expH * rho_down * expH.dag() rho_final_noinit = expH * rho_noinit * expH.dag() ### Trace out the electron rho_el_final_up = rho_final_up.ptrace( 0) # Trace out the nuclear spins rho_el_final_down = rho_final_down.ptrace( 0) # Trace out the nuclear spins rho_el_final_noinit = rho_final_noinit.ptrace( 0) # Trace out the nuclear spins ### Final fidelity Fid_up[ii] = 0.5 + 0.5 * (2 * qutip.fidelity( rhox, rho_el_final_up)**2 - 1) * np.exp(-(tau / t())**2) Fid_down[ii] = 0.5 + 0.5 * (2 * qutip.fidelity( rhox, rho_el_final_down)**2 - 1) * np.exp(-(tau / t())**2) Fid_noinit[ii] = 0.5 + 0.5 * (2 * qutip.fidelity( rhox, rho_el_final_noinit)**2 - 1) * np.exp(-(tau / t())**2) Fid = np.r_[Fid_noinit, Fid_up, Fid_down] return Fid
def test_qasm_circuit_pulse(self): qreg = self.qreg n = len(qreg.active_modes) QASM_CIRCUIT = [ "OPENQASM 2.0;", 'include "qelib1.inc";', f"qreg q[{n}];", "h q[0];", "barrier;", ] QASM_CIRCUIT.extend([f"CX q[0],q[{i}];" for i in range(1, n)]) QASM_CIRCUIT = "\n\t".join([""] + QASM_CIRCUIT) print("Running the following QASM circuit:") print(QASM_CIRCUIT) seq = QasmSequence(qreg) seq.qasm_circuit(QASM_CIRCUIT, unitary=False, append=True) _ = seq.plot_coefficients(subplots=False) result = seq.run(qreg.ground_state()) fid = fidelity(result.states[-1], self.ideal_state) ** 2 print( f"Pulsed qasm_circuit Bell state fidelity " f"(n = {len(qreg.active_modes)}): {fid:.7f}." ) self.assertLess(1 - fid, 1e-6)
def timescan(self, nT=100, **kwargs): # do a gate dynamics time scan # !!! If parameters are not separately specified, chooses optimal gate parameters # for programmed gate detuning self.set_custom_parameters(**kwargs) # initialize result vectors end_populations_dndn = [] end_populations_upup = [] end_populations_updn = [] end_populations_dnup = [] fidelities = [] times, final_rhos = self.do_gate(nT=nT) for ii in range(len(times)): end_populations_upup.append(expect(self.spin_upup, final_rhos[ii])) end_populations_dndn.append(expect(self.spin_dndn, final_rhos[ii])) end_populations_updn.append(expect(self.spin_updn, final_rhos[ii])) end_populations_dnup.append(expect(self.spin_dnup, final_rhos[ii])) rho_target = 1 / 2 * (self.uu_uu + self.dd_dd - 1j * self.ud_ud + 1j * self.du_du) fidelities.append( fidelity(rho_target, ptrace(final_rhos[ii], [0, 1]))**2) return times, end_populations_upup, end_populations_dndn, end_populations_updn, end_populations_dnup, fidelities
def extract_ft(ignore_percent, ghzs, times): N = len(times) ignore_number = int(N*ignore_percent/100) indices_sorted = np.argsort(times) t_sorted = times[indices_sorted] if ignore_number != 0: t_max = t_sorted[:-ignore_number][-1] tavg = np.average(times[indices_sorted][:-ignore_number]) tstd = np.std(times[indices_sorted][:-ignore_number]) ghz = np.sum(ghzs[indices_sorted][:-ignore_number]) else: t_max = t_sorted[-1] tavg = np.average(times) tstd = np.std(times) ghz = np.sum(ghzs) ghz = ghz/(N - ignore_number) ghz = stab.twirl_ghz(ghz) fidelity = qt.fidelity(ghz, ghz_ref) print("_____________________________________________________") print("N: ", N) print("T_avg: ", tavg, tstd) print("TIME_MAX:", t_max) print("F: ", fidelity) return fidelity, t_max
def plot_ghz_states_overlaps(self, ax, with_antisymmetric_ghz: bool, plot_title: bool = True): labelled_states = [(self.ghz_state.get_state_tensor(), r"$\psi_{\mathrm{GHZ}}^{\mathrm{s}}$")] if with_antisymmetric_ghz is not None: labelled_states.append( (self.ghz_state.get_state_tensor(symmetric=False), r"$\psi_{\mathrm{GHZ}}^{\mathrm{a}}$")) for _state, _label in labelled_states: ax.plot(self.t_list, [ fidelity(_state, _instantaneous_state)**2 for _instantaneous_state in self.solve_result.states ], label=_label, lw=1, alpha=0.8) ax.set_ylabel("Fidelity") if plot_title: ax.set_title("Fidelity with GHZ states") ax.set_ylim((-0.1, 1.1)) ax.yaxis.set_ticks([0, 0.5, 1]) ax.legend()
def test_two_qubit_error(self): print("----------Test two qubit error-----------") p = .09 rho_noise = errs.two_qubit_gate_noise(rho_test, p, 2, 0, 1) print(rho_noise) print(rho_noise.tr()) print(qt.fidelity(rho_noise, psi_test))
def test_score(params, x, y): """Calculates the average fidelity between the predicted and output kets for a given on the whole dataset. Args: params (obj:`np.ndarray`): parameters :math:`\t` and :math:`\tau` in :math: `U^{\dagger} U(\vec{t},\vec{\tau})` inputs (obj:`np.ndarray`): input kets :math:`|\psi_{l} \rangle` in the dataset outputs (obj:`np.ndarray`): output kets :math:`U(\vec{t}, \vec{\tau}) |ket_{input}\rangle` in the dataset Returns: float: fidelity between :math:`U(\vec{t}, \vec{\tau})|ket_{input} \rangle` and the output (label) kets for parameters :math:`\vec{t}, \vec{\tau}` averaged over the entire training set. """ fidel = 0 for i in range(train_len): pred = np.matmul(make_unitary(N, params), x[i]) step_fidel = fidelity(Qobj(pred), Qobj(y[i])) fidel += step_fidel return fidel / train_len
def scan_efficiency(self, ndot=0, fact_vec=[1, 2, 3, 4, 5], tau_mot=0, gamma_el=0, gamma_ram=0, tau_spin=0): if self.species is not 'effic_test': raise TypeError( 'Need species effic_test for this to work (factor not implemented for other ions species)' ) # initialize result vectors errors = [] efficiencies = [] rho_target = 1 / 2 * (self.uu_uu + self.dd_dd - 1j * self.ud_ud + 1j * self.du_du) self.set_mot_dephasing_time(tau_mot) self.set_el_deph_rate(gamma_el) self.set_ram_scat_rate(gamma_ram) self.set_spin_dephasing_time(tau_spin) for factor in fact_vec: self.set_eff_factor(factor) self.set_heating_rate(ndot) times, final_rhos = self.do_gate() errors.append( 1 - fidelity(rho_target, ptrace(final_rhos[-1], [0, 1]))**2) efficiencies.append(self.calc_gate_eff()) return fact_vec, errors, efficiencies
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) assert (len(test.get_control_labels()) == 3) 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=SolverOptions(store_states=True)) 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)
def get_fid(self, args=None, phi_tgt=None): if args is not None: self.run(args) if phi_tgt is not None: self.phi_tgt = phi_tgt self.fid = np.square(fidelity(self.final_state, self.phi_tgt)) return self.fid
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)
def test_u2_pulse(self): system = self.system q0 = system.q0 q1 = system.q1 init_state = system.fock() target_fidelity = 1 - 1e-6 for i, qubit in enumerate([q0, q1]): # U2(\phi, \lambda) = RZ(\phi) RY(\frac{\pi}{2}) RZ(\lambda) for phi_denom in [1, 2, 3, 4]: for lam_denom in [1, 2, 3, 4]: seq = QasmSequence(system) ideal = ( qubit.Rz(np.pi / phi_denom) * qubit.Ry(np.pi / 2) * qubit.Rz(np.pi / lam_denom) ) seq.qasm( f"u2(pi/{phi_denom},pi/{lam_denom}) q[{i}];", unitary=False, append=True, ) result = seq.run(init_state) state = result.states[-1] self.assertGreater( fidelity(state, ideal * init_state) ** 2, target_fidelity )
def detuning_scan(self, delta_g_vec, delta_g_0=None, **kwargs): # do a gate dynamics frequency scan # !!! If parameters are not separately specified, chooses optimal gate parameters # for programmed gate detuning self.set_custom_parameters(delta_g=delta_g_0, **kwargs) # initialize result vectors end_populations_dndn = [] end_populations_upup = [] end_populations_updn = [] end_populations_dnup = [] fidelities = [] for delta_g in delta_g_vec: self.set_gate_detuning(delta_g) times, final_rhos = self.do_gate(nT=2) end_populations_upup.append(expect(self.spin_upup, final_rhos[-1])) end_populations_dndn.append(expect(self.spin_dndn, final_rhos[-1])) end_populations_updn.append(expect(self.spin_updn, final_rhos[-1])) end_populations_dnup.append(expect(self.spin_dnup, final_rhos[-1])) rho_target = 1 / 2 * (self.uu_uu + self.dd_dd - 1j * self.ud_ud + 1j * self.du_du) fidelities.append( fidelity(rho_target, ptrace(final_rhos[-1], [0, 1]))**2) return end_populations_upup, end_populations_dndn, end_populations_updn, end_populations_dnup, fidelities
def run_operator(state, QI_a, QQ_a, QI_c, QQ_c, show_fid_graph=False): start_time = time.time_ns() fid = [] prod = 1 for k in range(num_time_steps): H = H0 + Ha_I * QI_a[k] + Ha_Q * QQ_a[k] + Hc_I * QI_c[ k] + Hc_Q * QQ_c[k] U = ((-1j * dt) * H).expm() prod = U * prod bl.add_states(qt.ptrace(prod * state, 0)) fid.append(qt.fidelity(prod * state, state_target * state_init)) result = prod * state if show_fid_graph: fig, ax = plt.subplots(1, 1) ax.plot(times, fid) ax.set_title("Fidelity Over Time") ax.set_xlabel('Time (sec)') ax.set_ylabel('Fidelity') print("- Simulating the system took", str((time.time_ns() - start_time) * 1e-9)[0:4], "Seconds") return result
def scan_tilt_angle(self, angle_max=10 / 360 * 2 * pi, angle_min=-10 / 360 * 2 * pi, n_steps=10, mode_name='rad_ip_l', **kwargs): # simulate gate fidelity for different heating rates # initialize result vectors self.set_custom_parameters(**kwargs) errors = [] rho_target = tensor(self.dn_dn, self.dn_dn) tilt_angles = np.linspace(angle_min, angle_max, n_steps) self.set_ion_temp(self.modes.modes[mode_name].nbar) detuning_offset = self.omega_z - self.modes.modes[mode_name].freq self.set_gate_detuning(self.delta_g + detuning_offset) for angle in tilt_angles: self.set_lamb_dicke_factors(mode_name=mode_name, raman_misalignment=angle) times, final_rhos = self.do_gate() errors.append( 1 - fidelity(rho_target, ptrace(final_rhos[-1], [0, 1]))**2) return tilt_angles, errors
def test_N_level_system(self): """ Test for circuit with N-level system. """ mat3 = qp.rand_unitary_haar(3) def controlled_mat3(arg_value): """ A qubit control an operator acting on a 3 level system """ control_value = arg_value dim = mat3.dims[0][0] return (tensor(fock_dm(2, control_value), mat3) + tensor(fock_dm(2, 1 - control_value), identity(dim))) qc = QubitCircuit(2, dims=[3, 2]) qc.user_gates = {"CTRLMAT3": controlled_mat3} qc.add_gate("CTRLMAT3", targets=[1, 0], arg_value=1) props = qc.propagators() final_fid = qp.average_gate_fidelity(mat3, ptrace(props[0], 0) - 1) assert pytest.approx(final_fid, 1.0e-6) == 1 init_state = basis([3, 2], [0, 1]) result = qc.run(init_state) final_fid = qp.fidelity(result, props[0] * init_state) assert pytest.approx(final_fid, 1.0e-6) == 1.
def scan_t_g(self, t_max=50e-6, t_min=10e-6, n_steps=10, tau=0, ndot=0, factor=1, gamma_el=0, gamma_ram=0, **kwargs): # simulate gate fidelity for different gate pulse durations, with delta_g # and Omega_R optimised for this t_g # i.e. determines scaling of errors due to eg heating with t_g errors = [] rho_target = 1 / 2 * (self.uu_uu + self.dd_dd - 1j * self.ud_ud + 1j * self.du_du) ts = np.linspace(t_min, t_max, n_steps) for t_g in ts: delta_g = self.calc_ideal_gate_detuning(T=t_g, verbose=False) self.set_custom_parameters(delta_g=delta_g, **kwargs) times, final_rhos = self.do_gate() errors.append( 1 - fidelity(rho_target, ptrace(final_rhos[-1], [0, 1]))**2) return ts, errors
def random_benchmark(state, **kwargs): target = root_iSWAP * state #.ptrace([1,2]) 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 test_orthogonal(self, left_dm, right_dm, dimension): left = basis(dimension, 0) right = basis(dimension, dimension // 2) if left_dm: left = left.proj() if right_dm: right = right.proj() assert fidelity(left, right) == pytest.approx(0, abs=1e-6)
def fitfunc(x): L = len(x)/3 x_noinit = x[0:L] x_up = x[L:2*L] x_down = x[2*L:3*L] ### Initial states rho_c1 = F1()*rho0 + (1-F1())*rho1 rho_c2_up = F2()*rho0 + (1-F2())*rho1 rho_c2_down = (1-F2())*rho0 + F2()*rho1 rho_c2_noinit = 0.5*rho0 + 0.5*rho1 rho_up = qutip.tensor(rhox,rho_c1,rho_c2_up) rho_down = qutip.tensor(rhox,rho_c1,rho_c2_down) rho_noinit = qutip.tensor(rhox,rho_c1,rho_c2_noinit) ### Hamiltonian H = 2*np.pi*(det()*qutip.tensor(szz,Id,Id) + 431.9e3*(qutip.tensor(Id,sz,Id) + qutip.tensor(Id,Id,sz)) + A_par_1()*qutip.tensor(szz,sz,Id) + A_perp_1()*qutip.tensor(szz,sx,Id) + A_par_2()*qutip.tensor(szz,Id,sz) + A_perp_2()*qutip.tensor(szz,Id,sx) ) Fid_up = np.zeros(len(x_up)) Fid_down = np.zeros(len(x_down)) Fid_noinit = np.zeros(len(x_noinit)) for ii, tau in enumerate(x_up): expH = (-1j*H*tau).expm() ### State evolution rho_final_up = expH * rho_up * expH.dag() rho_final_down = expH * rho_down * expH.dag() rho_final_noinit = expH * rho_noinit * expH.dag() ### Trace out the electron rho_el_final_up = rho_final_up.ptrace(0) # Trace out the nuclear spins rho_el_final_down = rho_final_down.ptrace(0) # Trace out the nuclear spins rho_el_final_noinit = rho_final_noinit.ptrace(0) # Trace out the nuclear spins ### Final fidelity Fid_up[ii] = O() + 0.5*(2*qutip.fidelity(rhox, rho_el_final_up)**2 -1)* np.exp(-(tau/t()/1e-6)**2) Fid_down[ii] = O() + 0.5*(2*qutip.fidelity(rhox, rho_el_final_down)**2 -1)* np.exp(-(tau/t()/1e-6)**2) Fid_noinit[ii] = O() + 0.5*(2*qutip.fidelity(rhox, rho_el_final_noinit)**2 -1)* np.exp(-(tau/t()/1e-6)**2) Fid = np.r_[Fid_noinit, Fid_up, Fid_down] return Fid
def dis(state1,state2): (n,m)=state1.shape if state1.type is not 'ket' or state2.type is not 'ket': print("Error: One or more input to the distance function is not a ket." ) p_0=0 else: fid=qt.fidelity(state1,state2) p_0 = 1/n + (n-1)*fid/n return p_0
def fidelity(self): """ Calculates fidelity of current and goal state/unitary. Return: fid (float): fidelity measure """ if self.is_unitary: assert self.current_unitary.shape == self.goal_unitary.shape fid = fidelity( Qobj(self.current_unitary) * self.basis_state, Qobj(self.goal_unitary) * self.basis_state) else: assert len(self.current_state) == len(self.goal_state) fid = fidelity(Qobj([self.current_state]), Qobj([self.goal_state])) return fid
def report_stats(result: OptimResult, N: int): result.stats.report() target_state = StandardGHZState(N).get_state_tensor() final_fidelity = qutip.fidelity(target_state, result.evo_full_final)**2 print(f"final_fidelity: {final_fidelity:.5f}") print(f"Final gradient normal {result.grad_norm_final:.3e}") print(f"Terminated due to {result.termination_reason}")
q1 = qt.basis(2,0) q2 = (qt.basis(2,1))#+qt.basis(2,0)).unit() # L1 = 0.01 * qt.tensor(qt.qeye(5),qt.destroy(2),I) # L2 = 0.01 * qt.tensor(qt.qeye(5),I,qt.destroy(2)) # lindblads = [L1,L2] if __name__ == '__main__': # cav = thermal_state(5e9,20e-3) sim = Simulation(do_qt_mesolve, state=qt.tensor(cav, q1, q2), fname='time_dependent.yaml') # sim.append_L(cavity_loss(10000, sim.w_c, 20e-3, sim.dims)) # sim.append_L(thermal_in(10000, sim.w_c, 20e-3, sim.dims)) # sim.append_L(relaxation(1,sim.dims,1)) # sim.append_L(relaxation(1,sim.dims,2)) # sim.append_L(decoherence(1e2,sim.dims,1)) # sim.append_L(decoherence(1e2,sim.dims,2)) states = sim.run_solver(nsteps=1000, steps=10000, tau=1e-9, progress_bar=True) target = root_iSWAP * qt.tensor(q1, q2) fids1 = [qt.fidelity(target, state.ptrace([1,2])) for state in states] # print(np.max(fids1),np.argmax(fids1)*1e-9) # sim = Simulation(do_qt_mesolve, state=qt.tensor(q1, q2), # fname='2qtest.yaml') # states = sim.run_solver(nsteps=1000,steps=2500,tau=1e-7,progress_bar=True) # target = root_iSWAP * qt.tensor(q1, q2) # fids2 = [qt.fidelity(target, state) for state in states] # print(np.max(fids1),np.argmax(fids1)*1e-7) plt.plot(1e-7*np.arange(len(fids1)), fids1, 'r') # # 1e-7*np.arange(len(fids2)), fids2, 'b') plt.show()
def random_benchmark(state, **kwargs): target = root_iSWAP * state#.ptrace([1,2]) 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]))
def fidelitycheck(self, out1, out2, rho0vec): fid = np.zeros(len(out1.states)) for i, E in enumerate(out2.states): rhot = vector_to_operator(E * rho0vec) fid[i] = fidelity(out1.states[i], rhot) return fid
print(Best_A) print(Best_B) Sin_terms = np.sin(np.outer(time, Freqs)) Cos_terms = np.cos(np.outer(time, Freqs)) f_t = np.add(np.dot(Sin_terms, Best_A), np.dot(Cos_terms, Best_B)) plt.figure(1) plt.plot(time, f_t) def func_t(t, args): S_terms = np.sin(np.outer(t, args['w'])) C_terms = np.cos(np.outer(t, args['w'])) return np.add(np.dot(S_terms, args['A']), np.dot(C_terms, args['B'])) Hamiltonian = [H0, [H1, func_t]] arguments = {'w':Freqs, 'A':Best_A, 'B':Best_B} Evolution = qutip.mesolve(Hamiltonian, Rho_ini, time, [np.sqrt(0.5)*qutip.tensor(qutip.sigmax(),qutip.sigmax())], [], args = arguments) fidelity = [] for i in range (len(time)) : fidelity.append(qutip.fidelity(Rho_fi, Evolution.states[i])) plt.figure(2) plt.plot(time, fidelity) print(fidelity[-1])
def Cost(x) : #Function to be minimized using scipy.optimize a = x[0:Nc:1] #Returns 1 - Fidelity b = x[Nc:2*Nc:1] args = {'w' : np.hstack((w, Frequencies)), 'A' : np.hstack((a, Best_parameters_A)), 'B' : np.hstack((b, Best_parameters_B))} temp = qutip.mesolve(H, Initial_density, Time_steps, [np.sqrt(0.5)*qutip.tensor(qutip.sigmax(),qutip.sigmax())], [], args = args) return 1. - qutip.fidelity(Final_density, temp.states[len(Time_steps) - 1])