def get2(x): """ parametrized (6 parameters) circuitry which can create a c. GHZ state i.e. |000> - |111>""" g1 = qt.tensor(qt.rx(x[0]), qt.rx(x[1]), qt.rx(x[2])) g2 = qt.cnot(3, 1, 2) g3 = qt.cnot(3, 0, 2) g4 = qt.tensor(qt.rx(x[3]), qt.rx(x[4]), qt.ry(x[5])) return g4 * g3 * g2 * g1 * qt.tensor(zero, zero, zero)
def main(): pop = input("How many of each gate do you want to populate? ") pop = int(pop) split = input( "Give training set split, in the form of a number between 0 and 1: ") k = input("Give a k value: ") k = int(k) d = input("Gimme a range of reference states: ") d = int(d) qubits = 4 n = 2**qubits csvpath = [ "GHZTrainingData200new.csv", "GHZTrainingData200QFT.csv", "GHZTrainingData200Had.csv", "GHZTrainingData200QFT2.csv" ] #special subset for quantum repeater ghzcirc = [ hadamaker(qubits, [0]), qt.cnot(qubits, 0, 1), qt.cnot(qubits, 1, 2), qt.cnot(qubits, 2, 3) ] ghz_tags = ["Hadamard", "CNOT", "CNOT", "CNOT"] circuit = [] angles = [] for i in range(len(ghzcirc)): circuit.append(ghzcirc[i]) circuit.append(ghz_tags[i]) cat = categorize(circuit) alt = [] angles = [] for i in range(len(circuit)): if type(circuit[i]) == str: continue else: alt.append(gate_troubleshooter(circuit[i], n)) choice = [2, 4, 5, 6] vector_name = ['new', 'QFT', 'Hadamard 2', 'Fourier State'] index = 0 for x in choice: choice = x path = csvpath[index] vectors = gen_basis_vectors(n, n, choice) print(vector_name[index]) index = index + 1 probs = colin_mochrie(alt, angles, vectors, pop, cat, qubits, d, path) KNN(probs, split, k) return 0
def entangle_players(self, a, b, dt, inverse): copy = self.current_state.copy() copy.dims = [[2]*self.n_players, [1]*self.n_players] dt = 0.01*dt if a != 0: copy = qt.tensor_swap(copy, (a, 0)) if b != 1: if b == 0: copy = qt.tensor_swap(copy, (a, 1)) else: copy = qt.tensor_swap(copy, (b, 1)) full_op = qt.tensor(qt.cnot(), *[qt.identity(2)]*(self.n_players-2)) full_unitary = (-2*math.pi*1j*dt*full_op).expm() if inverse: full_unitary = full_unitary.dag() full_unitary.dims = [[2]*self.n_players, [2]*self.n_players] copy = full_unitary*copy if b != 1: if b == 0: copy = qt.tensor_swap(copy, (1, a)) else: copy = qt.tensor_swap(copy, (1, b)) if a != 0: copy = qt.tensor_swap(copy, (0, a)) copy.dims = self.current_state.dims self.current_state = copy
def two_qubit_cliffords(): '''returns the two qubit clifford group as a list of qutip superoperators''' rot_cliffords = [qt.identity(2), qt.rotation((2/(np.sqrt(3))),(qt.sigmax()+qt.sigmay()+qt.sigmaz())/3),qt.rotation((4/(np.sqrt(3))),(qt.sigmax()+qt.sigmay()+qt.sigmaz())/3)] rot_class_cliffords = [qt.to_super(qt.tensor(x,y)) for x in rot_cliffords for y in rot_cliffords] class_one_cliffords = [qt.to_super(qt.tensor(x,y)) for x in qt.qubit_clifford_group() for y in qt.qubit_clifford_group()] class_two_cliffords = [x*qt.to_super(qt.cnot())*y for x in class_one_cliffords for y in rot_class_cliffords] class_three_cliffords = [x*qt.to_super(qt.iswap())*y for x in class_one_cliffords for y in rot_class_cliffords] class_four_cliffords = [x*qt.to_super(qt.swap()) for x in class_one_cliffords] return class_one_cliffords+class_two_cliffords+ class_three_cliffords+ class_four_cliffords
def test_EntanglingPower(): "Entangling power" assert_(abs(entangling_power(cnot()) - 2/9) < 1e-12) assert_(abs(entangling_power(iswap()) - 2/9) < 1e-12) assert_(abs(entangling_power(berkeley()) - 2/9) < 1e-12) assert_(abs(entangling_power(sqrtswap()) - 1/6) < 1e-12) alpha = 2 * np.pi * np.random.rand() assert_(abs(entangling_power(swapalpha(alpha)) - 1/6 * np.sin(np.pi * alpha) ** 2) < 1e-12) assert_(abs(entangling_power(swap()) - 0) < 1e-12)
def rot(qubits,choice): a=randint(0,qubits-2) b=randint(a+1,qubits-1) k=qt.cnot(qubits,a,b) k=k.full() if choice: k=np.random.permutation(k) k=qt.Qobj(k) #k=k*k.dag() k=tensor_fix(k) cn_final=qt.Qobj(k) return cn_final
def test_EntanglingPower(): "Entropy: Entangling power" assert_(abs(entangling_power(cnot()) - 2 / 9) < 1e-12) assert_(abs(entangling_power(iswap()) - 2 / 9) < 1e-12) assert_(abs(entangling_power(berkeley()) - 2 / 9) < 1e-12) assert_(abs(entangling_power(sqrtswap()) - 1 / 6) < 1e-12) alpha = 2 * np.pi * np.random.rand() assert_( abs( entangling_power(swapalpha(alpha)) - 1 / 6 * np.sin(np.pi * alpha)**2) < 1e-12) assert_(abs(entangling_power(swap()) - 0) < 1e-12)
def _get_two_qubit_gates(self, N, controls, targets, sigma): # Construct two qubit C-sigma gates. gates = [] if sigma == "X": for i in range(len(controls)): gates += [qt.cnot(N, controls[i], targets[i])] if sigma == "Z": for i in range(len(controls)): gates += [qt.cphase(np.pi, N, controls[i], targets[i])] return gates
def main(): d = 4 qubits = 3 n = 2**qubits state_creator = [ hadamaker(qubits, [1]), qt.cnot(qubits, 1, 2), qt.cnot(qubits, 0, 1), hadamaker(qubits, [0]), qt.cnot(qubits, 1, 2), conv_cz() ] state_creator_tags = [ "Hadamard", "CNOT", "CNOT2", "Hadamard2", "CNOT3", "Control Z" ] circuit = [] for i in range(len(state_creator)): circuit.append(state_creator[i]) circuit.append(state_creator_tags[i]) alt = [] for i in range(len(circuit)): if type(circuit[i]) == str: continue else: alt.append(gate_troubleshooter(circuit[i], n)) vectors = gen_basis_vectors(n, n, 2) ideal = get_ideal(alt, vectors, qubits, d) print(ideal[0]) tolerance = 0.9 for i in range(10): multi = uniform(0, 1) ideal2 = ideal[0] probvector = [] for x in range(len(ideal2)): probvector.append(multi * ideal2[x]) truth = within_tolerance(tolerance, probvector, ideal[0]) print(multi) print(truth) return 0
def _swap_noise(self, rho, pos): # Apply the noise induced by the one way SWAP gate # NOTE: use only two CNOTs to perform a SWAP # Swap noise is only single qubit gate because one of the states # because a one way Swap gate is used ancilla = qt.basis(2, 0) * qt.basis(2, 0).dag() ancilla = errs.env_error_all(ancilla, self.a0, self.a1, self.check["time0"]) rho = qt.tensor(rho, ancilla) N = len(rho.dims[0]) # Define ideal gates CNOT1 = qt.cnot(N, N - 1, pos) CNOT2 = qt.cnot(N, pos, N - 1) # Apply 3 CNOTS to get a swap rho = errs.two_qubit_gate(rho, CNOT1, self.pg, N, pos, N - 1) rho = errs.two_qubit_gate(rho, CNOT2, self.pg, N, pos, N - 1) rho = errs.two_qubit_gate(rho, CNOT1, self.pg, N, pos, N - 1) # Measure the ancilla to reduce the dimension rho = errs.measure_single_Zbasis_forced(rho, self.pm, 0, N, pos) return rho
def __init__(self, n, g, init_discrete=None, init_contin=None): # n: number of qubits # g: number of gadgets # du: derivatives # gamma: noise value # kraus: set of kraus operators self.g = g self.n = n self.init_state = qt.Qobj(qt.basis(2**n, 0), dims=[[2] * self.n, [1] * self.n]) #I think it might actually be worth setting gamma, du and kraus as global variables if init_discrete is None: self.sq = [np.random.choice(2) for i in range(g * n * (n + 1))] self.tq = [np.random.choice(2) for i in range(g * n * (n - 1))] else: self.sq, self.tq = init_discrete[0], init_discrete[1] if init_contin is None: self.sqp = [ 2 * np.pi * np.random.random() for i in range(int(3 * sum(self.sq))) ] else: self.sqp = init_contin #size of sq and sqp is 2*g*n*(n+1) #size of tq is g*n*(n-1) print(self.sq, self.tq) self.cnots = [] count = 0 for i in range(g): for j in range(n): temp_c = qt.tensor([si] * n) for k in range(n): if k != j: #print(self.tq[count]) if self.tq[count] == 1: #print('cnot',qt.cnot(self.n, j, k)) temp_c = qt.cnot(self.n, j, k) * temp_c count += 1 self.cnots.append(temp_c) else: self.cnots.append(temp_c) count += 1
def _parity_projection_ket(self, psi, targets, measurement): plus = qt.snot() * qt.basis(2, 0) full_psi = qt.tensor(psi, plus) N = len(full_psi.dims[0]) control = N-1 if self.basis_parity == "X": for t in targets: full_psi = qt.cnot(N, control, t) * full_psi if self.basis_parity == "Z": for t in targets: full_psi = qt.cphase(np.pi, N, control, t) * full_psi # NOTE: Parity projection is not a channel collapsed_psi = ops.collapse_single_Xbasis_ket(full_psi, measurement, N, control, True) if collapsed_psi.norm() != 0: collapsed_psi = collapsed_psi/collapsed_psi.norm() return collapsed_psi
# b = prot.expedient(rho_initial, [0, 1, 2], "X") print("----GHZ FIDELITY--------------") ghz = prot.make_ghz_expedient(4) ghz_ideal = prot_perf.make_ghz_expedient(4) print((ghz_ideal * ghz * ghz_ideal).tr()) print("-----------P SUCCESS SINGLE SELECTION----------") rho = prot.generate_bell_pair() print("Fidelity: ", qt.fidelity(rho, qt.bell_state('00'))) # Generate raw bell pair rho = qt.tensor(rho, prot.generate_bell_pair()) N = len(rho.dims[0]) # Apply two qubit gates CNOT = qt.cnot(N, 2, 0) * qt.cnot(N, 3, 1) rho = CNOT * rho * CNOT.dag() p = ps.single_sel(rho, N, [2, 3]) def p_ref(f): return (f**2 + 2 * f * (1 - f) / 3 + 5 * ((1 - f) / 3)**2) print("p: ", p) print("p_ref: ", p_ref(.9)) print("-----------P SUCCESS DOUBLE SELECTION----------") rho = prot.generate_bell_pair() # Generate raw bell pair
def CX(self, control, target): self.state = cnot(self.qubits, control, self.qubits - 1 - target) * self.state
def cnot(self, target : Qubit): # <1> self.parent._apply( qt.cnot(2, 0, 1), self.qubit_id, target.qubit_id )
def cnot(self, target: Qubit) -> None: self.parent._apply(qt.cnot(), [self.qubit_id, target.qubit_id])
def evolute(state): return qt.snot(N=3, target=0)*qt.cnot(N=3, control=0, target=1) * state
+ qt.bell_state('11') * qt.bell_state('11').dag() W = F * a + (1 - F) / 3. * b H = qt.snot(2, 1) return H * W * H.dag() def generate_werner(F): a = qt.bell_state('00') a = a * a.dag() return F * a + (1 - F) / 4. * qt.qeye(4) Fi = .9 State_initial = generate_noisy_pair(Fi) State = qt.tensor(State_initial, State_initial) CNOT = qt.cnot(4, 0, 2) * qt.cnot(4, 3, 1) State = CNOT * State * CNOT.dag() H = qt.snot(4, 1) * qt.snot(4, 3) State = H * State * H.dag() m1, State_collapsed1 = operations.measure_single(State, 4, 2) m2, State_collapsed = operations.measure_single(State_collapsed1, 3, 2) print(m1, m2) State_final = qt.snot(2, 1) * State_collapsed * qt.snot(2, 1).dag() State_ref = qt.snot(2, 1) * qt.bell_state('00') State_ref = State_ref * State_ref.dag() # initial Fidelity
import qutip as qt base = qt.cnot() state = qt.tensor(base, qt.qeye(2)) print(state) plist = [0, 1, 2] print(plist) print(state.permute(plist)) plist = [1, 0, 2] print(plist) print(state.permute(plist)) plist = [0, 2, 1] print(plist) print(state.permute(plist)) plist = [1, 2, 0] print(plist) print(state.permute(plist)) plist = [2, 0, 1] print(plist) print(state.permute(plist)) plist = [2, 1, 0] print(plist) print(state.permute(plist))
F = F / (F1 * F2 + F1 * (1 - F2) / 3 + F2 * (1 - F1) / 3 + 5 * (1 - F1) * (1 - F2) / 9) return F ### Purification protocols for psi print("--------------------PSI--------------------") ref = qt.bell_state('10') ref2 = qt.bell_state('11') rho_i = errs.bell_pair_phi(p) print("Initial F: ", qt.fidelity(ref, rho_i)**2) rho_i = qt.tensor(rho_i, rho_i) # Apply two_qubit_gates CNOT1 = qt.cnot(4, 2, 0) CNOT2 = qt.cnot(4, 3, 1) GATE = CNOT1 * CNOT2 # CPHASE1 = qt.cphase(np.pi, 4, 0, 2) # CPHASE2 = qt.cphase(np.pi, 4, 1, 3) # GATE = CPHASE1 * CPHASE2 rho = GATE * rho_i * GATE.dag() p1, rho = ops.forced_measure_single_Xbasis(rho, 4, 2, 0, True) print("p1: ", p1) p2, rho = ops.forced_measure_single_Xbasis(rho, 3, 2, 0, True) print("p2: ", p2, p_ref(1 - p)) print("F: ", qt.fidelity(ref, rho)**2, single_selection(1 - p, 1 - p)) print("--------------------") print(qt.fidelity(ref, rho)**2)
def as_qobj_operator(self, instance: "GateInstance") -> qutip.Qobj: return qutip.cnot()
### 1Qubit operators, basis b_1q_pauli = [X, Y, Z, I] b_1q_comput = arr2lqo(np.sqrt(2) * np.eye(4)) zero1, one1 = basis(2, 0), basis(2, 1) plus1, minus1 = 1 / np.sqrt(2) * (zero1 + one1), 1 / np.sqrt(2) * (zero1 - one1) p_1q_naive_unnormed = [I + Z, I - Z, I + X, I - X] p_1q_nielsen_unnormed = [I, I + X, I + Y, I + Z] p_1q_naive = [norm_dm(p) for p in p_1q_naive_unnormed] p_1q_nielsen = [norm_dm(p) for p in p_1q_nielsen_unnormed] ### 2 Qubits #orthonorm basis V = cnot() #B = np.eye(16) * 4 b_2q_pauli = [tensor(p[0], p[1]) for p in it.product(b_1q_pauli, b_1q_pauli)] b_2q_comput = arr2lqo(np.eye(16) * 2) b = b_2q_pauli B = lqo2arr(b) W = lqo2arr([V * b_el * V.dag() for b_el in b]) #input states p_2q_nielsen = [ tensor(p[0], p[1]) for p in it.product(p_1q_nielsen, p_1q_nielsen) ] p_2q_naive = [tensor(p[0], p[1]) for p in it.product(p_1q_naive, p_1q_naive)] P2q_nielsen = lqo2arr(p_2q_nielsen) P2q_naive = lqo2arr(p_2q_naive)
def add_cnots(control,targets,state,N): """adds a multi cnot gate by decomposition into single cnots""" for t in targets: state = qt.cnot(N=N,control=control[0],target=t)*state return
def main(): d = 4 qubits = 2 n = 2**qubits th = uniform(0, 2 * np.pi) rotate = tensor_fix(qt.tensor(id2, qt.ry(th))) rotate = tensor_fix(qt.tensor(rotate, id2)) """ state_creator=[rotate*hadamaker(qubits,[1]),qt.cnot(qubits,1,2),qt.cnot(qubits,0,1),hadamaker(qubits,[0]),qt.cnot(qubits,1,2),conv_cz()] state_creator_tags=["Hadamard","CNOT","CNOT2","Hadamard2","CNOT3","Control Z"] circuit=[] for i in range(len(state_creator)): circuit.append(state_creator[i]) circuit.append(state_creator_tags[i]) alt=[] for i in range(len(circuit)): if type(circuit[i]) == str: continue else: alt.append(gate_troubleshooter(circuit[i],n)) """ ghzcirc = [hadamaker(qubits, [0]), qt.cnot(qubits, 0, 1)] ghz_tags = ["Hadamard", "CNOT"] circuit = [] for i in range(len(ghzcirc)): circuit.append(ghzcirc[i]) circuit.append(ghz_tags[i]) #cat=categorize(circuit) alt = [] #angles=[] for i in range(len(circuit)): if type(circuit[i]) == str: continue else: alt.append(gate_troubleshooter(circuit[i], n)) choice = [2, 4, 5, 6] vector_name = ['new', 'QFT', 'Hadamard 2', 'Fourier State'] #ideals=[] tolerance = input("Give a tolerance: ") tolerance = float(tolerance) vectors = gen_basis_vectors(n, n, 5) ideal = get_ideal(alt, vectors, qubits, d) print(vector_name[i]) print(ideal[0]) ideal = [ 0.7803300858899107, 0.7803300858899107, 0.7803300858899107, 0.7803300858899107 ] #ideals.append(ideal[0]) path = input( "Give csv file location, remembering to use forward slashes: ") KNN(path, 0.8, 5, tolerance, ideal) """ tolerance=0.9 for i in range(10): multi=uniform(0,1) ideal2=ideal[0] probvector=[] for x in range(len(ideal2)): probvector.append(multi*ideal2[x]) truth=within_tolerance(tolerance,probvector,ideal[0]) print(multi) print(truth) """ return 0
def add_cnots(control, targets, state, N): """adds a multi cnot gate by decomposition into single cnots""" for t in targets: state = qt.cnot(N=N, control=control[0], target=t) * state return
def main(): pop = input("How many of each gate do you want to populate? ") pop = int(pop) split = input( "Give training set split, in the form of a number between 0 and 1: ") k = input("Give a k value: ") k = int(k) d = input("Gimme a range of reference states: ") d = int(d) qubits = 3 n = 2**qubits csvpath = [ "WTrainingData2000new.csv", "WTrainingData2000QFT.csv", "WTrainingData2000Had.csv", "WTrainingData2000QFT2.csv" ] r1 = tensor_fix(qt.tensor(qt.ry(-1.23096), id2)) r1 = tensor_fix(qt.tensor(r1, id2)) r2 = tensor_fix(qt.tensor(qt.ry(np.pi / 4), id2)) r2 = tensor_fix(qt.tensor(r2, id2)) r3 = tensor_fix(qt.tensor(qt.ry(-1 * np.pi / 4), id2)) r3 = tensor_fix(qt.tensor(r3, id2)) state_creator = [ r1, paulix(3, 1), paulix(3, 2), qt.cnot(3, 0, 1), r2, qt.cnot(3, 1, 0), r3, paulix(3, 0), paulix(3, 1), qt.cnot(3, 0, 2), qt.cnot(3, 1, 2) ] state_creator_tags = [ "Rotation", "X", "X2", "CNOT", "Rotation2", "CNOT2", "Rotation3", "X3", "X4", "CNOT3", "CNOT4" ] circuit = [] angles = [] for i in range(len(state_creator)): circuit.append(state_creator[i]) circuit.append(state_creator_tags[i]) cat = categorize(circuit) alt = [] angles = [] for i in range(len(circuit)): if type(circuit[i]) == str: continue else: alt.append(gate_troubleshooter(circuit[i], n)) choice = [2, 4, 5, 6] vector_name = ['new', 'QFT', 'Hadamard 2', 'Fourier State'] index = 0 for x in choice: choice = x path = csvpath[index] vectors = gen_basis_vectors(n, n, choice) print(vector_name[index]) index = index + 1 probs = alter_wcirc(alt, angles, vectors, pop, cat, qubits, d, path) KNN(probs, split, k) return 0
from qutip import sigmax, sigmay, sigmaz, identity, tensor, basis, ket2dm, Qobj, cnot, hadamard_transform import qutip import itertools as it ## Shortcuts of some main qutip objects zero = qt.qubits.qubit_states(1, [0]) one = qt.qubits.qubit_states(1, [1]) I, X, Y, Z = qt.identity([2]), qt.sigmax(), qt.sigmay(), qt.sigmaz() Rx, Ry, Rz = qt.rx, qt.ry, qt.rz op_pauli_1 = [X, Y, Z, I] s_zero_1, s_one_1 = basis(2, 0), basis(2, 1) s_plus_1, s_minus_1 = 1 / np.sqrt(2) * (s_zero_1 + s_one_1), 1 / np.sqrt(2) * ( s_zero_1 - s_one_1) #two qubits CN = cnot() HDM = hadamard_transform() # =========================================================================== # # Define the functions needed # =========================================================================== # # GHZ related functions def get_ghz(nb_qubits, angle=0): """ Generate a GHZ state of the form |00..00> + exp(i * angle) |11..11> """ a = tensor([zero for _ in range(nb_qubits)]) b = tensor([one for _ in range(nb_qubits)]) return 1 / np.sqrt(2) * (a + np.exp(1.0j * angle) * b) def get_ghz_offdiag(nb_qubits):
Sy = sigmay() Sz = sigmaz() Si = 0.5 * identity(2) H_d = 0.5 * (tensor(Sx, Sx) + tensor(Sy, Sy) + tensor(Sz, Sz) ) # Drift Hamiltonian H_c = [tensor(Sx, Si), tensor(Sy, Si), tensor(Si, Sx), tensor(Si, Sy)] # The (four) control Hamiltonians #H_d = (tensor(Sz, Si) + tensor(Si, Sz)) # Drift Hamiltonian #H_c = [tensor(Sz, Sz), tensor(Sx, Si) + tensor(Si, Sx)] # The (four) control Hamiltonians n_ctrls = len(H_c) U_0 = identity(4) #start U_targ = cnot() # tget ## Defining pulse # Duration of each timeslot dt = 0.05 # List of evolution times to try evo_times = [1.9, 1.95, 2.] n_evo_times = len(evo_times) evo_time = evo_times[0] n_ts = 2 #int(float(evo_time) / dt) results = list() ### OPTIMIZATION fid_err_targ = 1e-5 # Fidelity error target max_iter = 500 # Maximum iterations for the optisation algorithm max_wall_time = 120 # Maximum (elapsed) time allowed in seconds
def Rz(angle): return qt.rz(angle) def R(axis, angle): angle = np.remainder(angle, 2 * np.pi) if not (type(axis) is np.ndarray): axis = np.array(axis) axis = axis / np.linalg.norm(axis) return qt.Qobj(np.cos(angle / 2) * I - 1j * np.sin(angle / 2) * (axis[0] * X + axis[1] * Y + axis[2] * Z)) def Phase(angle): return qt.phasegate(angle) # 2 qubit gates CNOT = qt.cnot() CZ = qt.csign() Berkeley = qt.berkeley() SWAP = qt.swap() iSWAP = qt.iswap() SQSWAP = qt.sqrtswap() SQiSWAP = qt.sqrtiswap() def aSWAP(angle): return qt.swapalpha(angle) # 3 qubit gates Fredkin = qt.fredkin() Toffoli = qt.toffoli()