def osciallating_param_costs(): U1, U2, U1_, U2_ = [unitary_group.rvs(4).reshape(2,2,2,2) for _ in range(4)] RE = RightEnvironment() params = np.random.rand(6) C = CircuitSolver() for i in range(len(params)): Ms = [] M_s = [] for p in np.linspace(0,np.pi*2, 200): params[i] = p M = C.M(params) M_ = RE.circuit(U1, U2, U1_, U2_, M) Ms.append(M.reshape(4,)) M_s.append(M_.reshape(4,)) scores = np.linalg.norm(np.array(Ms) - np.array(M_s), axis = 1) plt.plot(scores, label = f"{i}") plt.legend() plt.show()
def circuit_ansatz(params, wires): """Circuit ansatz containing all the parametrized gates""" qml.QubitStateVector(unitary_group.rvs(2**4, random_state=0)[0], wires=wires) qml.RX(params[0], wires=wires[0]) qml.RY(params[1], wires=wires[1]) qml.RX(params[2], wires=wires[2]).inv() qml.RZ(params[0], wires=wires[3]) qml.CRX(params[3], wires=[wires[3], wires[0]]) qml.PhaseShift(params[4], wires=wires[2]) qml.CRY(params[5], wires=[wires[2], wires[1]]) qml.CRZ(params[5], wires=[wires[0], wires[3]]).inv() qml.PhaseShift(params[6], wires=wires[0]).inv() qml.Rot(params[6], params[7], params[8], wires=wires[0]) # # qml.Rot(params[8], params[8], params[9], wires=wires[1]).inv() qml.MultiRZ(params[11], wires=[wires[0], wires[1]]) # # qml.PauliRot(params[12], "XXYZ", wires=[wires[0], wires[1], wires[2], wires[3]]) qml.CPhase(params[12], wires=[wires[3], wires[2]]) qml.IsingXX(params[13], wires=[wires[1], wires[0]]) qml.IsingXY(params[14], wires=[wires[3], wires[2]]) qml.IsingYY(params[14], wires=[wires[3], wires[2]]) qml.IsingZZ(params[14], wires=[wires[2], wires[1]]) qml.U1(params[15], wires=wires[0]) qml.U2(params[16], params[17], wires=wires[0]) qml.U3(params[18], params[19], params[20], wires=wires[1]) # # qml.CRot(params[21], params[22], params[23], wires=[wires[1], wires[2]]).inv() # expected tofail qml.SingleExcitation(params[24], wires=[wires[2], wires[0]]) qml.DoubleExcitation(params[25], wires=[wires[2], wires[0], wires[1], wires[3]]) qml.SingleExcitationPlus(params[26], wires=[wires[0], wires[2]]) qml.SingleExcitationMinus(params[27], wires=[wires[0], wires[2]]) qml.DoubleExcitationPlus(params[27], wires=[wires[2], wires[0], wires[1], wires[3]]) qml.DoubleExcitationMinus(params[27], wires=[wires[2], wires[0], wires[1], wires[3]]) qml.RX(params[28], wires=wires[0]) qml.RX(params[29], wires=wires[1])
def test_unitary_qsd_4qubits(self): u = unitary_group.rvs(16) gate = unitary(u, 'qsd') state = get_state(gate) self.assertTrue(np.allclose(u[:, 0], state)) circuit = qiskit.QuantumCircuit(4) circuit.x(0) circuit.append(gate, circuit.qubits) state = get_state(circuit) self.assertTrue(np.allclose(u[:, 1], state)) circuit = qiskit.QuantumCircuit(4) circuit.x(1) circuit.append(gate, circuit.qubits) state = get_state(circuit) self.assertTrue(np.allclose(u[:, 2], state)) circuit = qiskit.QuantumCircuit(4) circuit.x([0, 1, 2, 3]) circuit.append(gate, circuit.qubits) state = get_state(circuit) self.assertTrue(np.allclose(u[:, 15], state))
def random_unitary_matrix(dim, seed): rng = np.random.RandomState(seed) return unitary_group.rvs(dim, random_state=rng)
def random_unitary(self): return circuit.Unitary(1, unitary_group.rvs(2))
def __init__(self, nbqubitinput, arity, length, name, learningrate=0, momentum=0, start=0): super().__init__(nbqubitinput, name) init = tf.orthogonal_initializer self.arity = arity size = 1 << arity #real = tf.get_variable(name+"w",[size,size],initializer=init) #real= tf.multiply(1.0/tf.sqrt(2.0),tf.eye(size, dtype="float32")) #imag = tf.multiply(1.0/tf.sqrt(2.0),tf.eye(size, dtype="float32")) #param=tf.complex(real,imag) param = tf.convert_to_tensor(unitary_group.rvs(size), dtype='complex64') paramdagger = tf.transpose(param, conjugate=True) for y in range(start, length): if (y % 2 == 0): for x in range(0, nbqubitinput // arity): with tf.variable_scope(name + "row" + str(y) + "gate" + str(x)): gate = genericQGate.genericQGate( param, nbqubitinput, arity, x * arity, learningrate, momentum) self.gatelist.append(gate) leftover = nbqubitinput % arity pos = nbqubitinput - leftover if (pos < nbqubitinput): with tf.variable_scope(name + "row" + str(y) + "gate" + str(pos)): size = 1 << leftover real = tf.get_variable("v", [size, size], initializer=init) #real = tf.eye(size, dtype="float32") imag = tf.zeros_like(real) param_l = tf.complex(real, imag) gate = genericQGate.genericQGate( param_l, nbqubitinput, leftover, pos, learningrate, momentum) self.gatelist.append(gate) else: with tf.variable_scope(name + "row" + str(y) + "gate0"): real = [[1 / tf.sqrt(2.0), 1 / tf.sqrt(2.0)], [1 / tf.sqrt(2.0), -1 / tf.sqrt(2.0)]] imag = [[0.0, 0.0], [0.0, 0.0]] hadamard = tf.complex(real, imag) gate = genericQGate.genericQGate(hadamard, nbqubitinput, 1, 0, learningrate, momentum) self.gatelist.append(gate) for x in range(0, (nbqubitinput - 1) // arity): with tf.variable_scope(name + "row" + str(y) + "gate" + str(x + 1)): gate = genericQGate.genericQGate( paramdagger, nbqubitinput, arity, 1 + x * arity, learningrate, momentum) self.gatelist.append(gate) leftover = (nbqubitinput - 1) % arity pos = nbqubitinput - leftover if (pos < nbqubitinput): with tf.variable_scope(name + "row" + str(y) + "gate" + str(pos)): size = 1 << leftover real = tf.get_variable("v", [size, size], initializer=init) #real = tf.eye(size, dtype="float32") imag = tf.zeros_like(real) param_l = tf.complex(real, imag) gate = genericQGate.genericQGate( param_l, nbqubitinput, leftover, pos, learningrate, momentum) self.gatelist.append(gate)
def create_random_unitary(n): return unitary_group.rvs(2**n)
def test_compare_unitary(self): # Given U1 = unitary_group.rvs(4) U2 = unitary_group.rvs(4) # When/Then self.assertFalse(compare_unitary(U1, U2))
"""This script is contains a simple use case of the QFAST synthesis method.""" from __future__ import annotations import logging from scipy.stats import unitary_group from bqskit.compiler import CompilationTask from bqskit.compiler import Compiler from bqskit.compiler.passes.synthesis import QFASTDecompositionPass from bqskit.ir import Circuit if __name__ == '__main__': # Enable logging logging.getLogger('bqskit').setLevel(logging.DEBUG) # Let's create a random 3-qubit unitary to synthesize and add it to a # circuit. circuit = Circuit.from_unitary(unitary_group.rvs(8)) # We will now define the CompilationTask we want to run. task = CompilationTask(circuit, [QFASTDecompositionPass()]) # Finally let's create create the compiler and execute the CompilationTask. with Compiler() as compiler: compiled_circuit = compiler.compile(task) for op in compiled_circuit: print(op)
return res def dispatch(nb_meas, probas, rule='rdm'): assert np.allclose(np.sum(probas), 1.) if rule == 'rdm': samples = np.random.choice(len(probas), nb_meas, p = probas) meas = [np.sum(samples == i) for i in range(len(probas))] else: meas = [int(p* nb_meas) for p in probas] return np.array(meas) # =========================================================================== # # Testing the different measurement schemes # =========================================================================== # Target = ut.HDM nb_meas = 1000 U = unitary_group.rvs(2, 1000) u = [qt.Qobj(U_el, dims = [[2],[2]]) for U_el in U] real_fid = np.array([ut.fid_perfect(unit, Target) for unit in u]) # Standard scheme sch1 = produce_schemes_1q('strat1')(Target) sch1_fid_perfect = np.array([measure_fid(unit, *sch1) for unit in u]) sch1_fid_limited = np.array([measure_fid(unit, *sch1, nb_meas = nb_meas) for unit in u]) sch1_smart = produce_schemes_1q('strat1_smart')(Target) sch1_smart_perfect = np.array([measure_fid(unit, *sch1_smart) for unit in u]) sch1_smart_limited = np.array([measure_fid(unit, *sch1_smart, nb_meas = nb_meas) for unit in u]) sch1_diag = produce_schemes_1q('diag')(Target) sch1_diag_perfect = np.array([measure_fid(unit, *sch1_diag) for unit in u])
description='Configuration for decomposition', add_help=True) parser.add_argument('--num_qubits', '-n', type=int, default=2, help="Number of qubits") parser.add_argument('--qasm_output', '-q', type=store_true, help="Conversion to QASM format") args = parser.parse_args() print('Current directory: ', os.getcwd()) num_bits = args.num_qubits print("Initializing random unitary U ..., num_qubits: ", num_bits) init_unitary_mat = unitary_group.rvs(2**num_bits) emb = CktEmbedder(num_bits, num_bits) file_prefix = "decomposition_demo" t = Tree(True, file_prefix, emb, init_unitary_mat, verbose=False) t.close_files() # The above code automatically creates an expansion of $U$ # into DIAG and MP_Y lines. Next we print the Picture file that was created. file = './qubiter/quantum_CSD_compiler/' + file_prefix + "_2_ZLpic.txt" df = pd.read_csv(file, delim_whitespace=True, header=None) style = "exact" xer = MultiplexorExpander(file_prefix, num_bits, style, verbose=False) xer = DiagUnitaryExpander(file_prefix + "_X1", num_bits, style) xer = MultiplexorExpander(file_prefix + "_X2",
# The next two lines start qfactor's logger. import logging logging.getLogger("qfactor").setLevel(logging.INFO) # We will optimize towards the toffoli unitary. toffoli = np.array([[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]]) # Start with the circuit structure # and an initial guess for the gate's unitaries. # Here we use randomly generated unitaries for initial guess. circuit = [ Gate(unitary_group.rvs(4), (1, 2)), Gate(unitary_group.rvs(4), (0, 2)), Gate(unitary_group.rvs(4), (1, 2)), Gate(unitary_group.rvs(4), (0, 2)), Gate(unitary_group.rvs(4), (0, 1)) ] # Note: the Gate object also has an optional boolean parameter "fixed" # If "fixed" is set to true, that gate's unitary will not change. # Call the optimize function ans = optimize( circuit, toffoli, # <--- These are the only required args diff_tol_a=1e-12, # Stopping criteria for distance change diff_tol_r=1e-6, # Relative criteria for distance change
""" ket_input = [] ket_output = [] for i in range(m): ket_input.append(jnp.array(rand_ket(d, seed=300).full())) # Output data -- action of unitary on a ket states ket_output.append(jnp.dot(tar_unitr, ket_input[i])) return (ket_input, ket_output) m = 100 # number of training data points N = 8 # Dimension of the unitary to be learnt train_len = int(m * 0.8) # tar_unitr gives a different unitary each time tar_unitr = jnp.asarray(unitary_group.rvs(N)) ket_input, ket_output = make_dataset(m, N) # ## Cost Function # # We use the same cost function as the authors # [Seth Lloyd and Reevu Maity, 2020](https://arxiv.org/pdf/1901.03431.pdf) # define # # $\begin{equation} \label{err_ps} # E = 1 - (\frac{1}{M})\sum_{i} \langle \psi_{i}|U^{\dagger} U(\vec{\theta}, \vec{\phi}, \vec{\omega})|\psi_{i}\rangle # \end{equation}$, # # where $ |\psi_{i} \rangle$ is the training (or testing) # data points -- in this case, kets, $U$ and # $U(\vec{\theta}, \vec{\phi}, \vec{\omega})$ are the target and
scores = [] for p in x: scores.append(np.linalg.norm(p * M - M_)) coefs = Polynomial.fit(x[:10],scores[:10],deg = 2, domain = (1,0.9)) new_vals = [coefs(a) for a in x] plt.plot(x, scores, label = "Exact") plt.plot(x, new_vals, label = "Poly Fit") plt.legend() plt.show() if __name__ == "__main__": ################ # Set up a random environment calculation U1, U2, U1_, U2_ = [unitary_group.rvs(4).reshape(2,2,2,2) for _ in range(4)] RE = RightEnvironment() R = Represent() R.U1 = U1 R.U2 = U2 R.U1_ = U1_ R.U2_ = U2_ ############### # Demonstrate the sinusoidal cost Function params = np.random.rand(6) C = CircuitSolver() params = [1] + list(np.random.rand(6)) CostFuncs = [] x = np.linspace(0,2*np.pi, 200)
def test_hermitian(): u = unitary_group.rvs(3) return Operator.is_hermitian(u)
def test_unitarity(): u = unitary_group.rvs(3) return Operator.is_unitary(u)
num_orbitals=2, num_spins=2, nw=400, ntau=801, ) up, do = '0', '1' p.spin_names = [up, do] p.orb_names = range(p.num_orbitals) # -- Unitary transform if False: from scipy.stats import unitary_group, ortho_group np.random.seed(seed=233423) # -- Reproducible "randomness" p.T = unitary_group.rvs(4) # General complex unitary transf #p.T = np.kron(ortho_group.rvs(2), np.eye(2)) # orbital only rotation # use parametrized "weak" realvalued 4x4 transform p.T = unitary_transf_4x4(t_vec=[0.3, 0.3, 0.3, 0.0, 0.0, 0.0]) #p.T = unitary_transf_4x4(t_vec=[0.25*np.pi, 0.0, 0.0, 0.0, 0.0, 0.0]) #p.T = np.eye(4) p.T = np.matrix(p.T) print p.T # -- Different types of operator sets p.op_imp = [c('0', 0), c('0', 1), c('0', 2), c('0', 3)] p.op_full = p.op_imp + [c('1', 0), c('1', 1), c('1', 2), c('1', 3)] p.spin_block_ops = [c('0', 0), c('1', 0), c('0', 1), c('1', 1)]
def test_passive_channel(self, M, setup_eng, tol): """check that passive channel is consistent with unitary methods""" U = unitary_group.rvs(M) loss_in = np.random.random(M) loss_out = np.random.random(M) T = (np.sqrt(loss_in) * U) * np.sqrt(loss_out[np.newaxis].T) eng, prog = setup_eng(M) with prog.context as q: for i in range(M): ops.Sgate(1) | q[i] ops.Dgate(A) | q[i] ops.PassiveChannel(T) | q state = eng.run(prog).state cov1 = state.cov() mu1 = state.means() eng, prog = setup_eng(M) with prog.context as q: for i in range(M): ops.Sgate(1) | q[i] ops.Dgate(A) | q[i] ops.LossChannel(loss_in[i]) | q[i] ops.Interferometer(U) | q for i in range(M): ops.LossChannel(loss_out[i]) | q[i] state = eng.run(prog).state cov2 = state.cov() mu2 = state.means() assert np.allclose(cov1, cov2, atol=tol, rtol=0) assert np.allclose(mu1, mu2, atol=tol, rtol=0) u, s, v = np.linalg.svd(T) eng, prog = setup_eng(M) with prog.context as q: for i in range(M): ops.Sgate(1) | q[i] ops.Dgate(A) | q[i] ops.Interferometer(v) | q for i in range(M): ops.LossChannel(s[i]**2) | q[i] ops.Interferometer(u) | q state = eng.run(prog).state cov3 = state.cov() mu3 = state.means() assert np.allclose(cov1, cov3, atol=tol, rtol=0) assert np.allclose(mu1, mu3, atol=tol, rtol=0) T1 = u * s eng, prog = setup_eng(M) with prog.context as q: for i in range(M): ops.Sgate(1) | q[i] ops.Dgate(A) | q[i] ops.PassiveChannel(v) | q ops.PassiveChannel(T1) | q state = eng.run(prog).state cov4 = state.cov() mu4 = state.means() assert np.allclose(cov1, cov4, atol=tol, rtol=0) assert np.allclose(mu1, mu4, atol=tol, rtol=0)
def main(): # input_dict = input_reader('input.txt') # n_qubits = input_dict['n_qubits'] # max_ebits = ceil(n_qubits/2) # n_instances = input_dict['n_instances'] # method = input_dict['method'] n_qubits = int(input("Enter the number of qubits: ")) max_ebits = ceil(n_qubits / 2) n_instances = int( input("Enter the number of random unitaries to average over: ")) method = str( input( "Enter the name of an optimization method. The supported ones are: \n\tNelder-Mead \n\tBFGS \n\tL-BFGS-B \n\tPowell \n\tSLSQP \n\tTNC \n Please choose one" )) unitaries = [unitary_group.rvs(2**n_qubits) for i in range(n_instances)] fun_values = [[0]] * max_ebits overlaps = [[0]] * max_ebits entropies = [[0]] * max_ebits start_time = time.time() for p in range(n_instances): print('Iteration', p + 1) initial_state_vec = np.array([1] + [0] * (2**n_qubits - 1)) for ebits in range(1, max_ebits + 1): print('\t Ebits in MPS:', ebits) local_time = time.time() state_tensor_network = [] for n in range(n_qubits - ebits): target_qubits = [(i + n) for i in range(ebits + 1)] state_tensor_network = state_tensor_network + hea_ansatz_eff( n_qubits, ebits, target_qubits) for i in range(len(state_tensor_network)): state_tensor_network[i]['block_number'] = i n_pars = len( extract_parameters_from_tensor_network(state_tensor_network)) update_tensor_network(state_tensor_network, [0 for i in range(n_pars)]) result = approximate_mps_qiskit(n_qubits, initial_state_vec, state_tensor_network, unitaries[p], method) l = len(result[0]) k = ebits - 1 fun_values[k] = np.concatenate( (fun_values[k], [fun_values[k][-1]] * (l - len(fun_values[k])))) new_fun_values = np.concatenate( (result[0], [result[0][-1]] * (len(fun_values[k]) - l))) fun_values[k] = np.array(fun_values[k]) + np.array(new_fun_values) overlaps[k] = np.concatenate( (overlaps[k], [overlaps[k][-1]] * (l - len(overlaps[k])))) new_overlaps = np.concatenate( (result[1], [result[1][-1]] * (len(overlaps[k]) - l))) overlaps[k] = np.array(overlaps[k]) + np.array(new_overlaps) entropies[k] = np.concatenate( (entropies[k], [entropies[k][-1]] * (l - len(entropies[k])))) new_entropies = np.concatenate( (result[2], [result[2][-1]] * (len(entropies[k]) - l))) entropies[k] = np.array(entropies[k]) + np.array(new_entropies) initial_state_vec = result[4] print('\t\t Completed in', time.time() - local_time) verts = [0] for line in fun_values: verts.append(verts[-1] + len(line)) # verts.pop(-1) fun_values_flat = np.array([]) for line in fun_values: fun_values_flat = np.concatenate((fun_values_flat, line)) fun_values_flat = fun_values_flat / n_instances overlaps_flat = np.array([]) for line in overlaps: overlaps_flat = np.concatenate((overlaps_flat, line)) overlaps_flat = overlaps_flat / n_instances entropies_flat = np.array([]) for line in entropies: entropies_flat = np.concatenate((entropies_flat, line)) entropies_flat = entropies_flat / n_instances print('Completed in', time.time() - start_time) # write the data file = open('fun_values_flat.txt', 'w') for fun_value in fun_values_flat: file.write(str(fun_value) + '\n') file.close() file = open('overlaps_flat.txt', 'w') for overlap in overlaps_flat: file.write(str(overlap) + '\n') file.close() file = open('entropies_flat.txt', 'w') for entropy in entropies_flat: file.write(str(entropy) + '\n') file.close() # plot figsize = (10, 8) tickssize = 12 fontsize = 16 linewidth = 1 x_axis = list(range(len(fun_values_flat))) x_ticks = x_axis s = 0 k = len(fun_values_flat) fig = plt.figure(figsize=figsize) gs = gridspec.GridSpec(3, 1, height_ratios=[1, 1, 1]) ax0 = plt.subplot(gs[0]) # ax0.plot(x_axis[s:k], 1 - fun_values_flat[s:k], color='tab:red', linewidth=2.5) ax0.hlines(y=0, xmin=s, xmax=k, colors='black', linestyles='solid') ax0.hlines(y=1, xmin=s, xmax=k, colors='green', linestyles='dashed') for v in verts: ax0.vlines(x=v, ymin=0, ymax=1.1, linestyles='solid', linewidth=1) ax0.set_ylabel('Function value', fontsize=fontsize) ax0.set_xlim(s, k) ax0.set_ylim(0, 1.1) ax0.grid() plt.xticks(fontsize=0) plt.yticks(fontsize=tickssize) ax1 = plt.subplot(gs[1]) plt.plot(x_axis[s:k], overlaps_flat[s:k], color='tab:blue', linewidth=2.5) ax1.hlines(y=0, xmin=s, xmax=k, colors='black', linestyles='solid') ax1.hlines(y=1, xmin=s, xmax=k, colors='green', linestyles='dashed') for v in verts: ax1.vlines(x=v, ymin=0, ymax=1.1, linestyles='solid', linewidth=1) ax1.set_ylabel('Overlap', fontsize=fontsize) ax1.hlines(y=0, xmin=x_axis[s:][0], xmax=x_axis[s:][-1], colors='black', linestyles='solid') ax1.hlines(y=1, xmin=x_axis[s:][0], xmax=x_axis[s:][-1], colors='green', linestyles='dashed') ax1.set_xlim(s, k) ax1.set_ylim(0, 1.1) ax1.grid() plt.xticks(fontsize=0) plt.yticks(fontsize=tickssize) ax2 = plt.subplot(gs[2], sharex=ax1) plt.setp(ax1.get_xticklabels(), visible=False) ax2.plot(x_axis[s:k], entropies_flat[s:k], color='purple', linewidth=2.5) ax2.hlines(y=0, xmin=s, xmax=k, colors='black', linestyles='solid') for v in verts: ax2.vlines(x=v, ymin=0, ymax=max_ebits + 0.4, linestyles='solid', linewidth=1) ax2.set_xlabel('Iterations', fontsize=fontsize) ax2.set_ylabel('Entanglement', fontsize=fontsize) ax2.hlines(y=0, xmin=x_axis[s:][0], xmax=x_axis[s:][-1], colors='black', linestyles='solid') for r in range(1, max_ebits + 1): ax2.hlines(y=r, xmin=verts[r - 1], xmax=verts[r], colors='green', linestyles='dashed') ax2.set_xlim(s, k) ax2.set_ylim(0, max_ebits + 0.4) ax2.grid() plt.xticks(fontsize=tickssize) plt.yticks(fontsize=tickssize) plt.subplots_adjust(hspace=0) plt.savefig('plot-' + str(n_qubits) + 'q-' + str(max_ebits) + 'l-' + str(n_instances) + 'i-' + method + '.pdf', bbox_inches='tight')
def test_is_unitary(self): # Given U = unitary_group.rvs(4) # When/Then self.assertTrue(is_unitary(U))
def test_optimize_fixed(self): u1 = unitary_group.rvs(8) g1 = Gate(u1, (0, 1, 2)) circ = optimize([g1], u1) self.assertTrue(np.allclose(circ[0].utry, g1.utry))
# Obtain the single qubit unitaries Gs, Rs = decompose_uniformly_controlled_unitaries(unitaries) assert len(Gs) == 2**n # Return the result return fill_uniformly_controlled_circuit(Gs, cqs, tq), Rs if __name__ == "__main__": from scipy.stats import unitary_group from pyquil.quil import Pragma import itertools as it np.set_printoptions(linewidth=200) n = 2 unitaries = [unitary_group.rvs(2) for _ in range(2**n)] qubits = list(range(n + 1)) program = pq.Program() UCC, R = generate_uniformly_controlled_circuit(unitaries, qubits[:n], qubits[-1]) program += UCC print("program:") print(program) print("Phases:") print(R) exit() # Correct indexing mess corrected_U = np.empty(U.shape, dtype=np.complex_) for i, j in it.product(range(2**(n + 1)), repeat=2):
def random_unitary_matrix(dim: int, seed: int): rng = np.random.RandomState(seed) return unitary_group.rvs(dim, random_state=rng)
def test_mixed_polarity_controls(self, control_wires, wires, control_values): """Test if ControlledQubitUnitary properly applies mixed-polarity control values.""" target_wires = Wires(wires) dev = qml.device("default.qubit", wires=len(control_wires + target_wires)) # Pick a random unitary U = unitary_group.rvs(2**len(target_wires), random_state=1967) # Pick random starting state for the control and target qubits control_state_weights = np.random.normal( size=(2**(len(control_wires) + 1) - 2)) target_state_weights = np.random.normal( size=(2**(len(target_wires) + 1) - 2)) @qml.qnode(dev) def circuit_mixed_polarity(): qml.templates.ArbitraryStatePreparation(control_state_weights, wires=control_wires) qml.templates.ArbitraryStatePreparation(target_state_weights, wires=target_wires) qml.ControlledQubitUnitary(U, control_wires=control_wires, wires=target_wires, control_values=control_values) return qml.state() # The result of applying the mixed-polarity gate should be the same as # if we conjugated the specified control wires with Pauli X and applied the # "regular" ControlledQubitUnitary in between. x_locations = [ x for x in range(len(control_values)) if control_values[x] == "0" ] @qml.qnode(dev) def circuit_pauli_x(): qml.templates.ArbitraryStatePreparation(control_state_weights, wires=control_wires) qml.templates.ArbitraryStatePreparation(target_state_weights, wires=target_wires) for wire in x_locations: qml.PauliX(wires=control_wires[wire]) qml.ControlledQubitUnitary(U, control_wires=control_wires, wires=wires) for wire in x_locations: qml.PauliX(wires=control_wires[wire]) return qml.state() mixed_polarity_state = circuit_mixed_polarity() pauli_x_state = circuit_pauli_x() assert np.allclose(mixed_polarity_state, pauli_x_state)
def random_unitary(qnum): dim = 2**qnum mat = unitary_group.rvs(dim) return mat
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 7 16:25:18 2019 @author: fred """ import matplotlib.pylab as plt from scipy.stats import unitary_group U = unitary_group.rvs(4, 100000) import numpy as np comput_basis = [np.array([1.,0.,0.,0.]), np.array([0.,1.,0.,0.]), np.array([0.,0.,1.,0.]), np.array([0.,0.,0.,1.])] state_basis = [np.array([1.,0.,0.,0.]), np.array([0.,1.,0.,0.]), np.array([0., 0., 1/np.sqrt(2), 1/np.sqrt(2)]),np.array([0.,0.,1.,0.]), np.array([0.,0.,0.,1.])] state_decompo = np.array([1,1,2,-1,-1]) cnot = np.array([[1.-0.j, 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 0., 1.], [0., 0., 1., 0.]]) def fid1(A, T= cnot): d = A.shape[0] f = np.square(np.abs(1/d * np.trace(np.transpose(np.conj(A)).dot(T)))) return f def fid_cheap(A, T=cnot, basis=comput_basis): ev_A = [A.dot(b) for b in basis] ev_T = [T.dot(b) for b in basis] f = np.average([np.square(np.abs(np.dot(np.conj(t), a))) for a, t in zip(ev_A, ev_T)]) return f
def gen_hermite(eig, compl=False): n = eig.shape[0] B = unitary_group.rvs(n) return B.T.conj() @ np.diag(eig) @ B
def test_cossin_error_missing_partitioning(): with pytest.raises(ValueError, match=".*exactly four arrays.* got 2"): cossin(unitary_group.rvs(2)) with pytest.raises(ValueError, match=".*might be due to missing p, q"): cossin(unitary_group.rvs(4))
if term > 0 and 1 / np.cosh(0.5 * term) < np.exp(-e**2 / (4 * K)): print("This experiment evades our algorithm!") return else: # sample from the output state mean = np.zeros([2 * M]) V = ClosestClassicalState(r, K, eta, U, tbar) import time t0 = time.time() x = np.random.multivariate_normal( mean, np.linalg.inv(V - tbar * np.identity(2 * M))) # sample from the measurement n = [ bernoulli.rvs(np.exp(-(x[i]**2 + x[i + 1]**2) / 4)) for i in range(len(x) - 1) ] print("{} sec".format(time.time() - t0)) return n r = 0.1 K = 4 eta = 0.088 U = unitary_group.rvs(12) etaD = 0.78 pD = 10**(-4) e = 0.023 n = sampleGBS(r, K, eta, U, etaD, pD, e) print(n)