def test_gaussian_copula_normal(self): """Test the Gaussian copula circuit against the normal case.""" mu = [0.1, 0.9] sigma = [[1, -0.2], [-0.2, 1]] num_qubits = [3, 2] bounds = [(-1, 1), (-1, 1)] def F(x, mean, std = 1): return norm.cdf(x, loc = mean, scale = std) def f(x, mean, std = 1): return norm.pdf(x, loc = mean, scale = std) cdfs = [lambda x:F(x, mu[0]), lambda x:F(x, mu[1])] pdfs = [lambda x:f(x, mu[0]), lambda x:f(x, mu[1])] normal = NormalDistribution(num_qubits, mu=mu, sigma=sigma, bounds=bounds) gc_normal = GaussianCopula(num_qubits, cdfs, sigma=sigma, bounds=bounds, pdfs = pdfs) sv_normal = Statevector.from_instruction(normal) sv_gc_normal = Statevector.from_instruction(gc_normal) np.testing.assert_array_almost_equal(sv_normal.data, sv_gc_normal.data)
def test_transpile(get_test_circuit, backend): # noqa """Test the transpiling using our backends Parameters ---------- get_test_circuit : callable pytest fixture for a simple quantum circuit backend : str name of the backend which is to be tested """ c3_qiskit = C3Provider() received_backend = c3_qiskit.get_backend(backend) trans_qc = transpile(get_test_circuit, received_backend) assert Statevector.from_instruction(get_test_circuit).equiv( Statevector.from_instruction(trans_qc))
def test_from_labels(self): """Initialize from labels.""" desired_sv = Statevector.from_label("01+-lr") qc = QuantumCircuit(6) qc.initialize("01+-lr", range(6)) actual_sv = Statevector.from_instruction(qc) self.assertTrue(desired_sv == actual_sv)
def run_circuit_and_tomography(circuit, qubits, method='lstsq'): psi = Statevector.from_instruction(circuit) qst = tomo.state_tomography_circuits(circuit, qubits) job = qiskit.execute(qst, Aer.get_backend('qasm_simulator'), shots=5000) tomo_fit = tomo.StateTomographyFitter(job.result(), qst) rho = tomo_fit.fit(method=method) return (rho, psi)
def statevector(self, include_final_measurements=False): """Return output statevector for the circuit. Parameters: include_final_measurements (bool): Include final measurements in the circuit. Returns: StateVector: Output statevector object. Example: .. jupyter-execute:: from qiskit import QuantumCircuit import kaleidoscope.qiskit qc = QuantumCircuit(3) qc.h(0) qc.cx(0, range(1,2)) qc.statevector() """ new_circ = self if not include_final_measurements: new_circ = self.remove_final_measurements(inplace=False) return Statevector.from_instruction(new_circ)
def test_from_int(self): """Initialize from int.""" desired_sv = Statevector.from_label("110101") qc = QuantumCircuit(6) qc.initialize(53, range(6)) actual_sv = Statevector.from_instruction(qc) self.assertTrue(desired_sv == actual_sv)
def send(self,circuit,arr_qubits): self._state_vector = Statevector.from_instruction(circuit) self._arr_qubits = arr_qubits self._circuit = circuit #From Marc ser = parser.QSerializer() ser.add_element('state_vector', self._state_vector)#self) ser.add_element('is_master', self._master)#self) ser.add_element('slave_offset', self._slave_offset)#self) ser.add_element('is_master', self._master)#self) ser.add_element('circuit', self._circuit)#self) str_to_send = ser.encode() #print(str_to_send.type()) #From Luca message = str_to_send channel = self.realchannel #SocketChannel() channel.send(message) channel.close() ## TODO: TCP THINGS return self
def simulate_circuit(circuit, assignment_matrix, num_qubits, shots=1024): """Simulates the given circuit under the given readout noise""" probs = Statevector.from_instruction(circuit).probabilities() noisy_probs = assignment_matrix @ probs labels = [bin(a)[2:].zfill(num_qubits) for a in range(2**num_qubits)] results = TestReadoutMitigation.rng.choice(labels, size=shots, p=noisy_probs) return Counts(dict(Counter(results)))
def test_gate_statevector(self, gate_cls, num_params): """Test standard gate simulation test.""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'matrix_product_state' ] circuit = self.gate_circuit(gate_cls, num_params=num_params, rng=self.RNG) target = Statevector.from_instruction(circuit) # Add snapshot and execute circuit.snapshot_statevector('final') backend_options = self.BACKEND_OPTS.copy() method = backend_options.pop('method', 'automatic') backend = self.SIMULATOR backend.set_options(method=method) result = execute(circuit, backend, shots=1, **backend_options).result() # Check results success = getattr(result, 'success', False) msg = '{}, method = {}'.format(gate_cls.__name__, method) if method not in SUPPORTED_METHODS: self.assertFalse(success) else: self.assertTrue(success, msg=msg) self.assertSuccess(result) snapshots = result.data(0).get("snapshots", {}).get("statevector", {}) value = snapshots.get('final', [None])[0] fidelity = state_fidelity(target, value) self.assertGreater(fidelity, 0.99999, msg=msg)
def get_rho(self): # Runs the circuit specified by self.qc and determines the expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ' (and the ones with Ys too if needed). if self.y_boxes: corr = ['ZZ', 'ZX', 'XZ', 'XX', 'YY', 'YX', 'YZ', 'XY', 'ZY'] ps = ['X', 'Y', 'Z'] else: corr = ['ZZ', 'ZX', 'XZ', 'XX'] ps = ['X', 'Z'] self.rho = {} results = {} for basis in corr: temp_qc = copy.deepcopy(self.qc) for j in range(2): if basis[j] == 'X': temp_qc.h(self.qr[j]) elif basis[j] == 'Y': temp_qc.sdg(self.qr[j]) temp_qc.h(self.qr[j]) if self.backend == None: ket = Statevector([1, 0, 0, 0]) ket = ket.from_instruction(temp_qc) results[basis] = ket.probabilities_dict() else: temp_qc.barrier(self.qr) temp_qc.measure(self.qr, self.cr) job = execute(temp_qc, backend=self.backend, shots=self.shots) results[basis] = job.result().get_counts() for string in results[basis]: results[basis][ string] = results[basis][string] / self.shots prob = {} # prob of expectation value -1 for single qubit observables for j in range(2): for p in ps: pauli = {} for pp in ['I'] + ps: pauli[pp] = (j == 1) * pp + p + (j == 0) * pp prob[pauli['I']] = 0 for ppp in ps: basis = pauli[ppp] for string in results[basis]: if string[(j + 1) % 2] == '1': prob[pauli['I']] += results[basis][string] / ( 2 + self.y_boxes) # prob of expectation value -1 for two qubit observables for basis in corr: prob[basis] = 0 for string in results[basis]: if string[0] != string[1]: prob[basis] += results[basis][string] for pauli in prob: self.rho[pauli] = 1 - 2 * prob[pauli]
def test_alice_circuit(self): qc = incompatible_measurement.bb84_states() test_state = Statevector.from_instruction(qc) real_state = [0, 0, 0.5, 0, 0, 0, 0.5, 0, 0, 0, -0.5, 0, 0, 0, -0.5, 0] error = abs(test_state.data - real_state) epsilon = 1.0E-4 self.assertFalse(any(x > epsilon for x in error))
def test_gate_density_matrix(self, gate_cls, num_params): """Test standard gate simulation test.""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust' ] circuit = self.gate_circuit(gate_cls, num_params=num_params, rng=self.RNG) target = Statevector.from_instruction(circuit) # Add snapshot and execute #circuit.snapshot_density_matrix('final') backend_options = self.BACKEND_OPTS method = backend_options.pop('method', 'automatic') backend = self.SIMULATOR backend.set_options(method=method) result = execute(circuit, backend, shots=1, **backend_options).result() # Check results success = getattr(result, 'success', False) msg = '{}, method = {}'.format(gate_cls.__name__, method) if method not in SUPPORTED_METHODS: self.assertFalse(success) else: self.assertTrue(success, msg=msg) self.assertSuccess(result)
def test_create_bell_state(self): qc = entanglement.create_bell_state() test_state = Statevector.from_instruction(qc) self.assertAlmostEqual(test_state.data[0], 1 / np.sqrt(2)) self.assertAlmostEqual(test_state.data[1], 0) self.assertAlmostEqual(test_state.data[2], 0) self.assertAlmostEqual(test_state.data[3], 1 / np.sqrt(2))
def test_rescaling(self): """Test the rescaling.""" amplitude = 0.8 scaling = 0.25 circuit = QuantumCircuit(1) circuit.ry(2 * np.arcsin(amplitude), 0) problem = EstimationProblem(circuit, objective_qubits=[0]) rescaled = problem.rescale(scaling) rescaled_amplitude = Statevector.from_instruction(rescaled.state_preparation).data[3] self.assertAlmostEqual(scaling * amplitude, rescaled_amplitude)
def test_gate(self, gate_cls, num_params, basis_gates): """Test standard gate simulation.""" circuit = self.gate_circuit(gate_cls, num_params=num_params, rng=self.RNG) target = Statevector.from_instruction(circuit) result = execute(circuit, self.SIMULATOR, basis_gates=basis_gates).result() self.assertSuccess(result) value = Statevector(result.get_statevector(0)) self.assertTrue(target.equiv(value), msg='{}, basis_gates = {}'.format( gate_cls.__name__, basis_gates))
def getProbabilityOutput(circuit): #Calculate the measurement probability probabilities = Statevector.from_instruction(circuit).probabilities_dict() probabilityOutput = "Probability distribution: " #Format according to [q0, q1, q2], probabaility; ... for the qbits q0, q1 and q2 for probability in probabilities.items(): x, y = eval(probability.__str__()) probabilityOutput += "[" for c in str(x): probabilityOutput += c + ", " probabilityOutput = probabilityOutput[0:len(probabilityOutput) - 2] probabilityOutput += "] , " + str(round(y, 3)) + "; " return probabilityOutput
def test_endian(self, little_endian): """Test the outcome for different endianness.""" qform = QuadraticForm(2, linear=[0, 1], little_endian=little_endian) circuit = QuantumCircuit(4) circuit.x(1) circuit.compose(qform, inplace=True) # the result is x_0 linear_0 + x_1 linear_1 = 1 = '0b01' result = "01" # the state is encoded as |q(x)>|x>, |x> = |x_1 x_0> = |10> index = (result if little_endian else result[::-1]) + "10" ref = np.zeros(2 ** 4, dtype=complex) ref[int(index, 2)] = 1 self.assertTrue(Statevector.from_instruction(circuit).equiv(ref))
def test_fitter_string_input(self): q3 = QuantumRegister(3) bell = QuantumCircuit(q3) bell.h(q3[0]) bell.cx(q3[0], q3[1]) bell.cx(q3[1], q3[2]) qst = tomo.state_tomography_circuits(bell, q3) qst_names = [circ.name for circ in qst] job = qiskit.execute(qst, Aer.get_backend('qasm_simulator'), shots=5000) tomo_fit = tomo.StateTomographyFitter(job.result(), qst_names) rho = tomo_fit.fit(method=self.method) psi = Statevector.from_instruction(bell) F_bell = state_fidelity(psi, rho, validate=False) self.assertAlmostEqual(F_bell, 1, places=1)
def assertDistributionIsCorrect(self, circuit, num_qubits, mu, sigma, bounds, upto_diag): """Assert that ``circuit`` implements the normal distribution correctly. This test asserts that the ``circuit`` produces the desired state-vector. """ if not isinstance(num_qubits, (list, np.ndarray)): num_qubits = [num_qubits] if not isinstance(mu, (list, np.ndarray)): mu = [mu] if not isinstance(sigma, (list, np.ndarray)): sigma = [[sigma]] # bit differently to cover the case the users might pass `bounds` as a single list, # e.g. [0, 1], instead of a tuple if not isinstance(bounds[0], tuple): bounds = [bounds] # compute the points meshgrid = np.meshgrid( *[ np.linspace(bound[0], bound[1], num=2**num_qubits[i]) for i, bound in enumerate(bounds) ], indexing="ij", ) x = list(zip(*[grid.flatten() for grid in meshgrid])) # compute the normalized, truncated probabilities probabilities = [] for x_i in x: if np.min(x_i) > 0: det = 1 / np.prod(x_i) probabilities += [ multivariate_normal.pdf(np.log(x_i), mu, sigma) * det ] else: probabilities += [0] normalized_probabilities = probabilities / np.sum(probabilities) expected = np.sqrt(normalized_probabilities) # compare to actual statevector from circuit actual = Statevector.from_instruction(circuit) if upto_diag: self.assertTrue(actual.equiv(expected)) else: np.testing.assert_array_almost_equal(expected, actual.data)
def assertPhaseEstimationIsCorrect(self, pec: QuantumCircuit, eigenstate: QuantumCircuit, phase_as_binary: str): r"""Assert that the phase estimation circuit implements the correct transformation. Applying the phase estimation circuit on a target register which holds the eigenstate :math:`|u\rangle` (say the last register), the final state should be .. math:: |\phi_1\rangle \cdots |\phi_t\rangle |u\rangle where the eigenvalue is written as :math:`e^{2\pi i \phi}` and the angle is represented in binary fraction, i.e. :math:`\phi = 0.\phi_1 \ldots \phi_t`. Args: pec: The circuit implementing the phase estimation circuit. eigenstate: The eigenstate as circuit. phase_as_binary: The phase of the eigenvalue in a binary fraction. E.g. if the phase is 0.25, the binary fraction is '01' as 0.01 = 0 * 0.5 + 1 * 0.25 = 0.25. """ # the target state eigenstate_as_vector = Statevector.from_instruction(eigenstate).data reference = eigenstate_as_vector zero, one = [1, 0], [0, 1] for qubit in phase_as_binary[::-1]: reference = np.kron(reference, zero if qubit == "0" else one) # the simulated state circuit = QuantumCircuit(pec.num_qubits) circuit.compose( eigenstate, list(range(pec.num_qubits - eigenstate.num_qubits, pec.num_qubits)), inplace=True, ) circuit.compose(pec, inplace=True) # TODO use Statevector for simulation once Qiskit/qiskit-terra#4681 is resolved # actual = Statevector.from_instruction(circuit).data backend = BasicAer.get_backend("statevector_simulator") actual = execute(circuit, backend).result().get_statevector() np.testing.assert_almost_equal(reference, actual)
def test_gate_density_matrix(self, gate_cls, num_angles, has_ctrl_qubits, basis_gates): """Test standard gate simulation test.""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust' ] backend_options = self.BACKEND_OPTS.copy() method = backend_options.pop('method', 'automatic') backend = self.SIMULATOR backend.set_options(method=method) circuits = self.gate_circuits(gate_cls, num_angles=num_angles, has_ctrl_qubits=has_ctrl_qubits, rng=self.RNG) for circuit in circuits: target = Statevector.from_instruction(circuit) # Add snapshot and execute circuit.snapshot_density_matrix('final') result = execute(circuit, backend, shots=1, basis_gates=basis_gates, optimization_level=0, **backend_options).result() # Check results success = getattr(result, 'success', False) msg = '{}, method = {}'.format(gate_cls.__name__, method) if method not in SUPPORTED_METHODS: self.assertFalse(success) else: self.assertTrue(success, msg=msg) self.assertSuccess(result) snapshots = result.data(0).get("snapshots", {}).get("density_matrix", {}) value = snapshots.get('final', [{'value': None}])[0]['value'] fidelity = state_fidelity(target, value) self.assertGreater(fidelity, 0.99999, msg=msg)
def run(): #create circuitmanager for handling grover's alg c = GroverCircuit(4, bonus_q=5) c.initHGates() #add h-gates to top 4 lines c.circuit.initialize([1 / np.sqrt(2), -1 / np.sqrt(2)], 8) #construct oracle c.circuit.barrier() c.circuit.append(sudokuOracle(), [0, 1, 2, 3, 4, 5, 6, 7]) c.circuit.mct([4, 5, 6, 7], 8) c.circuit.append(sudokuOracle(), [0, 1, 2, 3, 4, 5, 6, 7]) #add grover c.circuit.append(diffuser(4), [0, 1, 2, 3]) #do it again #construct oracle c.circuit.barrier() c.circuit.append(sudokuOracle(), [0, 1, 2, 3, 4, 5, 6, 7]) c.circuit.mct([4, 5, 6, 7], 8) c.circuit.append(sudokuOracle(), [0, 1, 2, 3, 4, 5, 6, 7]) #add grover c.circuit.append(diffuser(4), [0, 1, 2, 3]) c.circuit.barrier() state = Statevector.from_instruction(c.circuit) print(state) plot_state_qsphere(state) measureInRange(c.cm, 0, 4) c.cm.simulate() print(c.cm.counts) print('\n') c.cm.printTable() print('\n') c.cm.printQubitStates() print('\n') c.cm.printEntanglementTable() c.cm.printEntanglements() print(c.circuit.draw()) c.draw()
def qiskit(): # Plotting Single Bloch Sphere plot_bloch_vector([0, 1, 0], title='Bloch Sphere') # Building Quantum Circuit to use for multiqubit systems qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) # Plotting Multi Bloch System state = Statevector.from_instruction(qc) plot_bloch_multivector(state, title="New Bloch Multivector") # Plotting Bloch City Scape plot_state_city(state, color=['midnightblue', 'midnightblue'], title="New State City") # Plotting Bloch Pauli Vectors plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
def send(self,circuit,arr_qubits): self._state_vector = Statevector.from_instruction(circuit) self._arr_qubits = arr_qubits #From Marc ser = parser.QSerializer() ser.add_element('channel_class', self) str_to_send = ser.encode() #From Luca message = str_to_send TCP_IP = '127.0.0.1' channel = SocketChannel() channel.connect(TCP_IP, 5005) channel.send(message) #channel.close() ## TODO: TCP THINGS return self
def test_split_job(self): q3 = QuantumRegister(3) bell = QuantumCircuit(q3) bell.h(q3[0]) bell.cx(q3[0], q3[1]) bell.cx(q3[1], q3[2]) psi = Statevector.from_instruction(bell) qst = tomo.state_tomography_circuits(bell, q3) qst1 = qst[:len(qst) // 2] qst2 = qst[len(qst) // 2:] backend = Aer.get_backend('qasm_simulator') job1 = qiskit.execute(qst1, backend, shots=5000) job2 = qiskit.execute(qst2, backend, shots=5000) tomo_fit = tomo.StateTomographyFitter([job1.result(), job2.result()], qst) rho_mle = tomo_fit.fit(method='lstsq') F_bell_mle = state_fidelity(psi, rho_mle, validate=False) self.assertAlmostEqual(F_bell_mle, 1, places=1)
def assertQuadraticFormIsCorrect(self, m, quadratic, linear, offset, circuit): """Assert ``circuit`` implements the quadratic form correctly.""" def q_form(x, num_bits): x = np.array([int(val) for val in reversed(x)]) res = x.T.dot(quadratic).dot(x) + x.T.dot(linear) + offset # compute 2s complement res = (2**num_bits + int(res)) % 2**num_bits twos = bin(res)[2:].zfill(num_bits) return twos n = len(quadratic) # number of value qubits ref = np.zeros(2 ** (n + m), dtype=complex) for x in range(2 ** n): x_bin = bin(x)[2:].zfill(n) index = q_form(x_bin, m) + x_bin index = int(index, 2) ref[index] = 1 / np.sqrt(2 ** n) actual = QuantumCircuit(circuit.num_qubits) actual.h(list(range(n))) actual.compose(circuit, inplace=True) self.assertTrue(Statevector.from_instruction(actual).equiv(ref))
def test_gate_density_matrix(self, gate_cls, num_params): """Test standard gate simulation test.""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust' ] circuit = self.gate_circuit(gate_cls, num_params=num_params, rng=self.RNG) target = Statevector.from_instruction(circuit) # Add snapshot and execute circuit.snapshot_density_matrix('final') backend_options = self.BACKEND_OPTS method = backend_options.get('method', 'automatic') basis_gates = BASIS_GATES.get(method) result = execute(circuit, self.SIMULATOR, basis_gates=basis_gates, shots=1, backend_options=backend_options).result() # Check results success = getattr(result, 'success', False) msg = '{}, method = {}'.format(gate_cls.__name__, method) if method not in SUPPORTED_METHODS: self.assertFalse(success) else: self.assertTrue(success, msg=msg) self.assertSuccess(result) snapshots = result.data(0).get("snapshots", {}).get("density_matrix", {}) value = snapshots.get('final', [{'value': None}])[0]['value'] fidelity = state_fidelity(target, value) self.assertGreater(fidelity, 0.99999, msg=msg)
def test_statevector(self, expression, good_states): """Circuit generation""" oracle = PhaseOracle(expression) num_qubits = oracle.num_qubits circuit = QuantumCircuit(num_qubits) circuit.h(range(num_qubits)) circuit.compose(oracle, inplace=True) statevector = Statevector.from_instruction(circuit) valid_state = -1 / sqrt(2**num_qubits) invalid_state = 1 / sqrt(2**num_qubits) states = list(range(2**num_qubits)) expected_valid = [state in good_states for state in states] result_valid = [ isclose(statevector.data[state], valid_state) for state in states ] expected_invalid = [state not in good_states for state in states] result_invalid = [ isclose(statevector.data[state], invalid_state) for state in states ] self.assertListEqual(expected_valid, result_valid) self.assertListEqual(expected_invalid, result_invalid)
myqc = QuantumCircuit(1) #first we creat a superposition to have equal chances for states |0> and |1> myqc.h(0) myqc.u(theta, phi, lam, qb) return myqc # creat random parameters to build a random state on the Bloch sphere theta = random.uniform(0,1)*2*pi phi = random.uniform(0,1)*2*pi lam = random.uniform(0,1)*2*pi print("parameters theta, phi, and lam are: ", theta, phi, lam) random_circuit = newqc(theta, phi, lam, 0) state = Statevector.from_instruction(random_circuit) sv = state.data print("The state vector of our random state on the Bloch sphere is: " , sv) plot_bloch_multivector (state) plot_state_qsphere(state, show_state_labels=True) ############################################################################################################################# # ## Part 2) # defining the function to measure the similarity of 2 given quantum circuits using thr swap test def similarity(circuit1, circuit2, num_qubits): overlap_test_qc = QuantumCircuit(3,1) overlap_test_qc.h(0)
#Dibujo del segundo circuito qc2.draw(output='mpl') # In[8]: #State vector segundo circuito backend = Aer.get_backend('statevector_simulator') Statevector2 = execute(qc2, backend).result().get_statevector() array_to_latex(Statevector2, pretext="\\text{Statevector2 = }") # In[9]: #Primera, se convierten los circuitos antes creados en statevector y se ejecuta el metodo tensor #dando como resultado el producto tensorial en otro statevector, este proporciona sus datos #por medio del atributo data asi se puede dibujar en latex final1 = Statevector.from_instruction(qc) final2 = Statevector.from_instruction(qc2) final3 = final1.tensor(final2) array_to_latex(final3.data, pretext="\\text{Statevector Solution 1= }") # In[10]: #Segundo, se utiliza la clase Operator que permite convertir varios objetos en Operators #entre ellos un circuito, por lo tanto se convierten los dos en Operator y luego #se realiza la multiplicacion tensorial mediante el metodo tensor el cual da como resultado otro #operator que es ademas una compuerta unitaria lo que permite adicionarla a un circuito y pintar este #luego se pinta el statevector de este circuito y se comprueba que es el mismo resultado del metodo anterior A = Operator(qc) B = Operator(qc2) finalal = A.tensor(B) #Del operator se saca el numero de qubits que contiene