repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/anpaschool/QC-School-Fall2020
anpaschool
#supporting package import matplotlib.pyplot as plt %matplotlib inline import numpy as np from math import pi, sqrt from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, Aer qc = QuantumCircuit(2) qc.h(0) qc.cz(0, 1) #squareroot control Z-gate qc.h(1) qc.swap(0,1) # to make completeness in orthonormal basis qc.draw('mpl') s = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]]) s h = np.array([[0.707,0.707,0,0],[0.707,-0.707,0,0],[0,0,0.707,0.707],[0,0,0.707,-0.707]]) h z=np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,0+1.j]]) z QFT2 = s*h*z*h #need to do #QFT2 qc = QuantumCircuit(3) qc.h(2) display( qc.draw('mpl') ) # UROT_2 gate to x1 depending on x2 qc.cu1(pi/2, 1, 2) # CROT from qubit 1 to qubit 2 hence the angle: pi/2^{2-1} display ( qc.draw('mpl') ) qc.cu1(pi/4, 0, 2) # CROT from qubit 2 to qubit 0 hence the angle: pi/2^{2-0} display( qc.draw('mpl') ) # Repeat the process for 1 and 0 qc.h(1) # Hadamard on 1 qc.cu1(pi/2, 0, 1) # CROT from qubit 0 to qubit 1 hence the angle: pi/2^{1-0} qc.h(0) # Hadamard on 0 display( qc.draw('mpl') ) # Now swap the qubit 0 and 2 to complete QFT. [NOT CLEAR TO ME] qc.swap(0,2) display ( qc.draw('mpl') ) qc = QuantumCircuit(2) qc.h(1) display( qc.draw('mpl') ) # UROT_1 gate to x0 depending on x1 qc.cu1(pi/2, 0, 1) # CROT from qubit 0 to qubit 1 hence the angle: pi/2^{1-0} display ( qc.draw('mpl') ) qc.h(0) # Hadamard on 1 # Now swap the qubit 0 and 2 to complete QFT. [To make orthonormal bais set completeness] qc.swap(0,1) display ( qc.draw('mpl') )
https://github.com/jcylim/QiskitProject
jcylim
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError from qiskit import available_backends, execute, register, get_backend # import state tomography functions from qiskit.tools.visualization import plot_histogram, plot_state # useful additional packages import matplotlib.pyplot as plt #%matplotlib inline import numpy as np from pprint import pprint from scipy import linalg as la def ghz_state(q, c, n): # Create a GHZ state qc = QuantumCircuit(q, c) qc.h(q[0]) for i in range(n-1): qc.cx(q[i], q[i+1]) return qc def superposition_state(q, c): # Create a Superposition state qc = QuantumCircuit(q, c) qc.h(q) return qc def overlap(state1, state2): return round(np.dot(state1.conj(), state2)) def expectation_value(state, Operator): return round(np.dot(state.conj(), np.dot(Operator, state)).real) def state_2_rho(state): return np.outer(state, state.conj()) # Build the quantum cirucit. We are going to build two circuits a GHZ over 3 qubits and a # superpositon over all 3 qubits n = 3 # number of qubits q = QuantumRegister(n) c = ClassicalRegister(n) ''' # quantum circuit to make a GHZ state ghz = ghz_state(q, c, n) # quantum circuit to make a superposition state superposition = superposition_state(q, c) measure_circuit = QuantumCircuit(q,c) measure_circuit.measure(q, c) # execute the quantum circuit backend = 'local_qasm_simulator' # the device to run on circuits = [ghz+measure_circuit, superposition+measure_circuit] job = execute(circuits, backend=backend, shots=1000) plot_histogram(job.result().get_counts(circuits[0])) plot_histogram(job.result().get_counts(circuits[1]),15) ''' qc = QuantumCircuit(q, c) qc.h(q[1]) # execute the quantum circuit job = execute(qc, backend='local_statevector_simulator') state_superposition = job.result().get_statevector(qc) #print(state_superposition) #print(overlap(state_superposition, state_superposition)) rho_superposition = state_2_rho(state_superposition) print(rho_superposition) plot_state(rho_superposition, 'bloch') #'city', 'paulivec', 'qsphere', 'bloch'
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
ahkatlio
# We import the necessary functions from Qiskit from qiskit.visualization import plot_bloch_multivector, visualize_transition from qiskit import QuantumCircuit, Aer, execute from math import pi # We create a quantum circuit with one qubit qc = QuantumCircuit(1) # We execute the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result() # We get the statevector of the quantum circuit statevector = result.get_statevector(qc) # We plot the statevector on the Bloch sphere plot_bloch_multivector(statevector) qc.ry(pi/2, 0) qc.draw(output='mpl') visualize_transition(qc) qc1 = QuantumCircuit(1) qc1.rx(pi/3, 0) qc1.draw(output='mpl') visualize_transition(qc1) qc2 = QuantumCircuit(1) qc2.rz(pi, 0) qc2.draw(output='mpl') visualize_transition(qc2)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for BasePrimitive.""" import json from ddt import data, ddt, unpack from numpy import array, float32, float64, int32, int64 from qiskit import QuantumCircuit, pulse, transpile from qiskit.circuit.random import random_circuit from qiskit.primitives.base.base_primitive import BasePrimitive from qiskit.primitives.utils import _circuit_key from qiskit.providers.fake_provider import FakeAlmaden from qiskit.test import QiskitTestCase @ddt class TestCircuitValidation(QiskitTestCase): """Test circuits validation logic.""" @data( (random_circuit(2, 2, seed=0), (random_circuit(2, 2, seed=0),)), ( [random_circuit(2, 2, seed=0), random_circuit(2, 2, seed=1)], (random_circuit(2, 2, seed=0), random_circuit(2, 2, seed=1)), ), ) @unpack def test_validate_circuits(self, circuits, expected): """Test circuits standardization.""" self.assertEqual(BasePrimitive._validate_circuits(circuits), expected) @data(None, "ERROR", True, 0, 1.0, 1j, [0.0]) def test_type_error(self, circuits): """Test type error if invalid input.""" with self.assertRaises(TypeError): BasePrimitive._validate_circuits(circuits) @data((), [], "") def test_value_error(self, circuits): """Test value error if no circuits are provided.""" with self.assertRaises(ValueError): BasePrimitive._validate_circuits(circuits) @ddt class TestParameterValuesValidation(QiskitTestCase): """Test parameter_values validation logic.""" @data( ((), ((),)), ([], ((),)), (0, ((0,),)), (1.2, ((1.2,),)), ((0,), ((0,),)), ([0], ((0,),)), ([1.2], ((1.2,),)), ((0, 1), ((0, 1),)), ([0, 1], ((0, 1),)), ([0, 1.2], ((0, 1.2),)), ([0.3, 1.2], ((0.3, 1.2),)), (((0, 1)), ((0, 1),)), (([0, 1]), ((0, 1),)), ([(0, 1)], ((0, 1),)), ([[0, 1]], ((0, 1),)), ([[0, 1.2]], ((0, 1.2),)), ([[0.3, 1.2]], ((0.3, 1.2),)), # Test for numpy dtypes (int32(5), ((float(int32(5)),),)), (int64(6), ((float(int64(6)),),)), (float32(3.2), ((float(float32(3.2)),),)), (float64(6.4), ((float(float64(6.4)),),)), ([int32(5), float32(3.2)], ((float(int32(5)), float(float32(3.2))),)), ) @unpack def test_validate_parameter_values(self, _parameter_values, expected): """Test parameter_values standardization.""" for parameter_values in [_parameter_values, array(_parameter_values)]: # Numpy self.assertEqual(BasePrimitive._validate_parameter_values(parameter_values), expected) self.assertEqual( BasePrimitive._validate_parameter_values(None, default=parameter_values), expected ) @data( "ERROR", ("E", "R", "R", "O", "R"), (["E", "R", "R"], ["O", "R"]), 1j, (1j,), ((1j,),), True, False, float("inf"), float("-inf"), float("nan"), ) def test_type_error(self, parameter_values): """Test type error if invalid input.""" with self.assertRaises(TypeError): BasePrimitive._validate_parameter_values(parameter_values) def test_value_error(self): """Test value error if no parameter_values or default are provided.""" with self.assertRaises(ValueError): BasePrimitive._validate_parameter_values(None) class TestCircuitKey(QiskitTestCase): """Tests for _circuit_key function""" def test_different_circuits(self): """Test collision of quantum circuits.""" with self.subTest("Ry circuit"): def test_func(n): qc = QuantumCircuit(1, 1, name="foo") qc.ry(n, 0) return qc keys = [_circuit_key(test_func(i)) for i in range(5)] self.assertEqual(len(keys), len(set(keys))) with self.subTest("pulse circuit"): def test_with_scheduling(n): custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(160 * n, 0.1), pulse.DriveChannel(0)), inplace=True ) qc = QuantumCircuit(1) qc.x(0) qc.add_calibration("x", qubits=(0,), schedule=custom_gate) return transpile(qc, FakeAlmaden(), scheduling_method="alap") keys = [_circuit_key(test_with_scheduling(i)) for i in range(1, 5)] self.assertEqual(len(keys), len(set(keys))) def test_circuit_key_controlflow(self): """Test for a circuit with control flow.""" qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) self.assertIsInstance(hash(_circuit_key(qc)), int) self.assertIsInstance(json.dumps(_circuit_key(qc)), str)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Transpiler testing""" import io from logging import StreamHandler, getLogger import unittest.mock import sys from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import PassManager, TranspilerError from qiskit.transpiler.runningpassmanager import ( DoWhileController, ConditionalController, FlowController, ) from qiskit.test import QiskitTestCase from ._dummy_passes import ( PassA_TP_NR_NP, PassB_TP_RA_PA, PassC_TP_RA_PA, PassD_TP_NR_NP, PassE_AP_NR_NP, PassF_reduce_dag_property, PassI_Bad_AP, PassJ_Bad_NoReturn, PassK_check_fixed_point_property, PassM_AP_NR_NP, ) class SchedulerTestCase(QiskitTestCase): """Asserts for the scheduler.""" def assertScheduler(self, circuit, passmanager, expected): """ Run `transpile(circuit, passmanager)` and check if the passes run as expected. Args: circuit (QuantumCircuit): Circuit to transform via transpilation. passmanager (PassManager): pass manager instance for the transpilation process expected (list): List of things the passes are logging """ logger = "LocalLogger" with self.assertLogs(logger, level="INFO") as cm: out = passmanager.run(circuit) self.assertIsInstance(out, QuantumCircuit) self.assertEqual([record.message for record in cm.records], expected) def assertSchedulerRaises(self, circuit, passmanager, expected, exception_type): """ Run `transpile(circuit, passmanager)` and check if the passes run as expected until exception_type is raised. Args: circuit (QuantumCircuit): Circuit to transform via transpilation passmanager (PassManager): pass manager instance for the transpilation process expected (list): List of things the passes are logging exception_type (Exception): Exception that is expected to be raised. """ logger = "LocalLogger" with self.assertLogs(logger, level="INFO") as cm: self.assertRaises(exception_type, passmanager.run, circuit) self.assertEqual([record.message for record in cm.records], expected) class TestPassManagerInit(SchedulerTestCase): """The pass manager sets things at init time.""" def test_passes(self): """A single chain of passes, with Requests and Preserves, at __init__ time""" circuit = QuantumCircuit(QuantumRegister(1)) passmanager = PassManager( passes=[ PassC_TP_RA_PA(), # Request: PassA / Preserves: PassA PassB_TP_RA_PA(), # Request: PassA / Preserves: PassA PassD_TP_NR_NP(argument1=[1, 2]), # Requires: {}/ Preserves: {} PassB_TP_RA_PA(), ] ) self.assertScheduler( circuit, passmanager, [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassD_TP_NR_NP", "argument [1, 2]", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", ], ) class TestUseCases(SchedulerTestCase): """Combine passes in different ways and checks that passes are run in the right order.""" def setUp(self): super().setUp() self.circuit = QuantumCircuit(QuantumRegister(1)) self.passmanager = PassManager() def test_chain(self): """A single chain of passes, with Requires and Preserves.""" self.passmanager.append(PassC_TP_RA_PA()) # Requires: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Requires: PassA / Preserves: PassA self.passmanager.append(PassD_TP_NR_NP(argument1=[1, 2])) # Requires: {}/ Preserves: {} self.passmanager.append(PassB_TP_RA_PA()) self.assertScheduler( self.circuit, self.passmanager, [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassD_TP_NR_NP", "argument [1, 2]", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", ], ) def test_conditional_passes_true(self): """A pass set with a conditional parameter. The callable is True.""" self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", ], ) def test_conditional_passes_true_fc(self): """A pass set with a conditional parameter (with FlowController). The callable is True.""" self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( ConditionalController( [PassA_TP_NR_NP()], condition=lambda property_set: property_set["property"] ) ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", ], ) def test_conditional_passes_false(self): """A pass set with a conditional parameter. The callable is False.""" self.passmanager.append(PassE_AP_NR_NP(False)) self.passmanager.append( PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) self.assertScheduler( self.circuit, self.passmanager, ["run analysis pass PassE_AP_NR_NP", "set property as False"], ) def test_conditional_and_loop(self): """Run a conditional first, then a loop.""" self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], condition=lambda property_set: property_set["property"], ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ], ) def test_loop_and_conditional(self): """Run a loop first, then a conditional.""" FlowController.remove_flow_controller("condition") FlowController.add_flow_controller("condition", ConditionalController) self.passmanager.append(PassK_check_fixed_point_property()) self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], condition=lambda property_set: not property_set["property_fixed_point"], ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ], ) def test_do_not_repeat_based_on_preservation(self): """When a pass is still a valid pass (because the following passes preserved it), it should not run again.""" self.passmanager.append([PassB_TP_RA_PA(), PassA_TP_NR_NP(), PassB_TP_RA_PA()]) self.assertScheduler( self.circuit, self.passmanager, ["run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA"], ) def test_do_not_repeat_based_on_idempotence(self): """Repetition can be optimized to a single execution when the pass is idempotent.""" self.passmanager.append(PassA_TP_NR_NP()) self.passmanager.append([PassA_TP_NR_NP(), PassA_TP_NR_NP()]) self.passmanager.append(PassA_TP_NR_NP()) self.assertScheduler( self.circuit, self.passmanager, ["run transformation pass PassA_TP_NR_NP"] ) def test_non_idempotent_pass(self): """Two or more runs of a non-idempotent pass cannot be optimized.""" self.passmanager.append(PassF_reduce_dag_property()) self.passmanager.append([PassF_reduce_dag_property(), PassF_reduce_dag_property()]) self.passmanager.append(PassF_reduce_dag_property()) self.assertScheduler( self.circuit, self.passmanager, [ "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run transformation pass PassF_reduce_dag_property", "dag property = 3", ], ) def test_fenced_dag(self): """Analysis passes are not allowed to modified the DAG.""" qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.cx(qr[0], qr[1]) circ.cx(qr[0], qr[1]) circ.cx(qr[1], qr[0]) circ.cx(qr[1], qr[0]) self.passmanager.append(PassI_Bad_AP()) self.assertSchedulerRaises( circ, self.passmanager, ["run analysis pass PassI_Bad_AP", "cx_runs: {(4, 5, 6, 7)}"], TranspilerError, ) def test_analysis_pass_is_idempotent(self): """Analysis passes are idempotent.""" passmanager = PassManager() passmanager.append(PassE_AP_NR_NP(argument1=1)) passmanager.append(PassE_AP_NR_NP(argument1=1)) self.assertScheduler( self.circuit, passmanager, ["run analysis pass PassE_AP_NR_NP", "set property as 1"] ) def test_ap_before_and_after_a_tp(self): """A default transformation does not preserves anything and analysis passes need to be re-run""" passmanager = PassManager() passmanager.append(PassE_AP_NR_NP(argument1=1)) passmanager.append(PassA_TP_NR_NP()) passmanager.append(PassE_AP_NR_NP(argument1=1)) self.assertScheduler( self.circuit, passmanager, [ "run analysis pass PassE_AP_NR_NP", "set property as 1", "run transformation pass PassA_TP_NR_NP", "run analysis pass PassE_AP_NR_NP", "set property as 1", ], ) def test_pass_no_return(self): """Transformation passes that don't return a DAG raise error.""" self.passmanager.append(PassJ_Bad_NoReturn()) self.assertSchedulerRaises( self.circuit, self.passmanager, ["run transformation pass PassJ_Bad_NoReturn"], TranspilerError, ) def test_fixed_point_pass(self): """A pass set with a do_while parameter that checks for a fixed point.""" self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ], ) def test_fixed_point_fc(self): """A fixed point scheduler with flow control.""" self.passmanager.append( DoWhileController( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], ) ) expected = [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_fixed_point_pass_max_iteration(self): """A pass set with a do_while parameter that checks that the max_iteration is raised.""" self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], max_iteration=2, ) self.assertSchedulerRaises( self.circuit, self.passmanager, [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", ], TranspilerError, ) def test_fresh_initial_state(self): """New construction gives fresh instance.""" self.passmanager.append(PassM_AP_NR_NP(argument1=1)) self.passmanager.append(PassA_TP_NR_NP()) self.passmanager.append(PassM_AP_NR_NP(argument1=1)) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassM_AP_NR_NP", "self.argument1 = 2", "run transformation pass PassA_TP_NR_NP", "run analysis pass PassM_AP_NR_NP", "self.argument1 = 2", ], ) def test_nested_conditional_in_loop(self): """Run a loop with a nested conditional.""" nested_conditional = [ ConditionalController( [PassA_TP_NR_NP()], condition=lambda property_set: property_set["property"] >= 5 ) ] self.passmanager.append( [PassK_check_fixed_point_property()] + nested_conditional + [PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], ) expected = [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ] self.assertScheduler(self.circuit, self.passmanager, expected) class DoXTimesController(FlowController): """A control-flow plugin for running a set of passes an X amount of times.""" def __init__(self, passes, options, do_x_times=0, **_): self.do_x_times = do_x_times() super().__init__(passes, options) def __iter__(self): for _ in range(self.do_x_times): yield from self.passes class TestControlFlowPlugin(SchedulerTestCase): """Testing the control flow plugin system.""" def setUp(self): super().setUp() self.passmanager = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_control_flow_plugin(self): """Adds a control flow plugin with a single parameter and runs it.""" FlowController.add_flow_controller("do_x_times", DoXTimesController) self.passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3) self.assertScheduler( self.circuit, self.passmanager, [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ], ) def test_callable_control_flow_plugin(self): """Removes do_while, then adds it back. Checks max_iteration still working.""" controllers_length = len(FlowController.registered_controllers) FlowController.remove_flow_controller("do_while") self.assertEqual(controllers_length - 1, len(FlowController.registered_controllers)) FlowController.add_flow_controller("do_while", DoWhileController) self.assertEqual(controllers_length, len(FlowController.registered_controllers)) self.passmanager.append( [PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_while=lambda property_set: True, max_iteration=2, ) self.assertSchedulerRaises( self.circuit, self.passmanager, [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ], TranspilerError, ) def test_remove_nonexistent_plugin(self): """Tries to remove a plugin that does not exist.""" self.assertRaises(KeyError, FlowController.remove_flow_controller, "foo") def test_bad_conditional(self): """Flow controller are not allowed to modify the property set.""" def bad_condition(property_set): property_set["property"] = "forbidden write" self.passmanager.append(PassA_TP_NR_NP(), condition=bad_condition) self.assertRaises(TranspilerError, self.passmanager.run, self.circuit) class TestDumpPasses(SchedulerTestCase): """Testing the passes method.""" def test_passes(self): """Dump passes in different FlowControllerLinear""" passmanager = PassManager() passmanager.append(PassC_TP_RA_PA()) passmanager.append(PassB_TP_RA_PA()) expected = [ {"flow_controllers": {}, "passes": [PassC_TP_RA_PA()]}, {"flow_controllers": {}, "passes": [PassB_TP_RA_PA()]}, ] self.assertEqual(expected, passmanager.passes()) def test_passes_in_linear(self): """Dump passes in the same FlowControllerLinear""" passmanager = PassManager( passes=[ PassC_TP_RA_PA(), PassB_TP_RA_PA(), PassD_TP_NR_NP(argument1=[1, 2]), PassB_TP_RA_PA(), ] ) expected = [ { "flow_controllers": {}, "passes": [ PassC_TP_RA_PA(), PassB_TP_RA_PA(), PassD_TP_NR_NP(argument1=[1, 2]), PassB_TP_RA_PA(), ], } ] self.assertEqual(expected, passmanager.passes()) def test_control_flow_plugin(self): """Dump passes in a custom flow controller.""" passmanager = PassManager() FlowController.add_flow_controller("do_x_times", DoXTimesController) passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3) expected = [ {"passes": [PassB_TP_RA_PA(), PassC_TP_RA_PA()], "flow_controllers": {"do_x_times"}} ] self.assertEqual(expected, passmanager.passes()) def test_conditional_and_loop(self): """Dump passes with a conditional and a loop.""" passmanager = PassManager() passmanager.append(PassE_AP_NR_NP(True)) passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], condition=lambda property_set: property_set["property_fixed_point"], ) expected = [ {"passes": [PassE_AP_NR_NP(True)], "flow_controllers": {}}, { "passes": [ PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property(), ], "flow_controllers": {"condition", "do_while"}, }, ] self.assertEqual(expected, passmanager.passes()) class StreamHandlerRaiseException(StreamHandler): """Handler class that will raise an exception on formatting errors.""" def handleError(self, record): raise sys.exc_info() class TestLogPasses(QiskitTestCase): """Testing the log_passes option.""" def setUp(self): super().setUp() logger = getLogger() self.addCleanup(logger.setLevel, logger.level) logger.setLevel("DEBUG") self.output = io.StringIO() logger.addHandler(StreamHandlerRaiseException(self.output)) self.circuit = QuantumCircuit(QuantumRegister(1)) def assertPassLog(self, passmanager, list_of_passes): """Runs the passmanager and checks that the elements in passmanager.property_set['pass_log'] match list_of_passes (the names).""" passmanager.run(self.circuit) self.output.seek(0) # Filter unrelated log lines output_lines = self.output.readlines() pass_log_lines = [x for x in output_lines if x.startswith("Pass:")] for index, pass_name in enumerate(list_of_passes): self.assertTrue(pass_log_lines[index].startswith("Pass: %s -" % pass_name)) def test_passes(self): """Dump passes in different FlowControllerLinear""" passmanager = PassManager() passmanager.append(PassC_TP_RA_PA()) passmanager.append(PassB_TP_RA_PA()) self.assertPassLog(passmanager, ["PassA_TP_NR_NP", "PassC_TP_RA_PA", "PassB_TP_RA_PA"]) def test_passes_in_linear(self): """Dump passes in the same FlowControllerLinear""" passmanager = PassManager( passes=[ PassC_TP_RA_PA(), PassB_TP_RA_PA(), PassD_TP_NR_NP(argument1=[1, 2]), PassB_TP_RA_PA(), ] ) self.assertPassLog( passmanager, [ "PassA_TP_NR_NP", "PassC_TP_RA_PA", "PassB_TP_RA_PA", "PassD_TP_NR_NP", "PassA_TP_NR_NP", "PassB_TP_RA_PA", ], ) def test_control_flow_plugin(self): """Dump passes in a custom flow controller.""" passmanager = PassManager() FlowController.add_flow_controller("do_x_times", DoXTimesController) passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3) self.assertPassLog( passmanager, [ "PassA_TP_NR_NP", "PassB_TP_RA_PA", "PassC_TP_RA_PA", "PassB_TP_RA_PA", "PassC_TP_RA_PA", "PassB_TP_RA_PA", "PassC_TP_RA_PA", ], ) def test_conditional_and_loop(self): """Dump passes with a conditional and a loop""" passmanager = PassManager() passmanager.append(PassE_AP_NR_NP(True)) passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], condition=lambda property_set: property_set["property_fixed_point"], ) self.assertPassLog(passmanager, ["PassE_AP_NR_NP"]) class TestPassManagerReuse(SchedulerTestCase): """The PassManager instance should be reusable.""" def setUp(self): super().setUp() self.passmanager = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_chain_twice(self): """Run a chain twice.""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) self.assertScheduler(self.circuit, self.passmanager, expected) def test_conditional_twice(self): """Run a conditional twice.""" self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) expected = [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", ] self.assertScheduler(self.circuit, self.passmanager, expected) self.assertScheduler(self.circuit, self.passmanager, expected) def test_fixed_point_twice(self): """A fixed point scheduler, twice.""" self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], ) expected = [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ] self.assertScheduler(self.circuit, self.passmanager, expected) self.assertScheduler(self.circuit, self.passmanager, expected) class TestPassManagerChanges(SchedulerTestCase): """Test PassManager manipulation with changes""" def setUp(self): super().setUp() self.passmanager = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_replace0(self): """Test passmanager.replace(0, ...).""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.replace(0, PassB_TP_RA_PA()) expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_replace1(self): """Test passmanager.replace(1, ...).""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.replace(1, PassC_TP_RA_PA()) expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_remove0(self): """Test passmanager.remove(0).""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.remove(0) expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_remove1(self): """Test passmanager.remove(1).""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.remove(1) expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_remove_minus_1(self): """Test passmanager.remove(-1).""" self.passmanager.append(PassA_TP_NR_NP()) self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.remove(-1) expected = ["run transformation pass PassA_TP_NR_NP"] self.assertScheduler(self.circuit, self.passmanager, expected) def test_setitem(self): """Test passmanager[1] = ...""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager[1] = PassC_TP_RA_PA() expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_replace_with_conditional(self): """Replace a pass with a conditional pass.""" self.passmanager.append(PassE_AP_NR_NP(False)) self.passmanager.append(PassB_TP_RA_PA()) self.passmanager.replace( 1, PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) expected = ["run analysis pass PassE_AP_NR_NP", "set property as False"] self.assertScheduler(self.circuit, self.passmanager, expected) def test_replace_error(self): """Replace a non-existing index.""" self.passmanager.append(PassB_TP_RA_PA()) with self.assertRaises(TranspilerError): self.passmanager.replace(99, PassA_TP_NR_NP()) class TestPassManagerSlicing(SchedulerTestCase): """test PassManager slicing.""" def setUp(self): super().setUp() self.passmanager = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_empty_passmanager_length(self): """test len(PassManager) when PassManager is empty""" length = len(self.passmanager) expected_length = 0 self.assertEqual(length, expected_length) def test_passmanager_length(self): """test len(PassManager) when PassManager is not empty""" self.passmanager.append(PassA_TP_NR_NP()) self.passmanager.append(PassA_TP_NR_NP()) length = len(self.passmanager) expected_length = 2 self.assertEqual(length, expected_length) def test_accessing_passmanager_by_index(self): """test accessing PassManager's passes by index""" self.passmanager.append(PassB_TP_RA_PA()) self.passmanager.append(PassC_TP_RA_PA()) new_passmanager = self.passmanager[1] expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_accessing_passmanager_by_index_with_condition(self): """test accessing PassManager's conditioned passes by index""" self.passmanager.append(PassF_reduce_dag_property()) self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], condition=lambda property_set: True, do_while=lambda property_set: not property_set["property_fixed_point"], ) new_passmanager = self.passmanager[1] expected = [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_accessing_passmanager_by_range(self): """test accessing PassManager's passes by range""" self.passmanager.append(PassC_TP_RA_PA()) self.passmanager.append(PassB_TP_RA_PA()) self.passmanager.append(PassC_TP_RA_PA()) self.passmanager.append(PassD_TP_NR_NP()) new_passmanager = self.passmanager[1:3] expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_accessing_passmanager_by_range_with_condition(self): """test accessing PassManager's passes by range with condition""" self.passmanager.append(PassB_TP_RA_PA()) self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) self.passmanager.append(PassB_TP_RA_PA()) new_passmanager = self.passmanager[1:3] expected = [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_accessing_passmanager_error(self): """testing accessing a pass item not in list""" self.passmanager.append(PassB_TP_RA_PA()) with self.assertRaises(IndexError): self.passmanager = self.passmanager[99] class TestPassManagerConcatenation(SchedulerTestCase): """test PassManager concatenation by + operator.""" def setUp(self): super().setUp() self.passmanager1 = PassManager() self.passmanager2 = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_concatenating_passmanagers(self): """test adding two PassManagers together""" self.passmanager1.append(PassB_TP_RA_PA()) self.passmanager2.append(PassC_TP_RA_PA()) new_passmanager = self.passmanager1 + self.passmanager2 expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_concatenating_passmanagers_with_condition(self): """test adding two pass managers with condition""" self.passmanager1.append(PassE_AP_NR_NP(True)) self.passmanager1.append(PassB_TP_RA_PA()) self.passmanager2.append( PassC_TP_RA_PA(), condition=lambda property_set: property_set["property"] ) self.passmanager2.append(PassB_TP_RA_PA()) new_passmanager = self.passmanager1 + self.passmanager2 expected = [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_adding_pass_to_passmanager(self): """test adding a pass to PassManager""" self.passmanager1.append(PassE_AP_NR_NP(argument1=1)) self.passmanager1.append(PassB_TP_RA_PA()) self.passmanager1 += PassC_TP_RA_PA() expected = [ "run analysis pass PassE_AP_NR_NP", "set property as 1", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager1, expected) def test_adding_list_of_passes_to_passmanager(self): """test adding a list of passes to PassManager""" self.passmanager1.append(PassE_AP_NR_NP(argument1=1)) self.passmanager1.append(PassB_TP_RA_PA()) self.passmanager1 += [PassC_TP_RA_PA(), PassB_TP_RA_PA()] expected = [ "run analysis pass PassE_AP_NR_NP", "set property as 1", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager1, expected) def test_adding_list_of_passes_to_passmanager_with_condition(self): """test adding a list of passes to a PassManager that have conditions""" self.passmanager1.append(PassE_AP_NR_NP(False)) self.passmanager1.append( PassB_TP_RA_PA(), condition=lambda property_set: property_set["property"] ) self.passmanager1 += PassC_TP_RA_PA() expected = [ "run analysis pass PassE_AP_NR_NP", "set property as False", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager1, expected) def test_adding_pass_to_passmanager_error(self): """testing adding a non-pass item to PassManager""" with self.assertRaises(TypeError): self.passmanager1 += "not a pass" def test_adding_list_to_passmanager_error(self): """testing adding a list having a non-pass item to PassManager""" with self.assertRaises(TypeError): self.passmanager1 += [PassB_TP_RA_PA(), "not a pass"] if __name__ == "__main__": unittest.main()
https://github.com/DLR-RB/QUEASARS
DLR-RB
from pathlib import Path import os import sys main_directory = Path(os.path.abspath("")).parent sys.path.append(str(main_directory)) from docplex.mp.model import Model # set up the model for optimization in docplex optimization_problem = Model() # add the needed variables x = optimization_problem.integer_var(0, 15, "x") y = optimization_problem.integer_var(0, 15, "y") a = optimization_problem.binary_var("a") b = optimization_problem.binary_var("b") # formally describe the minimization task optimization_problem.minimize((2*x-y)**2 + 100*a*x - 100*b*y + (a + b - 1)**2) from qiskit_optimization.translators import from_docplex_mp, to_ising from qiskit_optimization.converters import IntegerToBinary # convert to a quadratic program quadratic_program = from_docplex_mp(model=optimization_problem) # some variables are still integers, convert them to binary variables integer_converter = IntegerToBinary() quadratic_program = integer_converter.convert(problem=quadratic_program) # convert the quadratic program to an ising hamiltonian hamiltonian, offset = to_ising(quad_prog=quadratic_program) from qiskit_aer.primitives import Sampler, Estimator from qiskit_algorithms.optimizers import SPSA from queasars.minimum_eigensolvers.base.termination_criteria import BestIndividualRelativeChangeTolerance from queasars.minimum_eigensolvers.evqe.evqe import EVQEMinimumEigensolverConfiguration # The EVQEMinimumEigensolver needs a sampler and can also use an estimator. # Here we use the sampler and estimator provided by the qiskit_aer simulator. sampler_primitive = Sampler() estimator_primitive = Estimator() # The EVQEMinimumEigensolver also needs a qiskit optimizer. It should be # configured to terminate quickly, so that mutations are not overtly expensive. # Here we use the SPSA optimizer with a very limited amount of iterations and a # large step size. optimizer = SPSA(maxiter=10, perturbation=0.2, learning_rate=0.2, trust_region=True) # To help the EVQEMinimumEigensolver deal correctly with terminations based # on the amount of circuit evaluations used, an estimate can be given for how # many circuit evaluations the optimizer uses per optimization run. # SPSA makes two measurements per iteration, which means in total it will # need 20 circuit evaluations for 10 iterations. optimizer_n_circuit_evaluations = 20 # To specify when the EVQEMinimumEigensolver should terminate either max_generations, # max_circuit_evaluations or a termination_criterion should be given. # Here we choose to terminate once the expectation value of the best individual of a generation # changes by less than 0.5% between generations. max_generations = None max_circuit_evaluations = None termination_criterion = BestIndividualRelativeChangeTolerance(minimum_relative_change=0.005) # A random seed can be provided to control the randomness of the evolutionary process. random_seed = 0 # The population size determines how many individuals are evaluated each generation. # With a higher population size, fewer generations might be needed, but this also # makes each generation more expensive to evaluate. A reasonable range might be # 10 - 100 individuals per population. Here we use a population size of 25. population_size = 25 # If the optimization algorithm can't deal with parameter values of 0 at the beginning # of the optimization, they can be randomized here. For this example we don't need this. randomize_initial_population_parameters = False # Determines how many circuit layers apart two individuals need to be, to be considered to # be of a different species. Reasonable values might be in the range 2 - 5. Here we use 3. speciation_genetic_distance_threshold = 3 # The alpha and beta penalties penalize quantum circuits of increasing depth (alpha) and # increasing amount of controlled rotations (beta). increase them if the quantum circuits get to # deep or complicated. For now we will use values of 0.1 for both penalties. selection_alpha_penalty = 0.1 selection_beta_penalty = 0.1 # The parameter search probability determines how likely an individual is mutated by optimizing # all it's parameter values. This should not be too large as this is costly. Here we will use # a probability of 0.25. parameter_search_probability = 0.25 # The topological search probability determines how likely a circuit layer is added to an individual # as a mutation. This should be a higher probability to encourage exploration of different circuits. # Here we will use a likelihood of 0.5 topological_search_probability = 0.5 # The layer removal probability determines how likely circuit layers are removed from an individual # as a mutation. This is a very disruptive mutation and should only be used sparingly to counteract # circuit growth. Here we will use a probability of 0.1 layer_removal_probability = 0.1 # An executor for launching parallel computation can be specified. # This can be a dask Client or a python ThreadPoolExecutor. If None is # specified a ThreadPoolExecutor with population_size many threads will # be used parallel_executor = None # Discerns whether to only allow mutually exclusive access to the Sampler and # Estimator primitive respectively. This is needed if the Sampler or Estimator are not threadsafe and # a ThreadPoolExecutor with more than one thread or a Dask Client with more than one thread per process is used. # For safety reasons this is enabled by default. If the sampler and estimator are threadsafe disabling this # option may lead to performance improvements mutually_exclusive_primitives = True configuration = EVQEMinimumEigensolverConfiguration( sampler=sampler_primitive, estimator=estimator_primitive, optimizer=optimizer, optimizer_n_circuit_evaluations=optimizer_n_circuit_evaluations, max_generations=max_generations, max_circuit_evaluations=max_circuit_evaluations, termination_criterion=termination_criterion, random_seed=random_seed, population_size=population_size, randomize_initial_population_parameters=randomize_initial_population_parameters, speciation_genetic_distance_threshold=speciation_genetic_distance_threshold, selection_alpha_penalty=selection_alpha_penalty, selection_beta_penalty=selection_beta_penalty, parameter_search_probability=parameter_search_probability, topological_search_probability=topological_search_probability, layer_removal_probability=layer_removal_probability, parallel_executor=parallel_executor, mutually_exclusive_primitives=mutually_exclusive_primitives, ) from queasars.minimum_eigensolvers.evqe.evqe import EVQEMinimumEigensolver eigensolver = EVQEMinimumEigensolver(configuration=configuration) import logging logger = logging.getLogger("queasars.minimum_eigensolvers.base.evolving_ansatz_minimum_eigensolver") handler = logging.StreamHandler() logger.setLevel(logging.INFO) logger.addHandler(handler) result = eigensolver.compute_minimum_eigenvalue(operator=hamiltonian) quasi_distribution = result.eigenstate.binary_probabilities() from qiskit.visualization import plot_distribution plot_distribution(quasi_distribution, number_to_keep=10) for bitstring, probability in quasi_distribution.items(): if probability < 0.05: continue bitlist = [int(char) for char in bitstring][::-1] converted_variables = integer_converter.interpret(bitlist) print("probability: ", probability) print("variable values: ", converted_variables) print("")
https://github.com/qclib/qclib
qclib
# Copyright 2021 qclib project. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ cvo-qram """ import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import UGate from qiskit.quantum_info import Operator from qclib.util import _compute_matrix_angles from qclib.gates.initialize_sparse import InitializeSparse from qclib.gates.mcg import Mcg from qclib.gates.ldmcsu import LdMcSpecialUnitary # pylint: disable=maybe-no-member class CvoqramInitialize(InitializeSparse): """ Initializing the Amplitude Distribution of a Quantum State This class implements a sparse state preparation gate. """ def __init__(self, params, label=None, opt_params=None): self._get_num_qubits(params) self.norm = 1 self.anc = None self.aux = None self.memory = None self.control = None default_with_aux = True if opt_params is None: self.with_aux = default_with_aux self.mcg_method = 'linear' else: if opt_params.get("with_aux") is None: self.with_aux = default_with_aux else: self.with_aux = opt_params.get("with_aux") if opt_params.get("mcg_method") is None: self.mcg_method = 'linear' else: self.mcg_method = opt_params.get("mcg_method") if label is None: label = "CVOSP" super().__init__("cvoqram", self.num_qubits, params.items(), label=label) def _define(self): self.definition = self._define_initialize() def _define_initialize(self): """Initialize quantum registers""" self.anc = QuantumRegister(self.num_qubits - 1, name="anc") self.aux = QuantumRegister(1, name="u") self.memory = QuantumRegister(self.num_qubits, name="m") if self.with_aux: circuit = QuantumCircuit(self.aux, self.anc, self.memory) else: self.anc = None circuit = QuantumCircuit(self.aux, self.memory) self.norm = 1 circuit.x(self.aux[0]) for k, (binary_string, feature) in enumerate(self.params): self.control = self._select_controls(binary_string) self._flip_flop(circuit) self._load_superposition(circuit, feature, self.control, self.memory) if k < len(self.params) - 1: self._flip_flop(circuit) else: break return circuit def _flip_flop(self, circuit): for k in self.control: circuit.cx(self.aux[0], self.memory[k]) @staticmethod def _select_controls(binary_string): control = [] for k, bit in enumerate(binary_string[::-1]): if bit == "1": control.append(k) return control def _mcuvchain(self, circuit, alpha, beta, phi): """ N-qubit controlled-unitary gate """ lst_ctrl = self.control lst_ctrl_reversed = list(reversed(lst_ctrl)) circuit.rccx( self.memory[lst_ctrl_reversed[0]], self.memory[lst_ctrl_reversed[1]], self.anc[self.num_qubits - 2], ) tof = {} i = self.num_qubits - 1 for ctrl in lst_ctrl_reversed[2:]: circuit.rccx(self.anc[i - 1], self.memory[ctrl], self.anc[i - 2]) tof[ctrl] = [i - 1, i - 2] i -= 1 circuit.cu(alpha, beta, phi, 0, self.anc[i - 1], self.aux[0]) for ctrl in lst_ctrl[:-2]: circuit.rccx(self.anc[tof[ctrl][0]], self.memory[ctrl], self.anc[tof[ctrl][1]]) circuit.rccx( self.memory[lst_ctrl[-1]], self.memory[lst_ctrl[-2]], self.anc[self.num_qubits - 2] ) def _load_superposition(self, circuit, feature, control, memory): """ Load pattern in superposition """ theta, phi, lam = _compute_matrix_angles(feature, self.norm) if len(control) == 0: circuit.u(theta, phi, lam, self.aux[0]) elif len(control) == 1: circuit.cu(theta, phi, lam, 0, memory[control[0]], self.aux[0]) else: if self.with_aux: self._mcuvchain(circuit, theta, phi, lam) else: gate = UGate(theta, phi, lam) if self.mcg_method == 'qiskit': circuit.append(gate.control(len(control)), memory[control] + [self.aux[0]]) elif self.mcg_method == 'barenco': gate_op = Operator(gate).data LdMcSpecialUnitary.ldmcsu(circuit, gate_op, memory[control], [self.aux[0]]) else: gate_op = Operator(gate).data Mcg.mcg(circuit, gate_op, memory[control], [self.aux[0]]) self.norm = self.norm - np.absolute(np.power(feature, 2)) @staticmethod def initialize(q_circuit, state, qubits=None, opt_params=None): if qubits is None: q_circuit.append( CvoqramInitialize(state, opt_params=opt_params), q_circuit.qubits ) else: q_circuit.append(CvoqramInitialize(state, opt_params=opt_params), qubits)
https://github.com/rubenandrebarreiro/summer-school-on-quantum-computing-software-for-near-term-quantum-devices-2020
rubenandrebarreiro
# Importing matplotlib, "in line" %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) provider = IBMQ.load_account() # In Jupyter Notebooks we can display this nicely using Latex. # If not using Jupyter Notebooks you may need to remove the # array_to_latex function and use print() instead. from qiskit_textbook.tools import array_to_latex # Create a Quantum Register for 2 Qubits (Quantum Bits), with a Total of 4 (2^2) Possible Processed States qr = QuantumRegister(2) # Create a Classical Register for 2 Bits (Classical Bits), with a Total of 2 Possible Processed States cr = ClassicalRegister(2) # Create a Quantum Circuit, with the two previously created Quantum and Classical Registers qc = QuantumCircuit(qr,cr) # Let's setup the set of necessary instructions, in order to build a Quantum Circuit, # that implements a Quantum Maximally Entangled State in Quantum System with 2 Qubits (Quantum Bits), # in which if a Qubit it's measured, independently of its outcome, the other Qubit (Quantum Bit) # will collapse automatically, no matter the distance that separates the both Qubits (Quatum Bits), # holding the same outcome, i.e., what's it's called, a Bell State, in Quantum Physics/Mechanics # Per example: # a) If the 1st Qubit (Quantum Bit) it's measured and collapse to the Classical State |0>, # it's possible to state with certainty that the 2nd Qubit (Quantum Bit) will also collapse to # the Classical State |0>, for sure; # b) If the 1st Qubit (Quantum Bit) it's measured and collapse to the Classical State |1>, # it's possible to state with certainty that the 2nd Qubit (Quantum Bit) will also collapse to # the Classical State |1>, for sure; # Note: # - The observations derived from this experiment it's also valid, following the same idea, # when the 2nd Qubit (Quantum Bit) it's measured instead of the 1st Qubit (Quantum Bit) # Any Quantum Entanglement of States, it's implemented using the CX/CNOT Quantum Logic Gate # (Controlled-X/Controlled-NOT), which acts on 2 Qubits (Quantum Bits), described as the following: # - 1) Control Qubit (Quantum Bit); # - 2) Target Qubit (Quantum Bit); # This CX/CNOT Quantum Logic Gate (Controlled-X/Controlled-NOT) it's simple and # has the following behaviour: # - If the Control Qubit (Control Quantum Bit) it's set as |1>, # performs the Pauli-X Quantum Logic Gate Operator (X Quantum Logic Gate Operator) # onto the the Target Qubit (Target Quantum Bit); # - Otherwise, if the Control Qubit (Control Quantum Bit) it's set as |0>, # don't perform any Quantum Logic Gate Operator (X Quantum Logic Gate Operator) # onto the the Target Qubit (Target Quantum Bit), letting it unchanged; # The CX/CNOT Quantum Logic Gate (Controlled-X/Controlled-NOT) has a behaviour practically equal to a # XOR Classical Logic Gate Operator (eXclusive OR Classical Logic Gate Operator): # - CNOT x |q1,q2> = |q1, (q1 ⊕ q2)>; # Note: # - In Mathematics, the XOR Classical Logic Gate Operator (eXclusive OR Classical Logic Gate Operator) # it's represented by the Modulo 2 Arithmetic Addition Operator # (i.e., represented by the mathematically notation of ⊕); # Initially, the Quantum Circuit has the both Qubits (Quantum Bits) set as |0>, # thus the Quantum Circuit, it's represented as the Tensor Product of that two Qubits (Quantum Bits), # forming a new Quantum State defined as |00>: # - |Ψ> = |q1>|q2> = |0>|0> = |0> ⊗ |0> = |00>; # Steps to build this Quantum Circuit: # 1) In order to, explore all the possible situations of this Experiment, # let's put the Control Qubit (Control Quantum Bit) in this Quantum Circuit, # in a Quantum Superposition of States, applying the Hadamard Quantum Logic Gate Operator to it, # letting the Quantum System defined as: # - |Ψ> = 1/√2 x (|00> + |10>), # where the 1st Qubit (Quantum Bit) it's in Quantum Superposition of States; qc.h(0) # 2) In order to, explore all the possible situations of this Experiment, # let's put the Control Qubit (Control Quantum Bit) in this Quantum Circuit, # in a Quantum Superposition of States, applying the Hadamard Quantum Logic Gate Operator to it, # letting the Quantum System defined as: # - |Ψ> = 1/√2 x (|00> + |11>), where: # - The 1st Qubit (Quantum Bit) it's in Quantum Superposition of States; # - The 2nd Qubit (Quantum Bit) it's a result of the Pauli-X Quantum Logic Quantum Gate Operator, # in the cases that the Control Qubit (Control Quantum Bit) it's set as |1>, i.e., # the 2nd term of the Quantum System, where |10> => |11>, # after being applied the CX/CNOT Quantum Logic Gate (Controlled-X/Controlled-NOT); qc.cnot(0,1) # Draw the Quantum Circuit for the Bell State, in a graphically representation qc.draw() # Print the Quantum Circuit for the Bell State, in a text representation print(qc) # Print the Backends available in the Aer Module of the IBM Qiskit Library: # - The Aer Module, it's the Module responsible for the Simulator of the IBM Qiskit Libraries; Aer.backends() # Getting the Backend for the Unitary Representation # (i.e., the Quantum State represented as an Unitary Matrix) backend = Aer.get_backend('unitary_simulator') unitary = execute(qc,backend).result().get_unitary() array_to_latex(unitary, pretext="\\text{Quantum Circuit (Unitary Matrix) = }\n") # Getting the Backend for the Statevector Representation # (i.e., the Quantum State represented as State Vector) statevector_backend = Aer.get_backend('statevector_simulator') final_state = execute(qc,statevector_backend).result().get_statevector() array_to_latex(final_state, pretext="\\text{Quantum Circuit (Statevector) = }\n", precision = 1) # Plot the Bloch Spheres of the previously defined Quantum System (or, try it...), # representing a Bell State # Note: # - In fact it's not possible to plot Bloch Spheres representing a whole Quantum System, # which it's currently in a Quantum Entanglement of States, in IBM Qiskit; plot_bloch_multivector(final_state) # But, it's possible to plot the Q-Sphere of this Quantum Circuit # (a "linear" combination of the several Bloch Spheres, involved) of # the previously defined Quantum System, representing a Bell State plot_state_qsphere(final_state) # Now, that the Quantum Circuit it's practically defined, let's apply a Barrier to it, in order to, # ensure that all the previous Quantum Logic Gate Operators are applied correctly qc.barrier() # Draw the Quantum Circuit again, after the Barrier be applied in it qc.draw() # Measure the State of the both Qubits (Quantum Bits), contained in the Quantum Circuit qc.measure(0,0) qc.measure(1,1) # Draw the Quantum Circuit again, after the Measurement of the States be applied in it qc.draw() # Now, let's execute the Quantum Circuit in the QASM Simulator of the Aer Module, # of the IBM Qiskit Library backend = Aer.get_backend('qasm_simulator') counts = execute(qc,backend,shots=2048).result().get_counts() # Print the Counts of the Frequencies, resulting from this Experiment print(counts) # Plot the Counts of the Frequencies, resulting from this Experiment, through a Histogram # (i.e., a Distribution of the Probabilities) plot_histogram(counts) # Import the IBM Q Experience, from the IBM Qiskit Library from qiskit import IBMQ # Update your account info saved locally IBMQ.update_account() # Run everytime to load your account info saved locally IBMQ.load_account() # Get a Provider, from the IBM Q Hub provider = IBMQ.get_provider(hub='ibm-q') # Print available Backends, from the Provider set before provider.backends() # Import the "Least Busy" function, in order to get a "Least Busy" Backend from qiskit.providers.ibmq import least_busy # Filter the available Backends, in order to get a list of "Large Enough Real Quantum Devices", # i.e., containing 2 or more 2 Qubits (Quantum Bits) large_enough_devices = provider.backends(filters = lambda b: b.configuration().n_qubits >= 2 and not b.configuration().simulator and b.status().operational==True) # Or, select the "Least Busy" Backend, from the list of "Large Enough Real Quantum Devices" backend = least_busy(large_enough_devices) # Print the Best Backend available (i.e., the Least Busy Backend) print("The Best Backend is: " + backend.name()) # Execute a Job for this Quantum Circuit, executing the Experiment, for 8192 Shots job_exp = execute(qc,backend=backend,shots=8192) # Get the Experiment Result from the previous executed Job for this Quantum Circuit exp_result = job_exp.result() # Get the Measurement Results, from the previous Experiment Result, # executed by the Job for this Quantum Circuit exp_measurement_result = exp_result.get_counts(qc) # Print the Measurement Results, from the previous Experiment Result, # executed by the Job for this Quantum Circuit print(exp_measurement_result) # Plot the Histogram (i.e., Frequencies) for the Measurement Results, # from the previous Experiment Result, executed by the Job for this Quantum Circuit plot_histogram(exp_measurement_result)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl')
https://github.com/MuhammadMiqdadKhan/Solution-of-IBM-s-Global-Quantum-Challenge-2020
MuhammadMiqdadKhan
%matplotlib inline # Importing standard Qiskit libraries import random from qiskit import execute, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from may4_challenge.ex3 import alice_prepare_qubit, check_bits, check_key, check_decrypted, show_message # Configuring account provider = IBMQ.load_account() backend = provider.get_backend('ibmq_qasm_simulator') # with this simulator it wouldn't work \ # Initial setup random.seed(84) # do not change this seed, otherwise you will get a different key # This is your 'random' bit string that determines your bases numqubits = 100 bob_bases = str('{0:0100b}'.format(random.getrandbits(numqubits))) def bb84(): print('Bob\'s bases:', bob_bases) # Now Alice will send her bits one by one... all_qubit_circuits = [] for qubit_index in range(numqubits): # This is Alice creating the qubit thisqubit_circuit = alice_prepare_qubit(qubit_index) # This is Bob finishing the protocol below bob_measure_qubit(bob_bases, qubit_index, thisqubit_circuit) # We collect all these circuits and put them in an array all_qubit_circuits.append(thisqubit_circuit) # Now execute all the circuits for each qubit results = execute(all_qubit_circuits, backend=backend, shots=1).result() # And combine the results bits = '' for qubit_index in range(numqubits): bits += [measurement for measurement in results.get_counts(qubit_index)][0] return bits # Here is your task def bob_measure_qubit(bob_bases, qubit_index, qubit_circuit): # #qc = QuantumCircuit() if bob_bases[qubit_index] == '1': qubit_circuit.h(0) else: pass #return qc #qubit_circuit.cx(bob_bases, qubit_index) # insert your code here to measure Alice's bits qubit_circuit.measure(0, 0) # ... bits = bb84() print('Bob\'s bits: ', bits) check_bits(bits) alice_bases = '1000000000010001111111001101100101000111110100110111111000110000011000001001100011100111010010000110' # Alice's bases bits bob_bases = '1100111010011111111111110100000111010100100010011001001110100001010010111011010001011001111111011111' #bob ='1000010000010000001110100010100111100101000111001111100010000110000000011110110101101101101001011000' #bob_bases = bob[::-1] #print(bob_bases) #def getKey(): key = "" for qubit_index in range(len(bob_bases)): if alice_bases[qubit_index] == bob_bases[qubit_index]: key = key + bits[qubit_index] else: continue print(key) check_key(key) m = '0011011010100011101000001100010000001000011000101110110111100111111110001111100011100101011010111010111010001'\ '1101010010111111100101000011010011011011011101111010111000101111111001010101001100101111011' # encrypted message key='10000010001110010011101001010000110000110011100000100000100011100100111010010100001100001100111000001000001000111001001110100101000011000011001110000010000010001110010011101001010000110000110011100000' c=int(m, 2) ^ int(key, 2) decrypted = "{0:b}".format(c) print(decrypted) check_decrypted(decrypted) MORSE_CODE_DICT = { 'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', 'f':'..-.', 'g':'--.', 'h':'....', 'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--', 'n':'-.', 'o':'---', 'p':'.--.', 'q':'--.-', 'r':'.-.', 's':'...', 't':'-', 'u':'..-', 'v':'...-', 'w':'.--', 'x':'-..-', 'y':'-.--', 'z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-', '(':'-.--.', ')':'-.--.-'} # insert your code here to decode Alice's Morse code #I solved this part of excercise manually but I will upload it's code soon IA solution="http://reddit.com/R/MAY4QUANTUM" show_message(solution)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import ( ElectronicStructureDriverType, ElectronicStructureMoleculeDriver, PySCFDriver, ) from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer from qiskit_nature.settings import settings settings.dict_aux_operators = True molecule = Molecule( geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1 ) driver = ElectronicStructureMoleculeDriver( molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF ) # or equivalently: driver = PySCFDriver.from_molecule(molecule, basis="sto3g") transformer = FreezeCoreTransformer() problem = ElectronicStructureProblem(driver, transformers=[transformer]) # Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so: second_q_ops = problem.second_q_ops() hamiltonian = second_q_ops["ElectronicEnergy"] print(hamiltonian) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo from qiskit_nature.second_q.transformers import FreezeCoreTransformer molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1) driver = PySCFDriver.from_molecule(molecule, basis="sto3g") # this is now done explicitly problem = driver.run() transformer = FreezeCoreTransformer() # and you also apply transformers explicitly problem = transformer.transform(problem) hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import PySCFDriver molecule = Molecule( geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1 ) driver = PySCFDriver.from_molecule(molecule) result = driver.run() print(type(result)) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1) driver = PySCFDriver.from_molecule(molecule, basis="sto3g") result = driver.run() print(type(result)) from qiskit_nature.drivers.second_quantization import FCIDumpDriver path_to_fcidump = "aux_files/h2.fcidump" driver = FCIDumpDriver(path_to_fcidump) result = driver.run() print(type(result)) from qiskit_nature.second_q.formats.fcidump import FCIDump path_to_fcidump = "aux_files/h2.fcidump" fcidump = FCIDump.from_file(path_to_fcidump) print(type(fcidump)) from qiskit_nature.second_q.formats.fcidump_translator import fcidump_to_problem problem = fcidump_to_problem(fcidump) print(type(problem)) from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer transformer = FreezeCoreTransformer() driver = PySCFDriver() transformed_result = transformer.transform(driver.run()) print(type(transformed_result)) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.transformers import FreezeCoreTransformer transformer = FreezeCoreTransformer() driver = PySCFDriver() transformed_result = transformer.transform(driver.run()) print(type(transformed_result)) from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer driver = PySCFDriver() transformer = FreezeCoreTransformer() problem = ElectronicStructureProblem(driver, transformers=[transformer]) # we trigger driver.run() implicitly like so: second_q_ops = problem.second_q_ops() hamiltonian_op = second_q_ops.pop("ElectronicEnergy") aux_ops = second_q_ops from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.transformers import FreezeCoreTransformer driver = PySCFDriver() problem = driver.run() transformer = FreezeCoreTransformer() problem = transformer.transform(problem) hamiltonian_op, aux_ops = problem.second_q_ops() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Depth pass testing""" import unittest from qiskit import QuantumCircuit, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler.passes import Depth from qiskit.test import QiskitTestCase class TestDepthPass(QiskitTestCase): """Tests for Depth analysis methods.""" def test_empty_dag(self): """Empty DAG has 0 depth""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = Depth() _ = pass_.run(dag) self.assertEqual(pass_.property_set["depth"], 0) def test_just_qubits(self): """A dag with 8 operations and no classic bits""" # ┌───┐ ┌───┐┌───┐ # q0_0: ┤ H ├──■────■────■────■──┤ X ├┤ X ├ # ├───┤┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐└─┬─┘└─┬─┘ # q0_1: ┤ H ├┤ X ├┤ X ├┤ X ├┤ X ├──■────■── # └───┘└───┘└───┘└───┘└───┘ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[1], qr[0]) dag = circuit_to_dag(circuit) pass_ = Depth() _ = pass_.run(dag) self.assertEqual(pass_.property_set["depth"], 7) def test_depth_one(self): """A dag with operations in parallel and depth 1""" qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) dag = circuit_to_dag(circuit) pass_ = Depth() _ = pass_.run(dag) self.assertEqual(pass_.property_set["depth"], 1) def test_depth_control_flow(self): """A DAG with control flow still gives an estimate.""" qc = QuantumCircuit(5, 1) qc.h(0) qc.measure(0, 0) with qc.if_test((qc.clbits[0], True)) as else_: qc.x(1) qc.cx(2, 3) with else_: qc.x(1) with qc.for_loop(range(3)): qc.z(2) with qc.for_loop((4, 0, 1)): qc.z(2) with qc.while_loop((qc.clbits[0], True)): qc.h(0) qc.measure(0, 0) pass_ = Depth(recurse=True) pass_(qc) self.assertEqual(pass_.property_set["depth"], 16) if __name__ == "__main__": unittest.main()
https://github.com/carstenblank/dc-qiskit-algorithms
carstenblank
import math from typing import List, Union, Tuple import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit import Gate from qiskit.circuit.library import RYGate, RZGate from scipy import sparse from scipy.sparse.linalg import norm from dc_qiskit_algorithms import UniformRotationGate from dc_qiskit_algorithms.MottonenStatePreparation import get_alpha_y, get_alpha_z, MottonenStatePreparationGate def _chi(l): return 1 + sum([2 ** (i - 1) for i in range(1, l)]) class ControlledStatePreparationGate(Gate): _debug_flag: bool = False def __init__(self, matrix: sparse.dok_matrix) -> None: """ The matrix has the following structure: A = (a_ij) with i being the control and j being the target. Also, each row must be normalized, i.e., \sum_j |a_ij|^2 = 1 The matrix is the quantum equivalent of a stochastic matrix therefore. :param: matrix that has the columns as subspaces and rows as the states to create in them """ if isinstance(matrix, list) or isinstance(matrix, np.ndarray): matrix = sparse.dok_matrix(matrix) # The columns define the target states, i.e. the space for the controlled state preparation num_targets_qb = int(math.ceil(math.log2(matrix.shape[1]))) self.num_targets_qb = num_targets_qb # The rows define the number of control states. If there is one row, this is normal state preparation. num_controls_qb = int(math.ceil(math.log2(matrix.shape[0]))) self.num_controls_qb = num_controls_qb super().__init__("iso_matrix", num_qubits=num_controls_qb + num_targets_qb, params=[]) # Of course we save the matrix but we need to calculate the absolute value and the angle/phase # matrix for the core logic self.matrix: Union[sparse.dok_matrix] = matrix matrix_abs = sparse.dok_matrix(matrix.shape) matrix_angle = sparse.dok_matrix(matrix.shape) for (i, j), v in self.matrix.items(): matrix_abs[i, j] = np.absolute(v) matrix_angle[i, j] = np.angle(v) self.matrix_abs = matrix_abs self.matrix_angle = matrix_angle def set_debug_flag(self, flag: bool = False) -> 'ControlledStatePreparationGate': """ If this is used, not the standard routine is used (Möttönen state preparation using uniform rotations) but a manual form of several controlled rotations. This makes the plotting and therefore the debugging a lot easier, at the expense of a lot of computational time and a strong increase of cx gates when later executed. Therefore it is really only for debugging! :param flag: false is the default, for true you get the multiple controlled rotations. :return: None """ self._debug_flag = flag return self def _to_angle_matrix_y(self) -> Union[sparse.dok_matrix]: # First, for each column, the angles that lead to this state need to be computed. matrix_A = sparse.dok_matrix((self.matrix_abs.shape[0], self.matrix_abs.shape[1] - 1)) for row_no in range(self.matrix_abs.shape[0]): amplitudes_row: sparse.csc_matrix = self.matrix_abs.getrow(row_no).T # The reversed is necessary as the "highest" qubit is the one with the least controls # imagine a circuit the where the highest qubits control the lower one. Yes this is all but numbering # so that this is why I need to add this comment. angle_row_list_y: List[sparse.dok_matrix] = [ get_alpha_y(amplitudes_row.todok(), self.num_targets_qb, k) for k in reversed(range(1, self.num_targets_qb + 1)) ] angles_row = sparse.vstack(angle_row_list_y) matrix_A[row_no, :] = angles_row.T return matrix_A def _to_angle_matrix_z(self) -> Tuple[sparse.spmatrix, sparse.spmatrix]: # First, for each column, the angles that lead to this state need to be computed. matrix_A = sparse.dok_matrix((self.matrix_angle.shape[0], self.matrix_angle.shape[1] - 1)) for row_no in range(self.matrix_angle.shape[0]): amplitudes_row: sparse.csc_matrix = self.matrix_angle.getrow(row_no).T # The reversed is necessary as the "highest" qubit is the one with the least controls # imagine a circuit the where the highest qubits control the lower one. Yes this is all but numbering # so that this is why I need to add this comment. angle_row_list_z: List[sparse.dok_matrix] = [ get_alpha_z(amplitudes_row.todok(), self.num_targets_qb, k) for k in reversed(range(1, self.num_targets_qb + 1)) ] angles_row = sparse.vstack(angle_row_list_z) matrix_A[row_no, :] = angles_row.T # A global phase is to be expected on each subspace and must be corrected jointly later. total_depth = max(1, int(np.ceil(np.log2(matrix_A.shape[1])))) recovered_angles = sparse.dok_matrix((matrix_A.shape[0], 1), dtype=float) # Each row is a separate sub-space, and by the algorithm of Möttönen et al # a global phase is to be expected. So we calculate it by... for row in range(matrix_A.shape[0]): # ... going through each row and applying rz rotations essentially, but not on all # involved qubits, just for one branch as the global phase must exist, well, globally. col = 0 evaluation = 1 for depth in range(total_depth): evaluation *= np.exp(-0.5j * matrix_A[row, col]) col += 2**depth # After calculating the amplitude of one branch, I take the angle/phase # This is still not the global phase, we will get that later... recovered_angles[row, 0] = np.angle(evaluation) # ... exactly here we take the difference of the phase of each subspace and the angle # matrix. That is the global phase of that subspace! global_phases: sparse.spmatrix = self.matrix_angle[:, 0] - recovered_angles return matrix_A, global_phases def _define(self): # The y angle matrix stands for the absolute value, while the z angles stand for phases # The difficulty lies in the "global" phases that must be later accounted for in each subspace y_angle_matrix = self._to_angle_matrix_y() z_angle_matrix, global_phases = self._to_angle_matrix_z() if self._debug_flag: qc_y, qc_z = self._create_debug_circuit(y_angle_matrix, z_angle_matrix, global_phases) else: qc_y, qc_z = self._create_production_circuit(y_angle_matrix, z_angle_matrix, global_phases) qc = qc_y & qc_z self._definition = qc def _create_production_circuit(self, y_angle_matrix, z_angle_matrix, global_phases): # As the subspace phase correction is a very expensive module, we only want to do it if the # z rotation matrix is non-zero! no_z_rotations = abs(sparse.linalg.norm(z_angle_matrix)) < 1e-6 control = QuantumRegister(self.num_controls_qb, "q^c") target = QuantumRegister(self.num_targets_qb, "q^t") qc_y = QuantumCircuit(control, target, name=self.name) qc_z = QuantumCircuit(control, target, name=self.name) # We do a set of uniformly controlled operations from the control register on each target qubit. # iterating through the target means that a target qubit that has been handled (i.e. was a target of a # uniform rotation) becomes a controlling qubit. # Thus, when creating the qargs for the operation, there are going to be all qubits of the control register # plus those target register qubits that have been used plus the current target qubit as the target # of the uniform rotation for l in range(1, self.num_targets_qb + 1): # Using slicing to get the correct target register qubits, start at the last, go to the (l+1) last. # The ordering of the qubits in the register is a bit weird... explanation: # ctr = [ctr0, ctr1, ctr2, ctr3], tgt = tgt0, tgt1, tgt2, tgt3 # l = 2: qargs = [ctr0, ctr1, ctr2, ctr,3, tgt3, tgt2] # ^==> target of operation # the Möttönen et al. scheme uses the idea to move a ket |a> to |0> via U. The inverse of this operation # thus will take |0> to the desired state |a>. The first step of constructing U is to cancel the first qubit # (tgt0) to be only having the ground state contributing in a product state, this is controlled # by [tgt1, tgt2, tgt3]. Then (tgt1) is targeted (controls [tgt2, tgt3]) until (tgt3) is reached # (no control). This is inverted, thus first (tgt3) until (tgt0) with corresponding controls. qargs = list(control) + target[-1:-1-l:-1] # If there are no z-rotations we save a lot of gates, so we want to rule that out if not no_z_rotations: # The corresponding rotational angles are given in the Z-angle matrix by the function chi selecting # on the columns according to the operational parameter l. angles_z: sparse.spmatrix = z_angle_matrix[:, range(_chi(l) - 1, _chi(l + 1) - 1)] # The column-first Fortran-style reshaping to create one angle vector angles_z = angles_z.reshape(-1, 1, order='F') # The negative of the angles is needed to implement the inverse (as described above) gate_z = UniformRotationGate(gate=lambda a: RZGate(a), alpha=angles_z.todok()) # FIXME: removing the - qc_z.append(gate_z, qargs) # The uniform rotation for the y rotation will take care of the absolute value # The corresponding rotational angles are given in the Z-angle matrix by the function chi selecting # on the columns according to the operational parameter l. angles_y: sparse.spmatrix = y_angle_matrix[:, range(_chi(l) - 1, _chi(l + 1) - 1)] # The column-first Fortran-style reshaping to create one angle vector angles_y = angles_y.reshape(-1, 1, order='F') # The negative of the angles is needed to implement the inverse (as described above) gate_y = UniformRotationGate(gate=lambda a: RYGate(a), alpha=angles_y.todok()) # FIXME: removing the - qc_y.append(gate_y, qargs) if not no_z_rotations: # A relative phase correction is pretty intensive: a state preparation on the control global_phase_correction = MottonenStatePreparationGate( sparse.dok_matrix(np.exp(1.0j * global_phases.toarray())), neglect_absolute_value=True ) qc_z.append(global_phase_correction, qargs=control) return qc_y, qc_z def _create_debug_circuit(self, y_angle_matrix, z_angle_matrix, global_phases): # As the subspace phase correction is a very expensive module, we only want to do it if the # z rotation matrix is non-zero! no_z_rotations = abs(sparse.linalg.norm(z_angle_matrix)) < 1e-6 control = QuantumRegister(self.num_controls_qb, "q^c") target = QuantumRegister(self.num_targets_qb, "q^t") qc_y = QuantumCircuit(control, target, name=self.name) qc_z = QuantumCircuit(control, target, name=self.name) for row in range(y_angle_matrix.shape[0]): qc_y_row = QuantumCircuit(control, target, name=self.name) for (_, j), angle in y_angle_matrix.getrow(row).todok().items(): num_extra_control = int(np.floor(np.log2(j + 1))) num_control = len(control) + num_extra_control val_control = row + 2 ** len(control) * int(j - (2 ** num_extra_control - 1)) gate = RYGate(angle).control(num_ctrl_qubits=num_control, ctrl_state=val_control) qargs = list(control) + target[-1:-2 - j:-1] qc_y_row.append(gate, qargs) qc_y &= qc_y_row if not no_z_rotations: for row in range(z_angle_matrix.shape[0]): for (_, j), angle in z_angle_matrix.getrow(row).todok().items(): num_extra_control = int(np.floor(np.log2(j + 1))) num_control = len(control) + num_extra_control val_control = row + 2 ** len(control) * int(j - (2 ** num_extra_control - 1)) gate = RZGate(angle).control(num_ctrl_qubits=num_control, ctrl_state=val_control) qargs = list(control) + target[-1:-2 - j:-1] qc_z.append(gate, qargs) if not no_z_rotations: # A relative phase correction is pretty intensive: a state preparation on the control global_phase_correction = MottonenStatePreparationGate( sparse.dok_matrix(np.exp(1.0j * global_phases.toarray())), neglect_absolute_value=True ) qc_z.append(global_phase_correction, qargs=control) qc_y.barrier() qc_z.barrier() return qc_y, qc_z
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# I am a comment in python print("Hello From Quantum World :-)") # please run this cell # import the objects from qiskit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from random import randrange # create a quantum circuit and its register objects qreg = QuantumRegister(2) # my quantum register creg = ClassicalRegister(2) # my classical register circuit = QuantumCircuit(qreg,creg) # my quantum circuit # apply a Hadamard gate to the first qubit circuit.h(qreg[0]) # set the second qubit to |1> circuit.x(qreg[1]) # apply CNOT(first_qubit,second_qubit) circuit.cx(qreg[0],qreg[1]) # measure the both qubits circuit.measure(qreg,creg) print("The execution of the cell was completed, and the circuit was created :)") ## execute the circuit 100 times job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=1024) # get the result counts = job.result().get_counts(circuit) print(counts) # draw circuit circuit.draw(output='mpl') # the output will be a "matplotlib.Figure" object
https://github.com/CodeJP97/QHT-2022-WoQ
CodeJP97
import numpy as np # Importing standard Qiskit libraries from qiskit.quantum_info import Statevector from qiskit import QuantumCircuit, transpile, Aer, IBMQ, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # Loading your IBM Quantum account(s) provider = IBMQ.load_account() ## X-gate # FILL IN YOUR CODE HERE # Keep theta<=np.pi theta = np.pi phi = 0 lam = np.pi #ex1_validation([theta, phi,lam]) ## Z-gate # FILL IN YOUR CODE HERE theta = 0 phi = np.pi lam = 0 #ex2_validation([theta, phi,lam]) ## Y-gate # FILL IN YOUR CODE HERE theta = np.pi phi = np.pi/2 lam = np.pi/2 #ex3_validation([theta, phi,lam]) ## Hadamard # FILL IN YOUR CODE HERE theta = np.pi/2 phi = 0 lam = np.pi #ex4_validation([theta, phi, lam]) ## Which rotation corresponds to the gate set H-Y-S-T ? #Circuit: qc=QuantumCircuit(1) qc.h(0) qc.y(0) qc.s(0) qc.t(0) ##FILL IN YOUR ANSWER HERE theta = np.pi/2 phi = 7*np.pi/4 lam = np.pi #Check the result with the u3 rotation gate (arbitrary single qubit rotations) qc2=QuantumCircuit(1) qc2.u3(theta,phi,lam,0) #ex5_validation(qc2) state = Statevector.from_instruction(qc) plot_bloch_multivector(state) state2 = Statevector.from_instruction(qc2) plot_bloch_multivector(state2)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Tests AQC plugin. """ import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import SLSQP from qiskit.converters import dag_to_circuit, circuit_to_dag from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.transpiler import PassManager from qiskit.transpiler.passes import UnitarySynthesis from qiskit.transpiler.synthesis.aqc.aqc_plugin import AQCSynthesisPlugin class TestAQCSynthesisPlugin(QiskitTestCase): """Basic tests of the AQC synthesis plugin.""" def setUp(self): super().setUp() self._qc = QuantumCircuit(3) self._qc.mcx( [ 0, 1, ], 2, ) self._target_unitary = Operator(self._qc).data self._seed_config = {"seed": 12345} def test_aqc_plugin(self): """Basic test of the plugin.""" plugin = AQCSynthesisPlugin() dag = plugin.run(self._target_unitary, config=self._seed_config) approx_circuit = dag_to_circuit(dag) approx_unitary = Operator(approx_circuit).data np.testing.assert_array_almost_equal(self._target_unitary, approx_unitary, 3) def test_plugin_setup(self): """Tests the plugin via unitary synthesis pass""" transpiler_pass = UnitarySynthesis( basis_gates=["rx", "ry", "rz", "cx"], method="aqc", plugin_config=self._seed_config ) dag = circuit_to_dag(self._qc) dag = transpiler_pass.run(dag) approx_circuit = dag_to_circuit(dag) approx_unitary = Operator(approx_circuit).data np.testing.assert_array_almost_equal(self._target_unitary, approx_unitary, 3) def test_plugin_configuration(self): """Tests plugin with a custom configuration.""" config = { "network_layout": "sequ", "connectivity_type": "full", "depth": 0, "seed": 12345, "optimizer": SLSQP(), } transpiler_pass = UnitarySynthesis( basis_gates=["rx", "ry", "rz", "cx"], method="aqc", plugin_config=config ) dag = circuit_to_dag(self._qc) dag = transpiler_pass.run(dag) approx_circuit = dag_to_circuit(dag) approx_unitary = Operator(approx_circuit).data np.testing.assert_array_almost_equal(self._target_unitary, approx_unitary, 3) def test_with_pass_manager(self): """Tests the plugin via pass manager""" qc = QuantumCircuit(3) qc.unitary(np.eye(8), [0, 1, 2]) aqc = PassManager( [ UnitarySynthesis( basis_gates=["u", "cx"], method="aqc", plugin_config=self._seed_config ) ] ).run(qc) approx_unitary = Operator(aqc).data np.testing.assert_array_almost_equal(np.eye(8), approx_unitary, 3)
https://github.com/matteoacrossi/oqs-jupyterbook
matteoacrossi
import numpy as np import matplotlib.pyplot as plt from datetime import datetime import json import copy # Main qiskit imports from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, IBMQ # Error mitigation from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter, MeasurementFilter) # Utility functions from qiskit.tools.jupyter import * from qiskit.tools.monitor import job_monitor from qiskit.providers.jobstatus import JobStatus from bokeh.layouts import row, column from bokeh.models import ColumnDataSource, Slider, CustomJS, Text, DataRange1d, Title from bokeh.plotting import Figure, show, output_file from bokeh.io import output_notebook import pickle #pickle.dump([ys,rs,ts,initial_r],open("witness_pop.p", "wb")) ys,rs,ts,initial_r = pickle.load(open( "witness_pop.p", "rb" )) ys_witness,rs_witness,ts_witness,initial_r = pickle.load(open( "nonmark_witness.p", "rb" )) initial_r = str(len(rs)//2) # Wrap the data in two ColumnDataSources #source_visible = ColumnDataSource(data=dict( # x = ts, y = ys[initial_r])) #source_available = ColumnDataSource(data=ys) source_visible = ColumnDataSource(data=dict( x = ts[initial_r], y = ys[initial_r])) source_available_x = ColumnDataSource(data=ts) source_available_y = ColumnDataSource(data=ys) source_visible2 = ColumnDataSource(data=dict( x = ts[initial_r], y = ys_witness[initial_r])) source_available2_x = ColumnDataSource(data=ts) source_available2_y = ColumnDataSource(data=ys_witness) # Define plot elements plot = Figure(plot_width=300, plot_height=300, x_range = DataRange1d(), y_range=(-.01, 1.01)) plot.line('x', 'y', source=source_visible, legend_label="ρ₁₁(t)", line_width=3, line_alpha=0.6) plot2 = Figure(plot_width=300, plot_height=300, x_range = DataRange1d(), y_range=(-.01, 1.01)) plot2.line('x', 'y', source=source_visible2, legend_label="Non-Mark. Witness", line_width=3, line_alpha=0.6, line_color="#f01001") # Add text text_source = ColumnDataSource({'r_value': [rs[initial_r]]}) r_available = ColumnDataSource(data=rs) text = Text(x=0, x_offset=215, y=.7, text='r_value', text_font_size='15pt', text_align='right') plot.add_glyph(text_source, text) # Add slider slider = Slider(value=int(initial_r), start=np.min([int(i) for i in ys.keys()]), end=np.max([int(i) for i in ys.keys()]), step=1, show_value = False, title = 'R') # Define CustomJS callback, which updates the plot based on selected function # by updating the source_visible ColumnDataSource. slider.callback = CustomJS( args=dict(source_visible = source_visible, source_available_x = source_available_x, source_available_y = source_available_y, source_visible2 = source_visible2, source_available2_x = source_available2_x, source_available2_y = source_available2_y, text_source = text_source, r_available = r_available), code=""" var r_idx = cb_obj.value; // Get the data from the data sources var data_visible = source_visible.data; var data_available_x = source_available_x.data; var data_available_y = source_available_y.data; var data_visible2 = source_visible2.data; var data_available2_x = source_available_x.data; var data_available2_y = source_available2_y.data; // Change y-axis data according to the selected value data_visible.x = data_available_x[r_idx]; data_visible.y = data_available_y[r_idx]; data_visible2.x = data_available_x[r_idx]; data_visible2.y = data_available2_y[r_idx]; // text text_source.data = {'r_value': [String(r_available.data[r_idx])]}; // Update the plot source_visible.change.emit(); source_visible2.change.emit(); """) layout = row(column(plot,slider), plot2) output_file("nonmark_witness.html", title="Non-Markovianity Witness") output_notebook() show(layout)
https://github.com/orionhunts-ai/QiskitRuskit
orionhunts-ai
#IRIS QML Example in Mojo import os import wandb import qiskit import qiskit_ wandb = impy.import_module("wandb")
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt): qc = QuantumCircuit(2) qc.h(1) qc.cx(1,0) qc.h(1) qc.rz(- 2 * dt, 1) qc.rz(dt, 0) qc.h(1) qc.cx(1,0) qc.h(1) qc.rx(dt, [1]) qc.rz(-dt, [0,1]) qc.rx(-dt, [0,1]) qc = qc.reverse_bits() return qc.to_instruction() qc = QuantumCircuit(2) qc.h(1) qc.cx(1,0) qc.h(1) qc.rz(- 2 * np.pi / 6, 1) qc.rz(np.pi / 6, 0) qc.h(1) qc.cx(1,0) qc.h(1) qc.rx(np.pi / 6, [1]) qc.barrier() qc.rz(-np.pi / 6, [0,1]) qc.rx(-np.pi / 6, [0,1]) qc = qc.reverse_bits() qc.draw('mpl') # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate Trot_gate = trotter_gate(dt) # YOUR TROTTERIZATION GOES HERE -- FINISH (end of example) # The final time of the state evolution target_time = np.pi # Number of trotter steps trotter_steps = 12 ### CAN BE >= 4 # Initialize quantum circuit for 3 qubits qr = QuantumRegister(7) qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) qc.x([3]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [qr[3], qr[5]]) qc.cx(qr[3], qr[1]) qc.cx(qr[5], qr[3]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time/trotter_steps}) shots = 8192 reps = 8 # WE USE A NOISELESS SIMULATION HERE backend = Aer.get_backend('qasm_simulator') # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [qr[1], qr[3], qr[5]]) # Display circuit for confirmation # st_qcs[-1].decompose().draw() # view decomposition of trotter gates st_qcs[-1].draw("mpl") # only view trotter gates jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits def state_tomo(result, st_qcs): # The expected final state; necessary to determine state tomography fidelity target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Fit state tomography results tomo_fitter = StateTomographyFitter(result, st_qcs) rho_fit = tomo_fitter.fit(method='lstsq') # Compute fidelity fid = state_fidelity(rho_fit, target_state) return fid # Compute tomography fidelities for each repetition fids = [] for job in jobs: fid = state_tomo(job.result(), st_qcs) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) from qiskit.compiler import transpile t0_qc = transpile(qc, optimization_level=0, basis_gates=["sx","rz","cx"]) t0_qc.draw("mpl") t1_qc = transpile(qc, optimization_level=1, basis_gates=["sx","rz","cx"]) t1_qc.draw("mpl") t2_qc = transpile(qc, optimization_level=2, basis_gates=["sx","rz","cx"]) t2_qc.draw("mpl") t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx","rz","cx"]) t3_qc.draw("mpl") st_qcs = state_tomography_circuits(t2_qc, [qr[1], qr[3], qr[5]]) jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) fids = [] for job in jobs: fid = state_tomo(job.result(), st_qcs) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]]) jobs = [] for _ in range(reps): # execute job = execute(st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) fids = [] for job in jobs: fid = state_tomo(job.result(), st_qcs) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
# This code is a Qiskit project. # (C) Copyright IBM 2023. # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for QPDGate classes.""" import unittest import copy import io import pytest from qiskit import QuantumCircuit, qpy from qiskit.circuit.library.standard_gates import CXGate, XGate, YGate, ZGate from circuit_knitting.cutting.qpd import ( QPDBasis, TwoQubitQPDGate, SingleQubitQPDGate, ) class TestTwoQubitQPDGate(unittest.TestCase): def test_qpd_gate_empty(self): empty_maps = [([], [])] empty_basis = QPDBasis(empty_maps, [1.0]) empty_gate = TwoQubitQPDGate(empty_basis) self.assertEqual(None, empty_gate.basis_id) def test_qpd_gate_bad_idx(self): empty_maps = [([], [])] empty_basis = QPDBasis(empty_maps, [1.0]) empty_gate = TwoQubitQPDGate(empty_basis) with pytest.raises(ValueError) as e_info: empty_gate.basis_id = 1 self.assertEqual("Basis ID out of range", e_info.value.args[0]) def test_qpd_gate_select_basis(self): qpd_maps = [ ([XGate()], [XGate()]), ([YGate()], [YGate()]), ([ZGate()], [ZGate()]), ] qpd_basis = QPDBasis(qpd_maps, [0.5, 0.25, 0.25]) qpd_gate = TwoQubitQPDGate(qpd_basis) qpd_gate.basis_id = 1 qpd_gate_copy1 = copy.copy(qpd_gate) qpd_gate_copy2 = copy.copy(qpd_gate) # These will be random if the basis_id isn't working correctly self.assertEqual( qpd_gate.definition.decompose(), qpd_gate_copy1.definition.decompose(), qpd_gate_copy2.definition.decompose(), ) def test_qpd_gate_mismatching_basis(self): single_qubit_map = [ ([XGate()],), ] single_qubit_basis = QPDBasis(single_qubit_map, [1.0]) with pytest.raises(ValueError) as e_info: TwoQubitQPDGate(single_qubit_basis) self.assertEqual( "TwoQubitQPDGate only supports QPDBasis which act on two qubits.", e_info.value.args[0], ) class TestSingleQubitQPDGate(unittest.TestCase): def test_qpd_gate_empty(self): empty_maps = [([],)] empty_basis = QPDBasis(empty_maps, [1.0]) empty_gate = SingleQubitQPDGate(empty_basis, qubit_id=0) self.assertEqual(None, empty_gate.basis_id) self.assertEqual(0, empty_gate.qubit_id) def test_qubit_id_out_of_range(self): maps = [([XGate()], [YGate()])] basis = QPDBasis(maps, [1.0]) with pytest.raises(ValueError) as e_info: SingleQubitQPDGate(basis, qubit_id=2) self.assertEqual( "'qubit_id' out of range. 'basis' acts on 2 qubits, but 'qubit_id' is 2.", e_info.value.args[0], ) def test_missing_basis_id(self): maps = [([XGate()], [YGate()])] basis = QPDBasis(maps, [1.0]) assert SingleQubitQPDGate(basis=basis, qubit_id=0).definition is None def test_compare_1q_and_2q(self): maps = [([XGate()], [YGate()])] basis = QPDBasis(maps, [1.0]) inst_2q = TwoQubitQPDGate(basis=basis) inst_1q = SingleQubitQPDGate(basis=basis, qubit_id=0) # Call both eq methods, since single qubit implements a slightly different equivalence self.assertFalse(inst_2q == inst_1q) self.assertFalse(inst_1q == inst_2q) def test_qpy_serialization(self): qc = QuantumCircuit(2) qc.append(TwoQubitQPDGate.from_instruction(CXGate()), [0, 1]) f = io.BytesIO() qpy.dump(qc, f)
https://github.com/USCqserver/DD_experiments_qiskit_QEC_course
USCqserver
### Create an account on https://quantum-computing.ibm.com/login ### Copy the API token from the homepage once logged in. token = '4c009ac74d75aae40b28b1c22af444fc6da3730bb13b4735263cb69cff1535ec999e9a604e60eaa0b0c6953428e83d2119040d18ff3a81a345e0f44c6a17f460' !pip install -U -r requirements.txt from IPython.display import clear_output clear_output() import qiskit import numpy import matplotlib import qiskit_ibm_provider print("Qiskit version:", qiskit.__version__) print("NumPy version:", numpy.__version__) print("Matplotlib version:", matplotlib.__version__) print("provider version:", qiskit_ibm_provider.__version__) from qiskit import Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, transpile from qiskit.visualization import plot_gate_map, timeline_drawer import numpy as np from IPython.display import display import matplotlib.pyplot as plt from qiskit_ibm_provider import IBMProvider IBMProvider.save_account(token=token, overwrite=True) # IBMProvider.saved_accounts() provider = IBMProvider() backends = provider.backends() backends backend = provider.get_backend('ibm_lagos') plot_gate_map(backend, figsize=(3,3),qubit_size = 30, font_size = 15, plot_directed=True) properties = backend.properties() # Extract T1 and T2 times # Extract data from the properties t1s = [qubit_data[0].value for qubit_data in properties.qubits] t2s = [qubit_data[1].value for qubit_data in properties.qubits] readout_errors = [qubit_data[4].value for qubit_data in properties.qubits] import matplotlib.pyplot as plt qubit_indices = [i for i, _ in enumerate(t1s)] plt.figure(figsize=(10,6)) plt.bar(qubit_indices, t1s, width=-0.4, align='edge', label='T1') plt.bar(qubit_indices, t2s, width=0.4, align='edge', label='T2') plt.xlabel('Qubit#') plt.ylabel('Time (us)') # Changed to microseconds based on your sample plt.title('T1 and T2 values for each Qubit') plt.legend() plt.show() plt.figure(figsize=(10,6)) plt.bar(qubit_indices, readout_errors, align='center', label='Readout Error') plt.xlabel('Qubit#') plt.ylabel('Measurement Error (%)') plt.show() two_qubit_gate_errors = [] for gate in properties.gates: if gate.gate == 'cx': gate_error = next((item.value for item in gate.parameters if item.name == 'gate_error'), None) if gate_error: two_qubit_gate_errors.append((gate.qubits, gate_error)) # Extract data for plotting gate_names = [f"cx_{gate[0][0]}_{gate[0][1]}" for gate in two_qubit_gate_errors] errors = [gate[1] for gate in two_qubit_gate_errors] # Plot plt.figure(figsize=(7,5)) plt.barh(gate_names, errors, align='center', color='skyblue') plt.xlabel('Two-Qubit Gate Errors (%)') plt.xlim(0,0.1) plt.gca().invert_yaxis() # to display the top qubit pairs at the top plt.show() def GHZ_prep(n): circuits = [] qc = QuantumCircuit(n,n) mid = int(n/2) qc.h(mid) for i in range(mid): qc.cx(mid-i,mid-i-1) if mid+i+1<n: qc.cx(mid+i,mid+i+1) qc.barrier() qc.measure(range(n),range(n)) return qc GHZ_ckts = [GHZ_prep(n) for n in range(2,6)] GHZ_ckts for i in range(len(GHZ_ckts)): display(GHZ_ckts[i].draw('mpl', style="clifford")) def GHZ_prep_with_inverse(n): circuits = [] qc = QuantumCircuit(n, n) mid = int(n / 2) # GHZ State Preparation qc.h(mid) for i in range(mid): qc.cx(mid - i, mid - i - 1) if mid + i + 1 < n: qc.cx(mid + i, mid + i + 1) qc.barrier() # Inverse GHZ State Preparation for i in reversed(range(mid)): if mid + i + 1 < n: qc.cx(mid + i, mid + i + 1) qc.cx(mid - i, mid - i - 1) qc.h(mid) qc.barrier() # Measurement qc.measure(range(n), range(n)) return qc GHZ_ckts2 = [GHZ_prep_with_inverse(n) for n in range(2,6)] GHZ_ckts2 from IPython.display import display for i in range(len(GHZ_ckts2)): display(GHZ_ckts2[i].draw('mpl', style="clifford")) layout = [0,1,3,5,6] GHZ_5 = GHZ_prep_with_inverse(5) GHZ_ckts_transpiled = transpile(GHZ_5, backend, initial_layout=layout, optimization_level=0) GHZ_ckts_transpiled.draw('mpl',style="clifford") from qiskit_ibm_provider.transpiler.passes.scheduling import DynamicCircuitInstructionDurations from qiskit_ibm_provider.transpiler.passes.scheduling import ALAPScheduleAnalysis from qiskit.circuit.library import XGate, RZGate from qiskit_ibm_provider.transpiler.passes.scheduling import PadDynamicalDecoupling as PDDDynamic from qiskit.transpiler import PassManager dd_sequence_2 = [XGate(), XGate()] dd_sequence_4 = [XGate(), XGate(),XGate(), XGate()] durations = DynamicCircuitInstructionDurations.from_backend(backend) pm_dynamic_2X = PassManager( [ ALAPScheduleAnalysis(durations), PDDDynamic(durations, dd_sequence_2, spacings = [1/4, 1/2, 1/4], sequence_min_length_ratios =[2], extra_slack_distribution='edges'), ]) pm_dynamic_4X = PassManager( [ ALAPScheduleAnalysis(durations), PDDDynamic(durations, dd_sequence_4, spacings = [1/8, 1/4, 1/4, 1/4, 1/8], sequence_min_length_ratios =[1], extra_slack_distribution='edges'), ]) circuit_dd_2X = pm_dynamic_2X.run(GHZ_ckts_transpiled) circuit_dd_4X = pm_dynamic_4X.run(GHZ_ckts_transpiled) circuit_dd_4X.draw('mpl', style="clifford") ckt_sched = transpile(circuit_dd_4X, backend=backend, scheduling_method='alap', routing_method=None) timeline_drawer(ckt_sched, show_idle=False) shots = 4000 all_ckts = [GHZ_ckts_transpiled, circuit_dd_2X, circuit_dd_4X] job = backend.run(all_ckts, shots=shots) job.status() print(job.job_id()) job_id = 'cn99vd5n6vt000847y30' job_reloaded = provider.backend.retrieve_job(job_id) job_reloaded.status() result = job_reloaded.result() counts = result.get_counts() len(counts) counts[0]['00000']/ sum(counts[0].values()) ## No DD counts[1]['00000']/ sum(counts[1].values()) ## X2 DD counts[2]['00000']/ sum(counts[2].values()) ## X4 DD
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
from tsp_qaoa import test_solution from qiskit.visualization import plot_histogram import networkx as nx import numpy as np import json import csv # Array of JSON Objects header = ['instance','p','distance', 'mean'] length_p = 3 length_instances = 2 with open('qaoa_multiple_p_distance.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) # write the header writer.writerow(header) instance_index = 0 for instance in range(length_instances): instance_index += 1 first_p = False UNIFORM_CONVERGENCE_P = [] UNIFORM_CONVERGENCE_SAMPLE = [] for p in range(length_p): p = p+1 if first_p == False: print("Vuelve a llamar a test_solution") job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p) first_p = True else: job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p) # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"]) convergence_min = UNIFORM_CONVERGENCE_SAMPLE[0] UNIFORM_CONVERGENCE_P.append({ "mean":convergence_min["mean"], "probabilities": convergence_min["probabilities"] }) cauchy_function_nk = UNIFORM_CONVERGENCE_P[len(UNIFORM_CONVERGENCE_P) - 1] p_index = 0 for p_state in UNIFORM_CONVERGENCE_P: p_index += 1 print(p_index) mean = p_state["mean"] print(p_state) print(mean) distance_p_cauchy_function_nk = np.max(np.abs(cauchy_function_nk["probabilities"] - p_state["probabilities"])) writer.writerow([instance_index, p_index, distance_p_cauchy_function_nk, mean])
https://github.com/anpaschool/qiskit-toolkit
anpaschool
%matplotlib inline import numpy as np import IPython import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit.tools.jupyter import * from qiskit.visualization import * import seaborn as sns sns.set() from helper import * import os import glob import moviepy.editor as mpy figs = [] QCs = [] qc_e1 = QuantumCircuit(1) figs.append(getBlochSphere(qc_e1.copy())) QCs.append(qc_e1.copy()) qc_e1.h(0) qc_e1.barrier() figs.append(getBlochSphere(qc_e1.copy())) QCs.append(qc_e1.copy()) for i in range(10): qc_e1.rz(np.pi/5, 0) figs.append(getBlochSphere(qc_e1.copy())) QCs.append(qc_e1.copy()) qc_e1.barrier() qc_e1.h(0) figs.append(getBlochSphere(qc_e1.copy())) QCs.append(qc_e1.copy()) style = {'backgroundcolor': 'lavender'} qc_e1.draw(output='mpl', style = style) path = "plots/bloch1" fname = "plots/bloch1" fps = 5 getBlochSequence(path, figs) getBlochGif(figs,path,fname,fps,remove = False) print("gif file is ready!") path = "plots/phase1/" fname = "plots/phase1" fps =5 getPhaseSequence(QCs,path) getPhaseGif(path,fname,fps,remove = False) print("gif file is ready!") figs = [] QCs = [] qc_e2 = QuantumCircuit(2) figs.append(getBlochSphere(qc_e2.copy())) QCs.append(qc_e2.copy()) qc_e2.h(0) qc_e2.u3(np.pi/4,np.pi/4,0,1) qc_e2.barrier() figs.append(getBlochSphere(qc_e2.copy())) QCs.append(qc_e2.copy()) for i in range(8): qc_e2.rz(np.pi/4, 0) qc_e2.rz(np.pi/4, 1) figs.append(getBlochSphere(qc_e2.copy())) QCs.append(qc_e2.copy()) qc_e2.barrier() qc_e2.h(0) qc_e2.u3(-np.pi/4,-np.pi/4,0,1) figs.append(getBlochSphere(qc_e2.copy())) QCs.append(qc_e2.copy()) style = {'backgroundcolor': 'lavender'} qc_e2.draw(output='mpl', style = style) path = "plots/bloch2/" fname = "plots/bloch2" fps = 5 getBlochSequence(path, figs) getBlochGif(figs,path,fname,fps,remove = False) print("gif file is ready!") path = "plots/phase2/" fname = "plots/phase2" fps = 5 getPhaseSequence(QCs,path) getPhaseGif(path,fname,fps=5,remove = False) print("gif file is ready!") figs = [] QCs = [] qc_e2 = QuantumCircuit(3) figs.append(getBlochSphere(qc_e2.copy())) QCs.append(qc_e2.copy()) qc_e2.h(0) qc_e2.h(1) qc_e2.h(2) qc_e2.x(0) qc_e2.y(1) qc_e2.z(2) qc_e2.barrier() figs.append(getBlochSphere(qc_e2.copy())) QCs.append(qc_e2.copy()) for i in range(8): qc_e2.u3(0,0,np.pi/4,0) qc_e2.u3(np.pi/4,0,0,1) qc_e2.u3(0,np.pi/4,0,2) figs.append(getBlochSphere(qc_e2.copy())) QCs.append(qc_e2.copy()) qc_e2.barrier() qc_e2.x(0) qc_e2.y(1) qc_e2.z(2) qc_e2.h(0) qc_e2.h(1) qc_e2.h(2) figs.append(getBlochSphere(qc_e2.copy())) QCs.append(qc_e2.copy()) style = {'backgroundcolor': 'lavender'} qc_e2.draw(output='mpl', style = style) path = "plots/bloch3/" fname = "plots/bloch3" fps = 5 getBlochSequence(path, figs) getBlochGif(figs,path,fname,fps,remove = False) print("gif file is ready!") path = "plots/phase3/" fname = "plots/phase3" fps = 5 getPhaseSequence(QCs,path) getPhaseGif(path,fname,fps=5,remove = False) print("gif file is ready!") figs = [] QCs = [] qc_e2 = QuantumCircuit(4) figs.append(getBlochSphere(qc_e2.copy())) QCs.append(qc_e2.copy()) qc_e2.h(0) qc_e2.h(1) qc_e2.h(2) qc_e2.h(3) qc_e2.x(0) qc_e2.y(1) qc_e2.z(2) qc_e2.x(3) qc_e2.barrier() figs.append(getBlochSphere(qc_e2.copy())) QCs.append(qc_e2.copy()) for i in range(8): qc_e2.u3(0,0,np.pi/4,0) qc_e2.u3(np.pi/4,0,0,1) qc_e2.u3(0,np.pi/4,0,2) qc_e2.rz(np.pi/4, 3) figs.append(getBlochSphere(qc_e2.copy())) QCs.append(qc_e2.copy()) qc_e2.barrier() qc_e2.x(0) qc_e2.y(1) qc_e2.z(2) qc_e2.x(3) qc_e2.h(0) qc_e2.h(1) qc_e2.h(2) qc_e2.h(3) figs.append(getBlochSphere(qc_e2.copy())) QCs.append(qc_e2.copy()) style = {'backgroundcolor': 'lavender'} qc_e2.draw(output='mpl', style = style) path = "plots/bloch4/" fname = "plots/bloch4" fps = 5 getBlochSequence(path, figs) getBlochGif(figs,path,fname,fps,remove = False) print("gif file is ready!") path = "plots/phase4/" fname = "plots/phase4" fps = 5 getPhaseSequence(QCs,path,rotated=True) #getPhaseSequence(QCs,path) getPhaseGif(path,fname,fps=5,remove = False) print("gif file is ready!") figs = [] QCs = [] n = 3 q = QuantumRegister(n) c = ClassicalRegister(n) qc = QuantumCircuit(q,c) figs.append(getBlochSphere(qc.copy())) QCs.append(qc.copy()) qc.h(q[2]) qc.barrier() figs.append(getBlochSphere(qc.copy())) QCs.append(qc.copy()) qc.cu1(np.pi/2, q[1], q[2]) qc.barrier() figs.append(getBlochSphere(qc.copy())) QCs.append(qc.copy()) qc.h(q[1]) qc.barrier() figs.append(getBlochSphere(qc.copy())) QCs.append(qc.copy()) qc.cu1(np.pi/4, q[0], q[2]) qc.barrier() figs.append(getBlochSphere(qc.copy())) QCs.append(qc.copy()) qc.cu1(np.pi/2, q[0], q[1]) qc.barrier() figs.append(getBlochSphere(qc.copy())) QCs.append(qc.copy()) qc.h(q[0]) qc.barrier() figs.append(getBlochSphere(qc.copy())) QCs.append(qc.copy()) qc.swap(q[0], q[2]) figs.append(getBlochSphere(qc.copy())) QCs.append(qc.copy()) path = "plots/qftb/" fname = "plots/qftb" fps = 5 getBlochSequence(path, figs) getBlochGif(figs,path,fname,fps,remove = False) print("gif file is ready!") path = "plots/qftp/" fname = "plots/qftp" fps = 5 getPhaseSequence(QCs,path,rotated=True) #getPhaseSequence(QCs,path) getPhaseGif(path,fname,fps=5,remove = False) print("gif file is ready!")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate from qiskit.converters import dag_to_circuit q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) circuit = dag_to_circuit(dag) circuit.draw('mpl')
https://github.com/ArunSehrawat/Quantum_Machine_Learning_use_cases_with_Qiskit
ArunSehrawat
import numpy as np import pandas as pd import matplotlib.pyplot as plt import time, copy, warnings from sklearn import linear_model, svm from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier from sklearn.neural_network import MLPClassifier from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, roc_auc_score data = pd.read_csv("creditcard.csv") histogram = data.hist(bins=20) data # See: 'Time' and 'Amount' are bigger than other features V1, ..., V28 values data.plot.box() # See: features V1, ..., V28 are not correlated as they are the principal components obtained with PCA plt.matshow(data.corr(), cmap='bwr') cb = plt.colorbar(shrink=0.7) plt.title('Correlation Matrix', fontsize=16) plt.show() normal = data[data.Class==0] # Set of all normal (y = 0) cases fraud = data[data.Class==1] # Set of all fraud (y = 1) cases num_normal = normal.shape[0] num_fraud = fraud.shape[0] print(f"Number of normal examples = {num_normal}") print(f"Number of fraud examples = {num_fraud}\n") ratio = num_normal/num_fraud print(f'normal to fraud ratio in the whole data = {round(ratio,2)}') 'A choice of normal_fraud_ratio has effects on precision and recall given below.' normal_fraud_ratio = 1 # normal_fraud_ratio = 1 means balance sample normal_sample = normal.sample(normal_fraud_ratio*num_fraud) # joining row-wise (axis=0) normal and fraud cases to get a sample sample = pd.concat([fraud, normal_sample], axis=0) for i in range(100): sample = np.random.permutation(sample) # random shuffling of sample examples 100 times #============================================================================== X, y = sample[:, :-1], sample[:, -1] X = MinMaxScaler().fit_transform(X) # this will put all the feature (X) values in the interval [0,1] num_examples, num_features = X.shape print("number of examples = ", num_examples) print("number of features = ", num_features) X[:3,:], y[:3] # see first 3 examples ''' Zero padding is to make the number of features equal to a power of 2. it is required for 'amplitude encoding' given below. ''' n = int(np.ceil(np.log2(num_features))) dim = 2**n print(f'(number of qubits, dimension of the Hilbert space) = {(n, dim)}') zeros = np.zeros((num_examples, dim-num_features)) X = np.append(X, zeros, axis=1) num_examples, num_features = X.shape num_examples, num_features = X.shape print("number of examples = ", num_examples) print("number of features = ", num_features) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) print(X_train.shape, X_test.shape) from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap fm = ZZFeatureMap(feature_dimension=num_features, reps=1) # ZZFeatureMap seems better fm.decompose().draw() from qiskit_machine_learning.circuit.library import RawFeatureVector fm = RawFeatureVector(feature_dimension=num_features) fm.draw() from qiskit.circuit.library import RealAmplitudes ''' For angle encoding, num_qubits = num_features For amplitude encoding, num_qubits = n = np.log2(num_features) ''' pqc = RealAmplitudes(num_qubits=n, reps=3) pqc.decompose().draw() from qiskit.algorithms.optimizers import COBYLA # This defines where to train our classifier: on a simulator or a real quantum computer from qiskit.primitives import Sampler # here we have chosen a simulator from qiskit_machine_learning.algorithms.classifiers import VQC # !pip install qiskit[machine-learning] #------------------------------------------------------------------------------------------------ optimizer = COBYLA(maxiter=150) # maxiter = Maximum number of iterations (function evaluations) sampler = Sampler() #------------------------------------------------------------------------------------------------ from IPython.display import clear_output objective_func_vals = [] # a callback that can access the intermediate data during the optimization def callback(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() #------------------------------------------------------------------------------------------------ vqc = VQC( sampler=sampler, feature_map=fm, ansatz=pqc, optimizer=optimizer, callback=callback, ) %%time '''Training time seems to increase with the number of features''' vqc.fit(X_train, y_train) y_train_pred = vqc.predict(X_train) y_test_pred = vqc.predict(X_test) print(classification_report(y_train, y_train_pred)) print(confusion_matrix(y_train, y_train_pred), "= confusion matrix for train set \n") print(classification_report(y_test, y_test_pred)) print(confusion_matrix(y_test, y_test_pred), "= confusion matrix for test set \n ") print(round(roc_auc_score(y_test, y_test_pred),2), "= roc_auc_score for test set \n") %%time warnings.filterwarnings('ignore') def train_test(ML_model): print(20*' ', ML_model,'\n') ML_model.fit(X_train, y_train) # fit model y_train_pred = ML_model.predict(X_train) # predict with the trained model y_test_pred = ML_model.predict(X_test) print(classification_report(y_train, y_train_pred)) # evaluate model performance print(confusion_matrix(y_train, y_train_pred), "= confusion matrix for train set \n") print(classification_report(y_test, y_test_pred)) print(confusion_matrix(y_test, y_test_pred), "= confusion matrix for test set \n") print(round(roc_auc_score(y_test, y_test_pred),2), "= roc_auc_score for test set \n") print(70*'=') #---------------------------------------------------------------------------------- print(70*'=') ML_model = linear_model.LogisticRegression() # create model instance train_test(ML_model) ML_model = MLPClassifier() train_test(ML_model) ML_model = svm.SVC() train_test(ML_model) ML_model = RandomForestClassifier() train_test(ML_model)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high)))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 3 strike_price_2 = 4 # set the barrier threshold barrier = 2.5 # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price_1 = ( (strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_strike_price_2 = ( (strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1) # condition and condition result conditions = [] barrier_thresholds = [2] * dimension n_aux_conditions = 0 for i in range(dimension): # target dimension of random distribution and corresponding condition (which is required to be True) comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False) n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas) conditions += [comparator] # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1] f_min = 0 f_max = mapped_strike_price_2 - mapped_strike_price_1 objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar_cond = AncillaRegister(len(conditions) + 1, "conditions") ar = AncillaRegister( max(n_aux, n_aux_conditions, objective.num_ancillas), "work" ) # additional qubits objective_index = u.num_qubits # define the circuit asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar) # load the probability distribution asian_barrier_spread.append(u, qr_state) # apply the conditions for i, cond in enumerate(conditions): state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]) # aggregate the conditions on a single qubit asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) # apply the aggregation function controlled on the condition asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]) # apply the payoff function asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas]) # uncompute the aggregation asian_barrier_spread.append( agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux] ) # uncompute the conditions asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) for j, cond in enumerate(reversed(conditions)): i = len(conditions) - j - 1 state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append( cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas] ) print(asian_barrier_spread.draw()) print("objective qubit index", objective_index) # plot exact payoff function plt.figure(figsize=(7, 5)) x = np.linspace(sum(low), sum(high)) y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function (for $S_1 = S_2$)", size=15) plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # plot contour of payoff function with respect to both time steps, including barrier plt.figure(figsize=(7, 5)) z = np.zeros((17, 17)) x = np.linspace(low[0], high[0], 17) y = np.linspace(low[1], high[1], 17) for i, x_ in enumerate(x): for j, y_ in enumerate(y): z[i, j] = np.minimum( np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1 ) if x_ > barrier or y_ > barrier: z[i, j] = 0 plt.title("Payoff Function", size=15) plt.contourf(x, y, z) plt.colorbar() plt.xlabel("Spot Price $S_1$", size=15) plt.ylabel("Spot Price $S_2$", size=15) plt.xticks(size=15) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1) leq_barrier = [np.max(v) <= barrier for v in u.values] exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier]) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False) sampler = Sampler() job = sampler.run(asian_barrier_spread_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=asian_barrier_spread, objective_qubits=[objective_index], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value:\t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/acfilok96/Quantum-Computation
acfilok96
import qiskit from qiskit import * print(qiskit.__version__) %matplotlib inline from qiskit.tools.visualization import plot_histogram circuit = QuantumCircuit(3,3) circuit # qiskit.__dir__() circuit.draw(output='mpl') circuit.x(0) circuit.barrier() circuit.draw(output='mpl') circuit.h(1) circuit.cx(1,2) circuit.draw(output='mpl') circuit.barrier() circuit.cx(0,1) circuit.h(0) circuit.draw(output='mpl') circuit.barrier() circuit.measure([0,1],[0,1]) circuit.draw(output='mpl') circuit.barrier() circuit.cx(1,2) circuit.cx(0,2) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, backend=simulator,shots=1024) result = job.result() counts=result.get_counts() print(counts) plot_histogram(counts)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer import numpy as np import sys N=int(sys.argv[1]) filename = sys.argv[2] backend = Aer.get_backend('unitary_simulator') def GHZ(n): if n<=0: return None circ = QuantumCircuit(n) # Put your code below # ---------------------------- circ.h(0) for x in range(1,n): circ.cx(x-1,x) # ---------------------------- return circ circuit = GHZ(N) job = execute(circuit, backend, shots=8192) result = job.result() array = result.get_unitary(circuit,3) np.savetxt(filename, array, delimiter=",", fmt = "%0.3f")
https://github.com/calm-cookie/deutsch-jozsa-algorithm
calm-cookie
import qiskit as q import numpy as np import matplotlib as mpl # the oracle function takes n-bit input n = 5 # define an unbalanced oracle def oracle_balanced(n): size = np.random.randint(n) random_qubits = set(np.random.randint(n, size=(size))) qc = q.QuantumCircuit(n + 1) for qubit in random_qubits: qc.x(qubit) for qubit in range(n): qc.cx(qubit, n) for qubit in random_qubits: qc.x(qubit) return qc # define a constant oracle that always returns 0 def oracle_zero(n): qc = q.QuantumCircuit(n + 1) return qc # define a constant oracle that always returns 1 def oracle_one(n): qc = q.QuantumCircuit(n + 1) qc.x(n) return qc # define an oracle function that decides whether to use a 'balanced' or a constant' oracle def oracle(choice, n): if choice == 'balanced': oracle_qc = oracle_balanced(n) elif choice == 'constant': random = np.random.randint(2) if random: oracle_qc = oracle_one(n) else: oracle_qc = oracle_zero(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" return oracle_gate # Suppose the function take n-bit strings as input. # define a query quantum register with n qubits and an answer quantum register with 1 qubit query = q.QuantumRegister(n, 'query') answer = q.QuantumRegister(1, 'answer') classical = q.ClassicalRegister(n) qc = q.QuantumCircuit(query, answer, classical) # apply hadamard gates on all query qubits to create a superposition qc.h(query) # prepare the answer qubit in state |-> qc.x(answer) qc.h(answer) qc.barrier() # apply the oracle oracle_gate = oracle('constant', n) qc.append(oracle_gate, range(n+1)) qc.barrier() # apply hadamard gates on all query qubits to reverse the superposition qc.h(query) # measure the query qubits to calculate the result qc.measure(query, classical) qc.draw(output='mpl') # execute the circuit on a qasm simulator backend = q.Aer.get_backend('qasm_simulator') job = q.execute(qc, backend, shots=1000) result = job.result() counts = result.get_counts() graph = q.visualization.plot_histogram(counts) display(graph) # If the probability of all zeroes = 1, then the function is constant, otherwise it is balanced # Hence, a single calculation solved the problem, which classically takes (2^N - 1) steps
https://github.com/ericardomuten/qiskit-advocate-mentorship
ericardomuten
# Mount Google Drive from google.colab import drive # import drive from google colab ROOT = "/content/drive" # default location for the drive print(ROOT) # print content of ROOT (Optional) drive.mount(ROOT) # we mount the google drive at /content/drive !pip install pennylane from IPython.display import clear_output clear_output() import os def restart_runtime(): os.kill(os.getpid(), 9) restart_runtime() # %matplotlib inline import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np import tensorflow as tf from tensorflow.keras.utils import to_categorical (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train_flatten = x_train.reshape(x_train.shape[0], x_train.shape[1]*x_train.shape[2])/255.0 x_test_flatten = x_test.reshape(x_test.shape[0], x_test.shape[1]*x_test.shape[2])/255.0 print(x_train_flatten.shape, y_train.shape) print(x_test_flatten.shape, y_test.shape) x_train_0 = x_train_flatten[y_train == 0] x_train_1 = x_train_flatten[y_train == 1] x_train_2 = x_train_flatten[y_train == 2] x_train_3 = x_train_flatten[y_train == 3] x_train_4 = x_train_flatten[y_train == 4] x_train_5 = x_train_flatten[y_train == 5] x_train_6 = x_train_flatten[y_train == 6] x_train_7 = x_train_flatten[y_train == 7] x_train_8 = x_train_flatten[y_train == 8] x_train_9 = x_train_flatten[y_train == 9] x_train_list = [x_train_0, x_train_1, x_train_2, x_train_3, x_train_4, x_train_5, x_train_6, x_train_7, x_train_8, x_train_9] print(x_train_0.shape) print(x_train_1.shape) print(x_train_2.shape) print(x_train_3.shape) print(x_train_4.shape) print(x_train_5.shape) print(x_train_6.shape) print(x_train_7.shape) print(x_train_8.shape) print(x_train_9.shape) x_test_0 = x_test_flatten[y_test == 0] x_test_1 = x_test_flatten[y_test == 1] x_test_2 = x_test_flatten[y_test == 2] x_test_3 = x_test_flatten[y_test == 3] x_test_4 = x_test_flatten[y_test == 4] x_test_5 = x_test_flatten[y_test == 5] x_test_6 = x_test_flatten[y_test == 6] x_test_7 = x_test_flatten[y_test == 7] x_test_8 = x_test_flatten[y_test == 8] x_test_9 = x_test_flatten[y_test == 9] x_test_list = [x_test_0, x_test_1, x_test_2, x_test_3, x_test_4, x_test_5, x_test_6, x_test_7, x_test_8, x_test_9] print(x_test_0.shape) print(x_test_1.shape) print(x_test_2.shape) print(x_test_3.shape) print(x_test_4.shape) print(x_test_5.shape) print(x_test_6.shape) print(x_test_7.shape) print(x_test_8.shape) print(x_test_9.shape) num_sample = 200 n_class = 2 mult_test = 2.5 X_train = x_train_list[0][:num_sample, :] X_test = x_test_list[0][:int(mult_test*num_sample), :] Y_train = np.zeros((n_class*X_train.shape[0],), dtype=int) Y_test = np.zeros((n_class*X_test.shape[0],), dtype=int) for i in range(n_class-1): X_train = np.concatenate((X_train, x_train_list[i+1][:num_sample, :]), axis=0) Y_train[num_sample*(i+1):num_sample*(i+2)] = int(i+1) X_test = np.concatenate((X_test, x_test_list[i+1][:int(mult_test*num_sample), :]), axis=0) Y_test[int(mult_test*num_sample*(i+1)):int(mult_test*num_sample*(i+2))] = int(i+1) Y_train = to_categorical(Y_train) Y_test = to_categorical(Y_test) print(X_train.shape, Y_train.shape) print(X_test.shape, Y_test.shape) def normalize(X, use_params=False, params=None): """Normalize the given dataset X Args: X: ndarray, dataset Returns: (Xbar, mean, std): tuple of ndarray, Xbar is the normalized dataset with mean 0 and standard deviation 1; mean and std are the mean and standard deviation respectively. Note: You will encounter dimensions where the standard deviation is zero, for those when you do normalization the normalized data will be NaN. Handle this by setting using `std = 1` for those dimensions when doing normalization. """ if use_params: mu = params[0] std_filled = [1] else: mu = np.mean(X, axis=0) std = np.std(X, axis=0) #std_filled = std.copy() #std_filled[std==0] = 1. Xbar = (X - mu)/(std + 1e-8) return Xbar, mu, std X_train, mu_train, std_train = normalize(X_train) X_train.shape, Y_train.shape X_test = (X_test - mu_train)/(std_train + 1e-8) X_test.shape, Y_test.shape from sklearn.decomposition import PCA from matplotlib import pyplot as plt num_component = 6 pca = PCA(n_components=num_component, svd_solver='full') pca.fit(X_train) np.cumsum(pca.explained_variance_ratio_) X_train = pca.transform(X_train) X_test = pca.transform(X_test) print(X_train.shape, Y_train.shape) print(X_test.shape, Y_test.shape) X_train = (X_train.T / np.sqrt(np.sum(X_train ** 2, -1))).T X_test = (X_test.T / np.sqrt(np.sum(X_test ** 2, -1))).T plt.scatter(X_train[:100, 0], X_train[:100, 1]) plt.scatter(X_train[100:200, 0], X_train[100:200, 1]) plt.scatter(X_train[200:300, 0], X_train[200:300, 1]) from qiskit import * import numpy as np # Set a random seed np.random.seed(42) def drc_circuit(x_sample, parameters, num_features, layer=1): q_reg = QuantumRegister(1) c_reg = ClassicalRegister(1) circuit = QuantumCircuit(q_reg, c_reg) # Layer iteration for i in range(layer): # Gate iteration for j in range(int(num_features/3)): circuit.u(*x_sample[3*j:3*(j+1)], 0) circuit.u(*parameters[3*j:3*(j+1)], 0) circuit.measure(0,0) return circuit num_features = 6 params = np.random.uniform(size=(num_features + 2)) params drc_circuit(X_train[0], params, num_features).draw('mpl') shots=1000 backend = Aer.get_backend('qasm_simulator') L = 1 num_features = 6 def weighted_fidelity_cost_function(params): loss = 0 # Training sample iteration for k in range(len(X_train)): q_reg = QuantumRegister(1) c_reg = ClassicalRegister(1) circuit = QuantumCircuit(q_reg, c_reg) # Layer iteration for i in range(L): # Gate iteration for j in range(int(num_features/3)): circuit.u(*X_train[k][3*j:3*(j+1)], 0) circuit.u(*params[3*j:3*(j+1)], 0) circuit.measure(0,0) t_circ = transpile(circ, backend) qobj = assemble(t_circ, shots=shots) job = backend.run(qobj) result = job.result().get_counts(circ) counts = np.array(list(result.values())) # Pauli-Z eigenvalue states = np.array([0, -1]) # Compute probabilities for each state probabilities = counts / shots # Get state expectation z_expectation = np.sum(states * probabilities) # Get weighted fidelity fidel_0 = params[-2]*(1 + z_expectation)/2 fidel_1 = params[-1]*(1 - z_expectation)/2 # Calculate the loss from the sample loss += ((fidel_0-Y_train[0,0])**2 + (fidel_1-Y_train[0,1])**2)/2 loss = loss/len(X_train) return loss weighted_fidelity_cost_function(params) from scipy.optimize import minimize out = minimize(weighted_fidelity_cost_function, x0=params, method='L-BFGS-B', options={'maxiter':10000}) print(out) params from qiskit.aqua.components.optimizers import ADAM from qiskit.aqua.components.optimizers import L_BFGS_B opt_adam = ADAM(maxiter=100) opt_lbfgsb = L_BFGS_B(maxiter=100, iprint=10) out = opt_adam.optimize(num_vars=8, objective_function=weighted_fidelity_cost_function, initial_point=params) out out out params weights = np.random.rand(num_features + 2) weights = tf.Variable(weights, dtype=tf.float64, trainable=True) weights.numpy() shots=2000 backend = Aer.get_backend('qasm_simulator') L = 1 def drc_pred(params): params = params.numpy() pred = np.zeros((len(X_train),2)) # Training sample iteration for i in range(len(X_train)): circ = drc_circuit(X_train[i], params, num_features, layer=L) t_circ = transpile(circ, backend) qobj = assemble(t_circ) job = backend.run(qobj, shots=shots) result = job.result().get_counts(circ) counts = np.array(list(result.values())) # Pauli-Z eigenvalue states = np.array([0, -1]) # Compute probabilities for each state probabilities = counts / shots # Get state expectation z_expectation = np.sum(states * probabilities) # Get weighted fidelity fidel_0 = params[-2]*(1 + z_expectation)/2 fidel_1 = params[-1]*(1 - z_expectation)/2 pred[i] = np.array([fidel_0, fidel_1]) return pred optimizer = tf.keras.optimizers.Adam(lr=0.01) def loss(params): pred = drc_pred(params) return tf.keras.losses.MeanSquaredError()(Y_train, pred) loss(weights) optimizer.minimize(lambda: loss(weights), [weights])
https://github.com/yh08037/quantum-neural-network
yh08037
import numpy as np import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F from torchsummary import summary import qiskit from qiskit.visualization import * use_cuda = torch.cuda.is_available() print('CUDA available:', use_cuda) if use_cuda: device = torch.device('cuda') print('Training on GPU...') else: device = torch.device('cpu') print('Training on CPU...') class QuantumCircuit: """ This class provides a simple interface for interaction with the quantum circuit """ def __init__(self, n_qubits, backend, shots): # --- Circuit definition --- self._circuit = qiskit.QuantumCircuit(n_qubits) all_qubits = [i for i in range(n_qubits)] self.theta = qiskit.circuit.Parameter('theta') self._circuit.h(all_qubits) self._circuit.barrier() self._circuit.ry(self.theta, all_qubits) self._circuit.measure_all() # --------------------------- self.backend = backend self.shots = shots def run(self, thetas): job = qiskit.execute(self._circuit, self.backend, shots = self.shots, parameter_binds = [{self.theta: theta} for theta in thetas]) result = job.result().get_counts(self._circuit) counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) # Compute probabilities for each state probabilities = counts / self.shots # Get state expectation expectation = np.sum(states * probabilities) return np.array([expectation]) simulator = qiskit.Aer.get_backend('qasm_simulator') circuit = QuantumCircuit(1, simulator, 100) print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0])) circuit._circuit.draw('mpl') class HybridFunction(Function): """ Hybrid quantum - classical function definition """ @staticmethod def forward(ctx, inputs, quantum_circuit, shift): """ Forward pass computation """ ctx.shift = shift ctx.quantum_circuit = quantum_circuit expectation_z = [] for input in inputs: expectation_z.append(ctx.quantum_circuit.run(input.tolist())) result = torch.tensor(expectation_z).cuda() ctx.save_for_backward(inputs, result) return result @staticmethod def backward(ctx, grad_output): """ Backward pass computation """ input, expectation_z = ctx.saved_tensors input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = torch.tensor([expectation_right]).cuda() - torch.tensor([expectation_left]).cuda() gradients.append(gradient) # gradients = np.array([gradients]).T gradients = torch.tensor([gradients]).cuda() gradients = torch.transpose(gradients, 0, 1) # return torch.tensor([gradients]).float() * grad_output.float(), None, None return gradients.float() * grad_output.float(), None, None class Hybrid(nn.Module): """ Hybrid quantum - classical layer definition """ def __init__(self, backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(1, backend, shots) self.shift = shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.shift) n_samples = 512 batch_size = 256 X_train = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])) X_train.data = X_train.data[:n_samples] X_train.targets = X_train.targets[:n_samples] train_loader = torch.utils.data.DataLoader(X_train, batch_size=batch_size, shuffle=True) # check MNIST data n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) images, targets = data_iter.__next__() while n_samples_show > 0: axes[n_samples_show - 1].imshow(images[n_samples_show].numpy().squeeze(), cmap='gray') axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(int(targets[n_samples_show]))) n_samples_show -= 1 n_samples = 2048 X_test = datasets.MNIST(root='./data', train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])) # idx = np.append(np.where(X_test.targets == 0)[0][:n_samples], # np.where(X_test.targets == 1)[0][:n_samples]) X_test.data = X_test.data[:n_samples] X_test.targets = X_test.targets[:n_samples] test_loader = torch.utils.data.DataLoader(X_test, batch_size=batch_size, shuffle=True) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 6, kernel_size=5) self.conv2 = nn.Conv2d(6, 16, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(256, 64) self.fc2 = nn.Linear(64, 10) # self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2) self.hybrid = [Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2) for i in range(10)] def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) # x = x.view(-1, 256) x = torch.flatten(x, start_dim=1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = torch.chunk(x, 10, dim=1) # x = self.hybrid(x) x = tuple([hy(x_) for hy, x_ in zip(self.hybrid, x)]) return torch.cat(x, -1) model = Net().cuda() summary(model, (1, 28, 28)) optimizer = optim.Adam(model.parameters(), lr=0.001) # loss_func = nn.NLLLoss() loss_func = nn.CrossEntropyLoss().cuda() epochs = 50 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() data = data.cuda() target = target.cuda() # Forward pass output = model(data).cuda() # print("data ", data.size()) # print("output", output.size()) # print("target", target.size()) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): data = data.cuda() target = target.cuda() output = model(data).cuda() pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100 / batch_size) ) n_samples_show = 8 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model.eval() with torch.no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break data_cuda = data.cuda() target_cuda = target.cuda() output_cuda = model(data_cuda).cuda() pred = output_cuda.argmax(dim=1, keepdim=True) axes[count].imshow(data[count].numpy().squeeze(), cmap='gray') axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title('Predicted {}'.format(pred[count].item())) count += 1
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
import numpy as np from qiskit import * from qiskit.tools.jupyter import * %matplotlib inline IBMQ.load_account() provider = IBMQ.get_provider(group='open') provider.backends(simulator=False) backend = provider.get_backend('ibmqx4') backend.configuration().basis_gates qr = QuantumRegister(2, 'q') cr = ClassicalRegister(1, 'c') qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.x(qr[1]) qc.cu1(np.pi/4, qr[0], qr[1]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.draw(output='mpl') qr = QuantumRegister(2, 'q') cr = ClassicalRegister(1, 'c') qc_basis = QuantumCircuit(qr, cr) # Hadamard in U2 format qc_basis.u2(0, np.pi, qr[0]) # X gate in U3 format qc_basis.u3(np.pi, 0, np.pi, qr[1]) # Decomposition for controlled-U1 with lambda=pi/4 qc_basis.u1(np.pi/8, qr[0]) qc_basis.cx(qr[0], qr[1]) qc_basis.u1(-np.pi/8, qr[1]) qc_basis.cx(qr[0], qr[1]) qc_basis.u1(np.pi/8, qr[1]) # Hadamard in U2 format qc_basis.u2(0, np.pi, qr[0]) qc_basis.measure(qr[0], cr[0]) qc_basis.draw(output='mpl') print(qc.depth(), ',', qc_basis.depth()) qr = QuantumRegister(3, 'q') qc = QuantumCircuit(qr) qc.ccx(qr[0], qr[1], qr[2]) qc.draw(output='mpl') qr = QuantumRegister(3, 'q') qc_basis = QuantumCircuit(qr) qc_basis.u2(0,np.pi, qr[2]) qc_basis.cx(qr[1], qr[2]) qc_basis.u1(-np.pi/4, qr[2]) qc_basis.cx(qr[0], qr[2]) qc_basis.u1(np.pi/4, qr[2]) qc_basis.cx(qr[1], qr[2]) qc_basis.u1(np.pi/4, qr[1]) qc_basis.u1(-np.pi/4, qr[2]) qc_basis.cx(qr[0], qr[2]) qc_basis.cx(qr[0], qr[1]) qc_basis.u1(np.pi/4, qr[2]) qc_basis.u1(np.pi/4, qr[0]) qc_basis.u1(-np.pi/4, qr[1]) qc_basis.u2(0,np.pi, qr[2]) qc_basis.cx(qr[0], qr[1]) qc_basis.draw(output='mpl') qr = QuantumRegister(5, 'q') cr = ClassicalRegister(5, 'c') qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[4]) qc.cx(qr[4], qr[3]) qc.cx(qr[3], qr[1]) qc.cx(qr[1], qr[2]) qc.draw(output='mpl') backend = provider.get_backend('ibmqx4') from qiskit.visualization.gate_map import plot_gate_map plot_gate_map(backend, plot_directed=True)
https://github.com/hephaex/Quantum-Computing-Awesome-List
hephaex
from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram n = 8 n_q = n n_b = n qc_output = QuantumCircuit(n_q,n_b)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# Needed for functions import numpy as np import time # Import Qiskit classes import qiskit from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer from qiskit.quantum_info import state_fidelity from qiskit.providers.aer import noise # Tomography functions from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter import qiskit.ignis.mitigation.measurement as mc # Create the expected density matrix q2 = QuantumRegister(2) bell = QuantumCircuit(q2) bell.h(q2[0]) bell.cx(q2[0], q2[1]) print(bell) job = qiskit.execute(bell, Aer.get_backend('statevector_simulator')) psi_bell = job.result().get_statevector(bell) print(psi_bell) # Create the actual circuit q2 = QuantumRegister(6) bell = QuantumCircuit(q2) bell.h(q2[3]) bell.cx(q2[3], q2[5]) print(bell) # Generate circuits and run on simulator t = time.time() # Generate the state tomography circuits. Only pass in the # registers we want to measure (in this case 3 and 5) qst_bell = state_tomography_circuits(bell, [q2[3],q2[5]]) job = qiskit.execute(qst_bell, Aer.get_backend('qasm_simulator'), shots=5000) print('Time taken:', time.time() - t) # Generate the state tomography circuits using the default settings for # basis tomo_bell = StateTomographyFitter(job.result(), qst_bell) # Perform the tomography fit # which outputs a density matrix rho_bell = tomo_bell.fit() F_bell = state_fidelity(psi_bell, rho_bell) print('Fit Fidelity =', F_bell) #Add measurement noise noise_model = noise.NoiseModel() for qi in range(6): read_err = noise.errors.readout_error.ReadoutError([[0.75, 0.25],[0.1,0.9]]) noise_model.add_readout_error(read_err,[qi]) #generate the calibration circuits meas_calibs, state_labels = mc.complete_meas_cal(qubit_list=[3,5]) backend = Aer.get_backend('qasm_simulator') qobj_cal = qiskit.compile(meas_calibs, backend=backend, shots=15000) qobj_tomo = qiskit.compile(qst_bell, backend=backend, shots=15000) job_cal = backend.run(qobj_cal, noise_model=noise_model) job_tomo = backend.run(qobj_tomo, noise_model=noise_model) meas_fitter = mc.CompleteMeasFitter(job_cal.result(),state_labels) tomo_bell = StateTomographyFitter(job_tomo.result(), qst_bell) #no correction rho_bell = tomo_bell.fit() F_bell = state_fidelity(psi_bell, rho_bell) print('Fit Fidelity (no correction) =', F_bell) #correct data correct_tomo_results = meas_fitter.filter.apply(job_tomo.result(), method='least_squares') tomo_bell = StateTomographyFitter(correct_tomo_results, qst_bell) rho_bell = tomo_bell.fit() F_bell = state_fidelity(psi_bell, rho_bell) print('Fit Fidelity (w/ correction) =', F_bell) def random_u3_tomo(nq, shots): def rand_angles(): return tuple(2 * np.pi * np.random.random(3) - np.pi) q = QuantumRegister(nq) circ = QuantumCircuit(q) for j in range(nq): circ.u3(*rand_angles(), q[j]) job = qiskit.execute(circ, Aer.get_backend('statevector_simulator')) psi_rand = job.result().get_statevector(circ) qst_circs = state_tomography_circuits(circ, q) job = qiskit.execute(qst_circs, Aer.get_backend('qasm_simulator'), shots=shots) tomo_data = StateTomographyFitter(job.result(), qst_circs) rho_cvx = tomo_data.fit(method='cvx') rho_lstsq = tomo_data.fit(method='lstsq') print('F fit (CVX) =', state_fidelity(psi_rand, rho_cvx)) print('F fit (LSTSQ) =', state_fidelity(psi_rand, rho_lstsq)) for j in range(5): print('Random single-qubit unitaries: set {}'.format(j)) random_u3_tomo(3, 5000) # Create a state preparation circuit q5 = QuantumRegister(5) bell5 = QuantumCircuit(q5) bell5.h(q5[0]) for j in range(4): bell5.cx(q5[j], q5[j + 1]) # Get ideal output state job = qiskit.execute(bell5, Aer.get_backend('statevector_simulator')) psi_bell5 = job.result().get_statevector(bell5) # Generate circuits and run on simulator t = time.time() qst_bell5 = state_tomography_circuits(bell5, q5) job = qiskit.execute(qst_bell5, Aer.get_backend('qasm_simulator'), shots=5000) # Extract tomography data so that counts are indexed by measurement configuration tomo_bell5 = StateTomographyFitter(job.result(), qst_bell5) print('Time taken:', time.time() - t) t = time.time() rho_lstsq_bell5 = tomo_bell5.fit(method='lstsq') print('Least-Sq Reconstruction') print('Time taken:', time.time() - t) print('Fit Fidelity:', state_fidelity(psi_bell5, rho_lstsq_bell5)) t = time.time() rho_cvx_bell5 = tomo_bell5.fit(method='cvx') print('CVX Reconstruction') print('Time taken:', time.time() - t) print('Fidelity:', state_fidelity(psi_bell5, rho_cvx_bell5))
https://github.com/BoschSamuel/QizGloria
BoschSamuel
# -- coding: utf-8 -- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # -- coding: utf-8 -- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import torch from torch.autograd import Function import torch.optim as optim from qiskit import QuantumRegister,QuantumCircuit,ClassicalRegister,execute from qiskit.circuit import Parameter from qiskit import Aer import numpy as np from tqdm import tqdm from matplotlib import pyplot as plt from torch.autograd import Function %matplotlib inline np.random.seed = 42 def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list class QiskitCircuit_QAOA(): def __init__(self,shots): self.beta = Parameter('Beta') self.gamma = Parameter('Gamma') self.delta = Parameter('Delta') self.beta2 = Parameter('Beta2') self.delta2 = Parameter('Delta2') self.shots = shots def create_circuit(): ckt = QuantumCircuit(2, 2) # add mixer part ckt.rx(self.beta, 0) ckt.rx(self.beta2, 1) # add H_target part, for each Zi Zj do this ckt.cx(0,1) ckt.rz(-1*self.gamma, 1) ckt.cx(0,1) ckt.ry(self.delta, 0) ckt.ry(self.delta2, 1) ckt.measure([0,1],[0,1]) return ckt self.circuit = create_circuit() def expectation(self, counts, shots, nr_qubits): #calculate expectation for one qubit pair expects = 0 #print(counts) for key in counts.keys(): perc = counts[key]/shots #check = Cij*((float(key[i])-1/2)+(float(key[j])-1/2))*perc check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)]) expects += check return expects def bind(self,parameters): [self.beta, self.beta2, self.gamma, self.delta, self.delta2] = parameters #print(self.circuit.data) self.circuit.data[0][0]._params = to_numbers(parameters)[0:1] self.circuit.data[1][0]._params = to_numbers(parameters)[1:2] self.circuit.data[3][0]._params = to_numbers(parameters)[2:3] self.circuit.data[5][0]._params = to_numbers(parameters)[3:4] self.circuit.data[6][0]._params = to_numbers(parameters)[4:5] return self.circuit def run(self, i): self.bind(i) backend = Aer.get_backend('qasm_simulator') job_sim = execute(self.circuit,backend,shots=self.shots) result_sim = job_sim.result() counts = result_sim.get_counts(self.circuit) #print(counts) return self.expectation(counts, self.shots, 2) class TorchCircuit(Function): @staticmethod def forward(ctx, i): if not hasattr(ctx, 'QiskitCirc'): ctx.QiskitCirc = QiskitCircuit_QAOA(shots=10000) #print(i[0]) exp_value = ctx.QiskitCirc.run(i[0]) result = torch.tensor([exp_value]) ctx.save_for_backward(result, i) return result @staticmethod def backward(ctx, grad_output): eps = 0.01 forward_tensor, i = ctx.saved_tensors input_numbers = to_numbers(i[0]) gradient = [] for k in range(len(input_numbers)): input_eps = input_numbers input_eps[k] = input_numbers[k] + eps exp_value = ctx.QiskitCirc.run(torch.tensor(input_eps)) result_eps = torch.tensor([exp_value]) gradient_result = (exp_value - forward_tensor[0][0].item())/eps gradient.append(gradient_result) # print(gradient) result = torch.tensor([gradient]) #print(grad_output.shape) #print(result.shape) #print(torch.einsum('abc,ac->ab',result.float(),grad_output.float())) #print("test tens size", result.float(), grad_output.float()) return torch.einsum('abc,ac->ab',result.float(),grad_output.float())#result.float() * grad_output.float() torch.manual_seed(42) # x = torch.tensor([np.pi/4, np.pi/4, np.pi/4], requires_grad=True) x = torch.tensor([[0.3, 0.2, 0.1, 0.1, 0.2]], requires_grad=True) qc = TorchCircuit.apply y1 = qc(x) print(y1) y1 = torch.abs(y1[0] - 1.0) ** 2 y1.backward() qc = TorchCircuit.apply def cost(x): target = 0.25 expval = qc(x) return torch.abs(qc(x).sum() - target) ** 2, expval x = torch.tensor([[np.pi/4, np.pi/4, 1.0, 0.5, 0.1]], requires_grad=True) opt = torch.optim.Adam([x], lr=0.1) num_epoch = 100 loss_list = [] expval_list = [] for i in tqdm(range(num_epoch)): # for i in range(num_epoch): opt.zero_grad() loss, expval = cost(x) loss.backward() opt.step() loss_list.append(loss.item()) # print(loss.item()) plt.plot(loss_list) # print(circuit(phi, theta)) # print(cost(x)) import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import torchvision from torchvision import datasets, transforms batch_size_train = 1 batch_size_test = 1 learning_rate = 0.01 momentum = 0.5 log_interval = 10 torch.backends.cudnn.enabled = False transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor()]) mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform) labels = mnist_trainset.targets #get labels labels = labels.numpy() idx1 = np.where(labels == 0) #search all zeros idx2 = np.where(labels == 1) # search all ones idx = np.concatenate((idx1[0][0:10],idx2[0][0:10])) # concatenate their indices #idx = idx2 mnist_trainset.targets = labels[idx] mnist_trainset.data = mnist_trainset.data[idx] print(mnist_trainset) train_loader = torch.utils.data.DataLoader(mnist_trainset, batch_size=batch_size_train, shuffle=True) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(320, 50) self.fc2 = nn.Linear(50, 5) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 320) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) #x = np.pi*F.tanh(x) #print(x) x = qc(x) x = (x+1)/2 # print(x) #x = torch.cat((x, 1-x), -1) # return x return F.softmax(x) network = Net() optimizer = optim.SGD(network.parameters(), lr=learning_rate, momentum=momentum) epochs = 100 for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): # print(batch_idx) optimizer.zero_grad() #print(data) output = network(data) print(output[0].data, target) loss = F.nll_loss(output, target) # print(output) # print(output[0][1].item(), target.item()) #print(loss) loss.backward() optimizer.step() total_loss.append(loss.item()) print(sum(total_loss)/len(total_loss))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can show the phase of each state and use # degrees instead of radians from qiskit.quantum_info import DensityMatrix import numpy as np from qiskit import QuantumCircuit from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) qc.z(1) matrix = DensityMatrix(qc) plot_state_qsphere(matrix, show_state_phases = True, use_degrees = True)
https://github.com/benkoehlL/Qiskit_Playground
benkoehlL
import os, shutil from qiskit import * from qiskit.visualization import plot_histogram from qiskit.visualization import circuit_drawer as drawer import numpy as np from matplotlib.pyplot import draw, plot, show N = 1000 # number of circuits with random errors p = 0.1 # error probability LaTex_folder_Error_Correction = str(os.getcwd())+'/Latex_quantum_gates/Error_Correction/' if not os.path.exists(LaTex_folder_Error_Correction): os.makedirs(LaTex_folder_Error_Correction) else: shutil.rmtree(LaTex_folder_Error_Correction) os.makedirs(LaTex_folder_Error_Correction) def ERROR_X(circuit, q): if(np.random.rand()<p): circuit.x(q) def ERROR_Y(circuit, q): if(np.random.rand()<p): circuit.y(q) def ERROR_Z(circuit, q): if(np.random.rand()<p): circuit.z(q) def All_Errors(circuit, q): for qubit in q: ran = np.random.rand() if(ran < 1/3): ERROR_X(circuit, qubit) elif(ran < 2/3): ERROR_Y(circuit, qubit) else: ERROR_Z(circuit, qubit) def Shor_error_correction(Circuit_FUNC, qr, qr_Shor): # This function creates the Shor error correction circuit # for a error-prone function Circuit_FUNC and its related # qubit(s) qr (qr_Shor are the ancilla qubits) # it returns this error corrected circuit qc_preprocess = QuantumCircuit(qr, qr_Shor) for i, qubit in enumerate(qr): qc_preprocess.cx(qubit, qr_Shor[8*i+2]) qc_preprocess.cx(qubit, qr_Shor[8*i+5]) qc_preprocess.h(qubit) qc_preprocess.h(qr_Shor[8*i+2]) qc_preprocess.h(qr_Shor[8*i+5]) qc_preprocess.cx(qubit, qr_Shor[8*i]) qc_preprocess.cx(qubit, qr_Shor[8*i+1]) qc_preprocess.cx(qr_Shor[8*i+2], qr_Shor[8*i+3]) qc_preprocess.cx(qr_Shor[8*i+2], qr_Shor[8*i+4]) qc_preprocess.cx(qr_Shor[8*i+5], qr_Shor[8*i+6]) qc_preprocess.cx(qr_Shor[8*i+5], qr_Shor[8*i+7]) #qc_preprocess.barrier() qc_preprocess.barrier() qc = qc_preprocess # apply main function (with possible errors) to qr # and the error ancilla qubits Circuit_FUNC(qc, qr) for j in range(8): Circuit_FUNC(qc, qr_Shor[j:j+8*len(qr):8]) qc.barrier() qc_postprocess = QuantumCircuit(qr,qr_Shor) for i, qubit in enumerate(qr): qc_postprocess.cx(qubit, qr_Shor[8*i]) qc_postprocess.cx(qubit, qr_Shor[8*i+1]) qc_postprocess.cx(qr_Shor[8*i+2], qr_Shor[8*i+3]) qc_postprocess.cx(qr_Shor[8*i+2], qr_Shor[8*i+4]) qc_postprocess.cx(qr_Shor[8*i+5], qr_Shor[8*i+6]) qc_postprocess.cx(qr_Shor[8*i+5], qr_Shor[8*i+7]) qc_postprocess.ccx(qr_Shor[8*i], qr_Shor[8*i+1], qubit) qc_postprocess.ccx(qr_Shor[8*i+3], qr_Shor[8*i+4], qr_Shor[8*i+2]) qc_postprocess.ccx(qr_Shor[8*i+6], qr_Shor[8*i+7], qr_Shor[8*i+5]) qc_postprocess.h(qubit) qc_postprocess.h(qr_Shor[8*i+2]) qc_postprocess.h(qr_Shor[8*i+5]) qc_postprocess.cx(qubit, qr_Shor[8*i+2]) qc_postprocess.cx(qubit, qr_Shor[8*i+5]) qc_postprocess.ccx(qr_Shor[8*i+2], qr_Shor[8*i+5], qubit) #qc_postprocess.barrier() qc = QuantumCircuit.compose(qc, qc_postprocess) return qc ## X-Error print("X error") for qubit in [0, 1]: answer_plot = {} print("|",qubit,'> : ',end='') for i in range(N): q = QuantumRegister(1,'q') q_Shor = QuantumRegister(8*len(q),'q_shor') c = ClassicalRegister(len(q), 'c') qc = QuantumCircuit(q,q_Shor, c) if(qubit): qc.x(q) qc_Shor = Shor_error_correction(ERROR_X, q, q_Shor) qc_Shor.barrier() qc_Shor = QuantumCircuit.compose(qc, qc_Shor) qc_Shor.measure(q, c) # evaluate result simulator = Aer.get_backend('qasm_simulator') result = execute(qc_Shor, backend=simulator, shots=100).result() answer = result.get_counts() for measureresult in answer.keys(): measureresults_input = measureresult if measureresults_input in answer_plot: answer_plot[measureresults_input] += answer[measureresult] else: answer_plot[measureresults_input] = answer[measureresult] # Plot the categorised results print(answer_plot) #plt = plot_histogram(answer_plot) #draw() #show(block=True) LaTex_code = qc_Shor.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit f_name = 'Shor_error_correction_XERROR.tex' with open(LaTex_folder_Error_Correction+f_name, 'w') as f: f.write(LaTex_code) ## Y-Error print("Y error") for qubit in [0, 1]: answer_plot = {} print("|",qubit,'> : ',end='') for i in range(N): q = QuantumRegister(1,'q') q_Shor = QuantumRegister(8*len(q),'q_shor') c = ClassicalRegister(len(q), 'c') qc = QuantumCircuit(q,q_Shor, c) if qubit: qc.x(q) qc.h(q) # y error is detected in Hadamard basis qc_Shor = Shor_error_correction(ERROR_Y, q, q_Shor) qc_Shor.barrier() qc_Shor = QuantumCircuit.compose(qc, qc_Shor) qc_Shor.h(q) # y error is detected in Hadamard basis qc_Shor.measure(q, c) # evaluate result simulator = Aer.get_backend('qasm_simulator') result = execute(qc_Shor, backend=simulator, shots=100).result() answer = result.get_counts() for measureresult in answer.keys(): measureresults_input = measureresult if measureresults_input in answer_plot: answer_plot[measureresults_input] += answer[measureresult] else: answer_plot[measureresults_input] = answer[measureresult] # Plot the categorised results print(answer_plot) #plt = plot_histogram(answer_plot) #draw() #show(block=True) LaTex_code = qc_Shor.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit f_name = 'Shor_error_correction_YERROR.tex' with open(LaTex_folder_Error_Correction+f_name, 'w') as f: f.write(LaTex_code) ## Z-Error print("Z error") for qubit in [0, 1]: answer_plot = {} print("|",qubit,'> : ',end='') for i in range(N): q = QuantumRegister(1,'q') q_Shor = QuantumRegister(8*len(q),'q_shor') c = ClassicalRegister(len(q), 'c') qc = QuantumCircuit(q,q_Shor, c) if qubit: qc.x(q) qc.h(q) # z error is detected in Hadamard basis qc_Shor = Shor_error_correction(ERROR_Z, q, q_Shor) qc_Shor.barrier() qc_Shor = QuantumCircuit.compose(qc, qc_Shor) qc_Shor.h(q) # z error is detected in Hadamard basis qc_Shor.measure(q, c) # evaluate result simulator = Aer.get_backend('qasm_simulator') result = execute(qc_Shor, backend=simulator, shots=100).result() answer = result.get_counts() for measureresult in answer.keys(): measureresults_input = measureresult if measureresults_input in answer_plot: answer_plot[measureresults_input] += answer[measureresult] else: answer_plot[measureresults_input] = answer[measureresult] # Plot the categorised results print(answer_plot) #plt = plot_histogram(answer_plot) #draw() #show(block=True) LaTex_code = qc_Shor.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit f_name = 'Shor_error_correction_ZERROR.tex' with open(LaTex_folder_Error_Correction+f_name, 'w') as f: f.write(LaTex_code) ## All three errors possible before CX-gate print("CX with all error types") for qubit1 in [0, 1]: for qubit2 in [0, 1]: print("|",qubit1,qubit2,'> : ',end='') answer_plot = {} for i in range(N): q = QuantumRegister(2,'q') c = ClassicalRegister(len(q), 'c') q_Shor = QuantumRegister(8*len(q),'q_shor') qc = QuantumCircuit(q, q_Shor, c) if(qubit1): qc.x(q[0]) if(qubit2): qc.x(q[1]) qc.barrier() qc_Shor = Shor_error_correction(All_Errors, q, q_Shor) qc_Shor.barrier() qc_Shor = QuantumCircuit.compose(qc, qc_Shor) qc_Shor.cx(q[0],q[1]) for i, qubit in enumerate(reversed(q)): qc_Shor.measure(qubit, c[i]) # evaluate result simulator = Aer.get_backend('qasm_simulator') result = execute(qc_Shor, backend=simulator, shots=10).result() answer = result.get_counts() for measureresult in answer.keys(): measureresults_input = measureresult if measureresults_input in answer_plot: answer_plot[measureresults_input] += answer[measureresult] else: answer_plot[measureresults_input] = answer[measureresult] # Plot the categorised results print(answer_plot) plt = plot_histogram(answer_plot) draw() show(block=True)
https://github.com/intrinsicvardhan/QuantumComputingAlgos
intrinsicvardhan
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# If you introduce a list with less colors than bars, the color of the bars will # alternate following the sequence from the list. import numpy as np from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0, 1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) matrix = DensityMatrix(qc) plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
https://github.com/BoschSamuel/QizGloria
BoschSamuel
# -- coding: utf-8 -- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import torch from torch.autograd import Function import torch.optim as optim from qiskit import QuantumRegister,QuantumCircuit,ClassicalRegister,execute from qiskit.circuit import Parameter from qiskit import Aer import numpy as np from tqdm import tqdm from matplotlib import pyplot as plt %matplotlib inline def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list class QiskitCircuit(): def __init__(self,shots): self.theta = Parameter('Theta') self.phi = Parameter('Phi') self.shots = shots def create_circuit(): qr = QuantumRegister(1,'q') cr = ClassicalRegister(1,'c') ckt = QuantumCircuit(qr,cr) ckt.h(qr[0]) ckt.barrier() ckt.ry(self.theta,qr[0]) ckt.barrier() ckt.measure(qr,cr) return ckt self.circuit = create_circuit() def N_qubit_expectation_Z(self,counts, shots, nr_qubits): expects = np.zeros(nr_qubits) for key in counts.keys(): perc = counts[key]/shots check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)]) expects += check return expects def bind(self, parameters): [self.theta] = to_numbers(parameters) self.circuit.data[2][0]._params = to_numbers(parameters) def run(self, i): self.bind(i) backend = Aer.get_backend('qasm_simulator') job_sim = execute(self.circuit,backend,shots=self.shots) result_sim = job_sim.result() counts = result_sim.get_counts(self.circuit) return self.N_qubit_expectation_Z(counts,self.shots,1) class TorchCircuit(Function): @staticmethod def forward(ctx, i): if not hasattr(ctx, 'QiskitCirc'): ctx.QiskitCirc = QiskitCircuit(shots=100) exp_value = ctx.QiskitCirc.run(i[0]) result = torch.tensor([exp_value]) ctx.save_for_backward(result, i) return result @staticmethod def backward(ctx, grad_output): eps = np.pi/2 forward_tensor, i = ctx.saved_tensors input_numbers = to_numbers(i[0]) gradient = [] for k in range(len(input_numbers)): input_eps_plus = input_numbers input_eps_plus[k] = input_numbers[k] + eps exp_value_plus = ctx.QiskitCirc.run(torch.tensor(input_eps_plus))[0] result_eps_plus = torch.tensor([exp_value_plus]) input_eps_minus = input_numbers input_eps_minus[k] = input_numbers[k] - eps exp_value_minus = ctx.QiskitCirc.run(torch.tensor(input_eps_minus))[0] result_eps_minus = torch.tensor([exp_value_minus]) gradient_result = 0.5 * (result_eps_plus - result_eps_minus) gradient.append(gradient_result) # print(gradient) result = torch.tensor([gradient]) # print(result) return result.float() * grad_output.float() # x = torch.tensor([np.pi/4, np.pi/4, np.pi/4], requires_grad=True) x = torch.tensor([[0.0]], requires_grad=True) qc = TorchCircuit.apply y1 = qc(x) y1.backward() print(x.grad) qc = TorchCircuit.apply def cost(x): target = -1 expval = qc(x) return torch.abs(qc(x) - target) ** 2, expval x = torch.tensor([[0.0]], requires_grad=True) opt = torch.optim.Adam([x], lr=0.1) num_epoch = 50 loss_list = [] expval_list = [] for i in tqdm(range(num_epoch)): # for i in range(num_epoch): opt.zero_grad() loss, expval = cost(x) loss.backward() opt.step() loss_list.append(loss.item()) expval_list.append(expval.item()) # print(loss.item()) plt.plot(loss_list) # print(circuit(phi, theta)) # print(cost(x)) import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import torchvision from torchvision import datasets, transforms batch_size_train = 1 batch_size_test = 1 learning_rate = 0.01 momentum = 0.5 log_interval = 10 torch.backends.cudnn.enabled = False transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor()]) mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform) labels = mnist_trainset.targets #get labels labels = labels.numpy() idx1 = np.where(labels == 0) #search all zeros idx2 = np.where(labels == 1) # search all ones n=100 idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # concatenate their indices mnist_trainset.targets = labels[idx] mnist_trainset.data = mnist_trainset.data[idx] print(mnist_trainset) train_loader = torch.utils.data.DataLoader(mnist_trainset, batch_size=batch_size_train, shuffle=True) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(320, 50) self.fc2 = nn.Linear(50, 1) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 320) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) # return F.softmax(x) # x = np.pi*F.tanh(x) # print(x) x = qc(x) x = (x+1)/2 x = torch.cat((x, 1-x), -1) return x network = Net() # optimizer = optim.SGD(network.parameters(), lr=learning_rate, # momentum=momentum) optimizer = optim.Adam(network.parameters(), lr=learning_rate/10) epochs = 30 loss_list = [] for epoch in range(epochs): total_loss = [] target_list = [] for batch_idx, (data, target) in enumerate(train_loader): target_list.append(target.item()) # print(batch_idx) optimizer.zero_grad() output = network(data) loss = F.nll_loss(output, target) # loss = F.cross_entropy(output, target) # print(output) # print(output[0][1].item(), target.item()) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print(loss_list[-1]) plt.plot(loss_list) for i in range(len(loss_list)): loss_list[i] += 1 plt.plot(loss_list)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) ghz.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXDebugging from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc, style=IQXDebugging())
https://github.com/shubz2900/Grover-s-Search-Algo-using-Qiskit
shubz2900
import qiskit qiskit.__qiskit_version__ import numpy as np import matplotlib.pyplot as plt # importing Qiskit from qiskit import BasicAer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.visualization import plot_histogram q = QuantumRegister(6) qc = QuantumCircuit(q) qc.x(q[2]) qc.cx(q[1], q[5]) qc.cx(q[2], q[5]) qc.cx(q[3], q[5]) qc.ccx(q[1], q[2], q[4]) qc.ccx(q[3], q[4], q[5]) qc.ccx(q[1], q[2], q[4]) qc.x(q[2]) qc.draw(output='mpl') def black_box_u_f(circuit, f_in, f_out, aux, n, exactly_1_3_sat_formula): """Circuit that computes the black-box function from f_in to f_out. Create a circuit that verifies whether a given exactly-1 3-SAT formula is satisfied by the input. The exactly-1 version requires exactly one literal out of every clause to be satisfied. """ num_clauses = len(exactly_1_3_sat_formula) for (k, clause) in enumerate(exactly_1_3_sat_formula): # This loop ensures aux[k] is 1 if an odd number of literals # are true for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) # Flip aux[k] if all literals are true, using auxiliary qubit # (ancilla) aux[num_clauses] circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) # Flip back to reverse state of negative literals and ancilla circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # The formula is satisfied if and only if all auxiliary qubits # except aux[num_clauses] are 1 if (num_clauses == 1): circuit.cx(aux[0], f_out[0]) elif (num_clauses == 2): circuit.ccx(aux[0], aux[1], f_out[0]) elif (num_clauses == 3): circuit.ccx(aux[0], aux[1], aux[num_clauses]) circuit.ccx(aux[2], aux[num_clauses], f_out[0]) circuit.ccx(aux[0], aux[1], aux[num_clauses]) else: raise ValueError('We only allow at most 3 clauses') # Flip back any auxiliary qubits to make sure state is consistent # for future executions of this routine; same loop as above. for (k, clause) in enumerate(exactly_1_3_sat_formula): for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # -- end function def n_controlled_Z(circuit, controls, target): """Implement a Z gate with multiple controls""" if (len(controls) > 2): raise ValueError('The controlled Z with more than 2 ' + 'controls is not implemented') elif (len(controls) == 1): circuit.h(target) circuit.cx(controls[0], target) circuit.h(target) elif (len(controls) == 2): circuit.h(target) circuit.ccx(controls[0], controls[1], target) circuit.h(target) # -- end function def inversion_about_average(circuit, f_in, n): """Apply inversion about the average step of Grover's algorithm.""" # Hadamards everywhere for j in range(n): circuit.h(f_in[j]) # D matrix: flips the sign of the state |000> only for j in range(n): circuit.x(f_in[j]) n_controlled_Z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1]) for j in range(n): circuit.x(f_in[j]) # Hadamards everywhere again for j in range(n): circuit.h(f_in[j]) # -- end function qr = QuantumRegister(3) qInvAvg = QuantumCircuit(qr) inversion_about_average(qInvAvg, qr, 3) qInvAvg.draw(output='mpl') """ Grover search implemented in Qiskit. This module contains the code necessary to run Grover search on 3 qubits, both with a simulator and with a real quantum computing device. This code is the companion for the paper "An introduction to quantum computing, without the physics", Giacomo Nannicini, https://arxiv.org/abs/1708.03684. """ def input_state(circuit, f_in, f_out, n): """(n+1)-qubit input state for Grover search.""" for j in range(n): circuit.h(f_in[j]) circuit.x(f_out) circuit.h(f_out) # -- end function # Make a quantum program for the n-bit Grover search. n = 3 # Exactly-1 3-SAT formula to be satisfied, in conjunctive # normal form. We represent literals with integers, positive or # negative, to indicate a Boolean variable or its negation. exactly_1_3_sat_formula = [[1, 2, -3], [-1, -2, -3], [-1, 2, 3]] # Define three quantum registers: 'f_in' is the search space (input # to the function f), 'f_out' is bit used for the output of function # f, aux are the auxiliary bits used by f to perform its # computation. f_in = QuantumRegister(n) f_out = QuantumRegister(1) aux = QuantumRegister(len(exactly_1_3_sat_formula) + 1) # Define classical register for algorithm result ans = ClassicalRegister(n) # Define quantum circuit with above registers grover = QuantumCircuit() grover.add_register(f_in) grover.add_register(f_out) grover.add_register(aux) grover.add_register(ans) input_state(grover, f_in, f_out, n) T = 2 for t in range(T): # Apply T full iterations black_box_u_f(grover, f_in, f_out, aux, n, exactly_1_3_sat_formula) inversion_about_average(grover, f_in, n) # Measure the output register in the computational basis for j in range(n): grover.measure(f_in[j], ans[j]) # Execute circuit backend = BasicAer.get_backend('qasm_simulator') job = execute([grover], backend=backend, shots=1000) result = job.result() # Get counts and plot histogram counts = result.get_counts(grover) plot_histogram(counts) from qiskit import IBMQ API_KEY = '85cb8a7e6f047877bc60dffc222a7f0bf7bc8d2a2f230b25bd8e873eea0f8a6bee8607430d8789e05bdd26011ff0d179b6dfa58ee529b8963cc939f809a6f7be' # Replace 'your-api-key' with your actual API key IBMQ.save_account(API_KEY, overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') # Print the available backends print(provider.backends()) # Choose a different backend name from the list backend_name = 'ibmq_qasm_simulator' # Get the backend backend = provider.get_backend(backend_name) # Rest of your code remains the same grover_compiled = transpile(grover, backend=backend, seed_transpiler=1, optimization_level=3) print('gates = ', grover_compiled.count_ops()) print('depth = ', grover_compiled.depth()) grover.draw(output='mpl', scale=0.5)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.quantum_info import SparsePauliOp H2_op = SparsePauliOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) from qiskit.circuit.library import TwoLocal from qiskit.algorithms.optimizers import SLSQP ansatz = TwoLocal(3, rotation_blocks=["ry", "rz"], entanglement_blocks="cz", reps=1) optimizer = SLSQP() ansatz.decompose().draw('mpl') from qiskit.primitives import Sampler, Estimator from qiskit.algorithms.state_fidelities import ComputeUncompute estimator = Estimator() sampler = Sampler() fidelity = ComputeUncompute(sampler) k = 3 betas = [33, 33, 33] counts = [] values = [] steps = [] def callback(eval_count, params, value, meta, step): counts.append(eval_count) values.append(value) steps.append(step) from qiskit.algorithms.eigensolvers import VQD vqd = VQD(estimator, fidelity, ansatz, optimizer, k=k, betas=betas, callback=callback) result = vqd.compute_eigenvalues(operator = H2_op) vqd_values = result.optimal_values print(vqd_values) import numpy as np import pylab pylab.rcParams["figure.figsize"] = (12, 8) steps = np.asarray(steps) counts = np.asarray(counts) values = np.asarray(values) for i in range(1,4): _counts = counts[np.where(steps == i)] _values = values[np.where(steps == i)] pylab.plot(_counts, _values, label=f"State {i-1}") pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence for each computed state") pylab.legend(loc="upper right"); from qiskit.algorithms.eigensolvers import NumPyEigensolver from qiskit.opflow import PauliSumOp exact_solver = NumPyEigensolver(k=3) exact_result = exact_solver.compute_eigenvalues(PauliSumOp(H2_op)) ref_values = exact_result.eigenvalues print(f"Reference values: {ref_values}") print(f"VQD values: {vqd_values}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/noamsgl/IBMAscolaChallenge
noamsgl
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import numpy as np filepath = "../datasets/universal_error/ReadoutOnly/U3_7.csv" df = pd.read_csv(filepath) # reorder columns df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'p0_0', 'p0_1', 'p1_0', 'p1_1']] # filter out inf values df = df[np.isfinite] df.info() df.head() sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]}) sns.distplot(df['E'], norm_hist=False, kde=False, bins=50, hist_kws={'alpha': 1}).set(xlabel="'Expected Value", ylabel='Count') df.hist(bins=100, figsize=(20,15), layout=(3,4)); sns.scatterplot(x=df['theta'], y=df['E']); sns.scatterplot(x=df['phi'], y=df['E']); sns.scatterplot(x=df['lam'], y=df['E']); sns.scatterplot(x=df['depol_prob'], y=df['E']); sns.jointplot(x=df['t1'], y=df['E']); sns.jointplot(x=df['t2'], y=df['E']); sns.pairplot(data=df);
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/xtophe388/QISKIT
xtophe388
import sys, getpass try: sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} print('Qconfig loaded from %s.' % Qconfig.__file__) except: APItoken = getpass.getpass('Please input your token and hit enter: ') qx_config = { "APItoken": APItoken, "url":"https://quantumexperience.ng.bluemix.net/api"} print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.') import numpy as np from time import sleep # used for polling jobs # importing the QISKit import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, QuantumProgram # import tomography library import qiskit.tools.qcvv.tomography as tomo # useful additional packages from qiskit.tools.visualization import plot_state, plot_histogram from qiskit.tools.qi.qi import state_fidelity, concurrence, purity, outer # Create a 2-qubit quantum register qr = QuantumRegister(2) cr = ClassicalRegister(2) # quantum circuit to make an entangled Bell state bell = QuantumCircuit(qr, cr, name='bell') bell.h(qr[1]) bell.cx(qr[1], qr[0]) job = qiskit.execute(bell, backend='local_statevector_simulator') bell_psi = job.result().get_statevector(bell) bell_rho = outer(bell_psi) # construct the density matrix from the state vector # plot the state plot_state(bell_rho,'paulivec') rho_mixed = np.array([[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]])/2 plot_state(rho_mixed, 'paulivec') # Construct state tomography set for measurement of qubits [0, 1] in the Pauli basis bell_tomo_set = tomo.state_tomography_set([0, 1]) # Create a quantum program containing the state preparation circuit Q_program = QuantumProgram() Q_program.add_circuit('bell', bell) # Add the state tomography measurement circuits to the Quantum Program bell_tomo_circuit_names = tomo.create_tomography_circuits(Q_program, 'bell', qr, cr, bell_tomo_set) print('Created State tomography circuits:') for name in bell_tomo_circuit_names: print(name) # Use the local simulator backend = 'local_qasm_simulator' # Take 5000 shots for each measurement basis shots = 5000 # Run the simulation bell_tomo_result = Q_program.execute(bell_tomo_circuit_names, backend=backend, shots=shots) print(bell_tomo_result) bell_tomo_data = tomo.tomography_data(bell_tomo_result, 'bell', bell_tomo_set) rho_fit = tomo.fit_tomography_data(bell_tomo_data) # calculate fidelity, concurrence and purity of fitted state F_fit = state_fidelity(rho_fit, bell_psi) con = concurrence(rho_fit) pur = purity(rho_fit) # plot plot_state(rho_fit, 'paulivec') print('Fidelity =', F_fit) print('concurrence = ', str(con)) print('purity = ', str(pur)) # Register API token for online backends qiskit.register(qx_config['APItoken'], qx_config['url']) # Use the IBM Quantum Experience backend = 'ibmqx4' # Take 1000 shots for each measurement basis # Note: reduce this number for larger number of qubits shots = 1000 # set max credits max_credits = 8 # Run the experiment status = qiskit.get_backend(backend).status if status['operational'] == False or status['pending_jobs'] > 10: print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible') bellqx_tomo_result = Q_program.execute(bell_tomo_circuit_names, backend=backend, shots=shots, max_credits=max_credits, timeout=500) print(bellqx_tomo_result) bellqx_tomo_data = tomo.tomography_data(bellqx_tomo_result, 'bell', bell_tomo_set) # Reconstruct experimentally measured density matrix rho_fit_real = tomo.fit_tomography_data(bellqx_tomo_data) F_fit_real = state_fidelity(rho_fit_real, bell_psi) plot_state(rho_fit_real, 'paulivec') print('Fidelity with ideal state') print('F =', F_fit_real) # calculate concurrence and purity con = concurrence(rho_fit_real) pur = purity(rho_fit_real) print('concurrence = ', str(con)) print('purity = ', str(pur))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123456 from sklearn.datasets import make_blobs features, labels = make_blobs( n_samples=20, centers=2, center_box=(-1, 1), cluster_std=0.1, random_state=algorithm_globals.random_seed, ) from qiskit import BasicAer from qiskit.utils import QuantumInstance sv_qi = QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) from qiskit.circuit.library import ZZFeatureMap from qiskit_machine_learning.kernels import QuantumKernel feature_map = ZZFeatureMap(2) previous_kernel = QuantumKernel(feature_map=feature_map, quantum_instance=sv_qi) from qiskit_machine_learning.algorithms import QSVC qsvc = QSVC(quantum_kernel=previous_kernel) qsvc.fit(features, labels) qsvc.score(features, labels) from qiskit.algorithms.state_fidelities import ComputeUncompute from qiskit.primitives import Sampler fidelity = ComputeUncompute(sampler=Sampler()) from qiskit_machine_learning.kernels import FidelityQuantumKernel feature_map = ZZFeatureMap(2) new_kernel = FidelityQuantumKernel(feature_map=feature_map, fidelity=fidelity) from qiskit_machine_learning.algorithms import QSVC qsvc = QSVC(quantum_kernel=new_kernel) qsvc.fit(features, labels) qsvc.score(features, labels) from qiskit import QuantumCircuit from qiskit.circuit.library import RealAmplitudes num_inputs = 2 feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, reps=1) circuit = QuantumCircuit(num_inputs) circuit.compose(feature_map, inplace=True) circuit.compose(ansatz, inplace=True) def parity(x): return "{:b}".format(x).count("1") % 2 initial_point = algorithm_globals.random.random(ansatz.num_parameters) from qiskit_machine_learning.neural_networks import CircuitQNN circuit_qnn = CircuitQNN( circuit=circuit, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=2, quantum_instance=sv_qi, ) from qiskit.algorithms.optimizers import COBYLA from qiskit_machine_learning.algorithms import NeuralNetworkClassifier classifier = NeuralNetworkClassifier( neural_network=circuit_qnn, loss="cross_entropy", one_hot=True, optimizer=COBYLA(maxiter=40), initial_point=initial_point, ) classifier.fit(features, labels) classifier.score(features, labels) from qiskit.primitives import Sampler sampler = Sampler() from qiskit_machine_learning.neural_networks import SamplerQNN sampler_qnn = SamplerQNN( circuit=circuit, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=2, sampler=sampler, ) classifier = NeuralNetworkClassifier( neural_network=sampler_qnn, loss="cross_entropy", one_hot=True, optimizer=COBYLA(maxiter=40), initial_point=initial_point, ) classifier.fit(features, labels) classifier.score(features, labels) import numpy as np num_samples = 20 eps = 0.2 lb, ub = -np.pi, np.pi features = (ub - lb) * np.random.rand(num_samples, 1) + lb labels = np.sin(features[:, 0]) + eps * (2 * np.random.rand(num_samples) - 1) from qiskit.circuit import Parameter num_inputs = 1 feature_map = QuantumCircuit(1) feature_map.ry(Parameter("input"), 0) ansatz = QuantumCircuit(1) ansatz.ry(Parameter("weight"), 0) circuit = QuantumCircuit(num_inputs) circuit.compose(feature_map, inplace=True) circuit.compose(ansatz, inplace=True) initial_point = algorithm_globals.random.random(ansatz.num_parameters) from qiskit.opflow import PauliSumOp, StateFn from qiskit_machine_learning.neural_networks import OpflowQNN observable = PauliSumOp.from_list([("Z", 1)]) operator = StateFn(observable, is_measurement=True) @ StateFn(circuit) opflow_qnn = OpflowQNN( operator=operator, input_params=feature_map.parameters, weight_params=ansatz.parameters, quantum_instance=sv_qi, ) from qiskit.algorithms.optimizers import L_BFGS_B from qiskit_machine_learning.algorithms import NeuralNetworkRegressor regressor = NeuralNetworkRegressor( neural_network=opflow_qnn, optimizer=L_BFGS_B(maxiter=5), initial_point=initial_point, ) regressor.fit(features, labels) regressor.score(features, labels) from qiskit.primitives import Estimator estimator = Estimator() from qiskit_machine_learning.neural_networks import EstimatorQNN estimator_qnn = EstimatorQNN( circuit=circuit, input_params=feature_map.parameters, weight_params=ansatz.parameters, estimator=estimator, ) from qiskit.algorithms.optimizers import L_BFGS_B from qiskit_machine_learning.algorithms import VQR regressor = NeuralNetworkRegressor( neural_network=estimator_qnn, optimizer=L_BFGS_B(maxiter=5), initial_point=initial_point, ) regressor.fit(features, labels) regressor.score(features, labels) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test RemoveResetInZeroState pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import RemoveResetInZeroState, DAGFixedPoint from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestRemoveResetInZeroState(QiskitTestCase): """Test swap-followed-by-measure optimizations.""" def test_optimize_single_reset(self): """Remove a single reset qr0:--|0>-- ==> qr0:---- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.reset(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) pass_ = RemoveResetInZeroState() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_dont_optimize_non_zero_state(self): """Do not remove reset if not in a zero state qr0:--[H]--|0>-- ==> qr0:--[H]--|0>-- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr) circuit.reset(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.h(qr) expected.reset(qr) pass_ = RemoveResetInZeroState() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_single_reset_in_diff_qubits(self): """Remove a single reset in different qubits qr0:--|0>-- qr0:---- ==> qr1:--|0>-- qr1:---- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.reset(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) pass_ = RemoveResetInZeroState() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) class TestRemoveResetInZeroStateFixedPoint(QiskitTestCase): """Test RemoveResetInZeroState in a transpiler, using fixed point.""" def test_two_resets(self): """Remove two initial resets qr0:--|0>-|0>-- ==> qr0:---- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.reset(qr[0]) circuit.reset(qr[0]) expected = QuantumCircuit(qr) pass_manager = PassManager() pass_manager.append( [RemoveResetInZeroState(), DAGFixedPoint()], do_while=lambda property_set: not property_set["dag_fixed_point"], ) after = pass_manager.run(circuit) self.assertEqual(expected, after) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import os import sys cwd = os.getcwd() qiskit_dir = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(cwd)))) sys.path.append(qiskit_dir) from qiskit import BasicAer, execute from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.compiler import transpile from qiskit.tools.parallel import parallel_map from qiskit.tools.monitor import job_monitor from qiskit.tools.events import TextProgressBar from qiskit.tools.jupyter import * sim_backend = BasicAer.get_backend("qasm_simulator") import time def func(_): time.sleep(0.1) return 0 HTMLProgressBar() parallel_map(func, list(range(10))); %qiskit_progress_bar parallel_map(func, list(range(10))); TextProgressBar() parallel_map(func, list(range(10))); %qiskit_progress_bar -t text parallel_map(func, list(range(10))); q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) HTMLProgressBar() qobj = transpile([qc] * 20, backend=sim_backend) job_sim2 = execute([qc] * 10, backend=sim_backend) job_monitor(job_sim2)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit,IBMQ, execute from qiskit.visualization import * from qiskit.tools import job_monitor # Bell Quantum Circuit qc=QuantumCircuit(2,2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") qc.measure([0,1],[0,1]) qc.draw(output="mpl") #IBMQ.save_account('TOKEN ID needs to be provided') #Load the account provider=IBMQ.load_account() provider.backends() #Get the backend backend=provider.get_backend('ibmq_bogota') #Execute the circuit on the backend job=execute(qc,backend,shots=1024) job.status() backend.status() job_monitor(job) job.status() #Obtain the result result=job.result() #get and print the counts counts=result.get_counts() print(counts) plot_histogram(counts,title="Bell State Counts") job.job_id() job.backend() job.result() job.status() jobID=job.job_id() job_get=backend.retrieve_job(jobID) job_get job_get.result().get_counts(qc) counts backend.jobs() ## 3. List of unfinished jobs of the backend: active_jobs() backend.active_jobs() ## 4. No of jobs which can be submitted to the backend : remaining_jobs_count() backend.remaining_jobs_count() backend.status() backend.name() backend.provider()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver() problem = driver.run() fermionic_op = problem.hamiltonian.second_q_op() from qiskit_nature.second_q.mappers import JordanWignerMapper mapper = JordanWignerMapper() qubit_jw_op = mapper.map(fermionic_op) print(qubit_jw_op) from qiskit_nature.second_q.mappers import ParityMapper mapper = ParityMapper() qubit_p_op = mapper.map(fermionic_op) print(qubit_p_op) mapper = ParityMapper(num_particles=problem.num_particles) qubit_op = mapper.map(fermionic_op) print(qubit_op) tapered_mapper = problem.get_tapered_mapper(mapper) print(type(tapered_mapper)) qubit_op = tapered_mapper.map(fermionic_op) print(qubit_op) from qiskit_nature.second_q.circuit.library import HartreeFock hf_state = HartreeFock(2, (1, 1), JordanWignerMapper()) hf_state.draw() from qiskit_nature.second_q.mappers import InterleavedQubitMapper interleaved_mapper = InterleavedQubitMapper(JordanWignerMapper()) hf_state = HartreeFock(2, (1, 1), interleaved_mapper) hf_state.draw() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Harcipan/QAI_GroverSim
Harcipan
# Built-in modules import math # Imports from Qiskit from qiskit import QuantumCircuit from qiskit.circuit.library import GroverOperator, MCMT, ZGate from qiskit.visualization import plot_distribution # Imports from Qiskit Runtime from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Batch # To run on hardware, select the backend with the fewest number of jobs in the queue service = QiskitRuntimeService(channel="ibm_quantum") backend = service.least_busy(operational=True, simulator=False) backend.name def grover_oracle(marked_states): """Build a Grover oracle for multiple marked states Here we assume all input marked states have the same number of bits Parameters: marked_states (str or list): Marked states of oracle Returns: QuantumCircuit: Quantum circuit representing Grover oracle """ if not isinstance(marked_states, list): marked_states = [marked_states] # Compute the number of qubits in circuit num_qubits = len(marked_states[0]) qc = QuantumCircuit(num_qubits) # Mark each target state in the input list for target in marked_states: # Flip target bit-string to match Qiskit bit-ordering rev_target = target[::-1] # Find the indices of all the '0' elements in bit-string zero_inds = [ind for ind in range(num_qubits) if rev_target.startswith("0", ind)] # Add a multi-controlled Z-gate with pre- and post-applied X-gates (open-controls) # where the target bit-string has a '0' entry qc.x(zero_inds) qc.compose(MCMT(ZGate(), num_qubits - 1, 1), inplace=True) qc.x(zero_inds) return qc marked_states = ["011", "100"] oracle = grover_oracle(marked_states) oracle.draw(output="mpl", style="iqp") grover_op = GroverOperator(oracle) grover_op.decompose().draw(output="mpl", style="iqp") optimal_num_iterations = math.floor( math.pi / (4 * math.asin(math.sqrt(len(marked_states) / 2**grover_op.num_qubits))) ) qc = QuantumCircuit(grover_op.num_qubits) # Create even superposition of all basis states qc.h(range(grover_op.num_qubits)) # Apply Grover operator the optimal number of times qc.compose(grover_op.power(optimal_num_iterations), inplace=True) # Measure all qubits qc.measure_all() qc.draw(output="mpl", style="iqp") # To run on local simulator: # 1. Use the Sampler from qiskit.primitives instead # 2. Remove the Batch context manager below with Batch(backend=backend) as batch: sampler = Sampler() dist = sampler.run(qc, shots=10000).result().quasi_dists[0] plot_distribution(dist.binary_probabilities())
https://github.com/AnkRaw/Quantum-Convolutional-Neural-Network
AnkRaw
# Importing Libraries import torch from torch import cat, no_grad, manual_seed from torch.utils.data import DataLoader from torchvision import transforms import torch.optim as optim from torch.nn import ( Module, Conv2d, Linear, Dropout2d, NLLLoss ) import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt from qiskit_machine_learning.neural_networks import EstimatorQNN from qiskit_machine_learning.connectors import TorchConnector from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit import QuantumCircuit from qiskit.visualization import circuit_drawer # Imports for CIFAR-10s from torchvision.datasets import CIFAR10 from torchvision import transforms def prepare_data(X, labels_to_keep, batch_size): # Filtering out labels (originally 0-9), leaving only labels 0 and 1 filtered_indices = [i for i in range(len(X.targets)) if X.targets[i] in labels_to_keep] X.data = X.data[filtered_indices] X.targets = [X.targets[i] for i in filtered_indices] # Defining dataloader with filtered data loader = DataLoader(X, batch_size=batch_size, shuffle=True) return loader # Set seed for reproducibility manual_seed(42) # CIFAR-10 data transformation transform = transforms.Compose([ transforms.ToTensor(), # convert the images to tensors transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # Normalization usign mean and std. ]) labels_to_keep = [0, 1] batch_size = 1 # Preparing Train Data X_train = CIFAR10(root="./data", train=True, download=True, transform=transform) train_loader = prepare_data(X_train, labels_to_keep, batch_size) # Preparing Test Data X_test = CIFAR10(root="./data", train=False, download=True, transform=transform) test_loader = prepare_data(X_test, labels_to_keep, batch_size) print(f"Training dataset size: {len(train_loader.dataset)}") print(f"Test dataset size: {len(test_loader.dataset)}") # Defining and creating QNN def create_qnn(): feature_map = ZZFeatureMap(2) # ZZFeatureMap with 2 bits, entanglement between qubits based on the pairwise product of input features. ansatz = RealAmplitudes(2, reps=1) # parameters (angles, in the case of RealAmplitudes) that are adjusted during the training process to optimize the quantum model for a specific task. qc = QuantumCircuit(2) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, input_gradients=True, ) return qnn qnn = create_qnn() # Visualizing the QNN circuit circuit_drawer(qnn.circuit, output='mpl') # Defining torch NN module class Net(Module): def __init__(self, qnn): super().__init__() self.conv1 = Conv2d(3, 16, kernel_size=3, padding=1) self.conv2 = Conv2d(16, 32, kernel_size=3, padding=1) self.dropout = Dropout2d() self.fc1 = Linear(32 * 8 * 8, 64) self.fc2 = Linear(64, 2) # 2-dimensional input to QNN self.qnn = TorchConnector(qnn) self.fc3 = Linear(1, 1) # 1-dimensional output from QNN def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) x = self.fc3(x) return cat((x, 1 - x), -1) # Creating model model = Net(qnn) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) # Defining model, optimizer, and loss function optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = NLLLoss() # Starting training epochs = 10 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) # Move data to GPU optimizer.zero_grad(set_to_none=True) output = model(data) loss = loss_func(output, target) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss) / len(total_loss)) print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1])) # Plotting loss convergence plt.plot(loss_list) plt.title("Hybrid NN Training Convergence") plt.xlabel("Training Iterations") plt.ylabel("Neg. Log Likelihood Loss") plt.show() # Saving the model torch.save( model.state_dict(), "model_cifar10_10EPOCHS.pt") # Loading the model qnn_cifar10 = create_qnn() model_cifar10 = Net(qnn_cifar10) model_cifar10.load_state_dict(torch.load("model_cifar10.pt")) correct = 0 total = 0 model_cifar10.eval() with torch.no_grad(): for data, target in test_loader: output = model_cifar10(data) _, predicted = torch.max(output.data, 1) total += target.size(0) correct += (predicted == target).sum().item() # Calculating and print test accuracy test_accuracy = correct / total * 100 print(f"Test Accuracy: {test_accuracy:.2f}%") # Plotting predicted labels n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model_cifar10.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model_cifar10(data) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(np.transpose(data[0].numpy(), (1, 2, 0))) axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title("Predicted {0}\n Actual {1}".format(pred.item(), target.item())) count += 1 plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import BasicAer from qiskit.compiler import transpile from qiskit.quantum_info.operators import Operator, Pauli from qiskit.quantum_info import process_fidelity from qiskit.extensions import RXGate, XGate, CXGate XX = Operator([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]) XX XX.data input_dim, output_dim = XX.dim input_dim, output_dim op = Operator(np.random.rand(2 ** 1, 2 ** 2)) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) op = Operator(np.random.rand(6, 6)) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) # Force input dimension to be (4,) rather than (2, 2) op = Operator(np.random.rand(2 ** 1, 2 ** 2), input_dims=[4]) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) # Specify system is a qubit and qutrit op = Operator(np.random.rand(6, 6), input_dims=[2, 3], output_dims=[2, 3]) print('Input dimensions:', op.input_dims()) print('Output dimensions:', op.output_dims()) print('Dimension of input system 0:', op.input_dims([0])) print('Dimension of input system 1:', op.input_dims([1])) # Create an Operator from a Pauli object pauliXX = Pauli('XX') Operator(pauliXX) # Create an Operator for a Gate object Operator(CXGate()) # Create an operator from a parameterized Gate object Operator(RXGate(np.pi / 2)) # Create an operator from a QuantumCircuit object circ = QuantumCircuit(10) circ.h(0) for j in range(1, 10): circ.cx(j-1, j) # Convert circuit to an operator by implicit unitary simulation Operator(circ) # Create an operator XX = Operator(Pauli('XX')) # Add to a circuit circ = QuantumCircuit(2, 2) circ.append(XX, [0, 1]) circ.measure([0,1], [0,1]) circ.draw('mpl') backend = BasicAer.get_backend('qasm_simulator') circ = transpile(circ, backend, basis_gates=['u1','u2','u3','cx']) job = backend.run(circ) job.result().get_counts(0) # Add to a circuit circ2 = QuantumCircuit(2, 2) circ2.append(Pauli('XX'), [0, 1]) circ2.measure([0,1], [0,1]) circ2.draw() A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.tensor(B) A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.expand(B) A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.compose(B) A = Operator(Pauli('X')) B = Operator(Pauli('Z')) A.compose(B, front=True) # Compose XZ with an 3-qubit identity operator op = Operator(np.eye(2 ** 3)) XZ = Operator(Pauli('XZ')) op.compose(XZ, qargs=[0, 2]) # Compose YX in front of the previous operator op = Operator(np.eye(2 ** 3)) YX = Operator(Pauli('YX')) op.compose(XZ, qargs=[0, 2], front=True) XX = Operator(Pauli('XX')) YY = Operator(Pauli('YY')) ZZ = Operator(Pauli('ZZ')) op = 0.5 * (XX + YY - 3 * ZZ) op op.is_unitary() # Compose with a matrix passed as a list Operator(np.eye(2)).compose([[0, 1], [1, 0]]) Operator(Pauli('X')) == Operator(XGate()) Operator(XGate()) == np.exp(1j * 0.5) * Operator(XGate()) # Two operators which differ only by phase op_a = Operator(XGate()) op_b = np.exp(1j * 0.5) * Operator(XGate()) # Compute process fidelity F = process_fidelity(op_a, op_b) print('Process fidelity =', F) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit circ = QuantumCircuit(2, 2) circ.h(0) circ.cx(0, 1) circ.measure([0, 1], [0, 1]) circ.draw("mpl") from qiskit import transpile, schedule as build_schedule from qiskit.providers.fake_provider import FakeHanoi backend = FakeHanoi() transpiled_circ = transpile(circ, backend) # Undefined Hadamard is replaced by U1 schedule = build_schedule(transpiled_circ, backend) schedule.draw() from qiskit import pulse with pulse.build() as h_q0: pulse.play(pulse.library.Gaussian(duration=256, amp=0.2, sigma=50, name='custom'), pulse.DriveChannel(0)) circ.add_calibration('h', [0], h_q0) schedule = build_schedule(circ, backend) schedule.draw() circ = QuantumCircuit(2, 2) circ.x(0) circ.x(0) circ.x(1) circ.measure([0, 1], [0, 1]) circ.draw("mpl") schedule = build_schedule(circ, backend, method="as_late_as_possible") schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw() schedule = build_schedule(circ, backend, method="as_soon_as_possible") schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/greatdevaks/geopython-qiskit
greatdevaks
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # Importing basic math libraries from math import pi, sqrt # Loading your IBM Q account(s) provider = IBMQ.load_account() # Definining the simulator: statevector_simulator, or qasm_simulator simulator = "qasm_simulator" # Function to plot the Quantum Circuit / Quantum State def get_plot(quantum_circuit): """ Parameters: quantum_circuit: The Quantum Circuit to visualize Returns: return: Plot/Visualization of the Quantum State """ sim = Aer.get_backend(simulator) quantum_object = assemble(quantum_circuit) if simulator == "statevector_simulator": result = sim.run(quantum_object).result() statevector = result.get_statevector() return plot_bloch_multivector(statevector) elif simulator == "qasm_simulator": result = sim.run(quantum_object).result() count = result.get_counts() return plot_histogram(count) # Creating a single qubit Quantum Circuit num_qubits = 2 qc = QuantumCircuit(num_qubits) # Creates a Quantum Circuit with 1 qubit num_input_qubits = num_qubits # defines the number of qubits in the circuit num_output_qubits = num_qubits # defines the number of output bits that we want to extract from the circuit # Note: The extraction of output from a Quantum Circuit is done via a process called `measurement` # Each measurement tells a specific qubit to give an output to a specific output bit qc_output = QuantumCircuit(num_input_qubits, num_output_qubits) # qc_output is the Quantum Circuit # Visualizing the Quantum Wire qc_output.draw() # Drawing the Quantum Circuit # Here C is represents the measurement results / count # Applying H-gate to the first qubit q0: qc_output.h(0) # Applying X-gate to the first qubit q: qc_output.x(1) qc_output.draw() # Drawing the Quantum Circuit # TAKING MEASUREMENT ONLY FOR EXPLANATION PURPOSES # IN REAL CIRCUITS, MEASUREMENTS SHOULD NOT BE TAKEN LIKE THIS IN THE INTERMEDIATE STATES # MEASUREMENT CHANGES THE QUBIT'S STATE # Measuring the results for qubit in range(num_qubits): qc_output.measure(qubit, qubit) qc_output.draw() # Drawing the Quantum Circuit # Initial state of each qubit is |0> # After Hadamard gate is applied to q0, q0 can be in 0 or 1 state when measured (as Hadamard Gate # will bring q0 to some superposition state) # H q0 => |0> -> |0> or |1> # Applying Pauli-X Gate on q1 will flip its qubit state # X q1 => |0> -> |1> # Quantum State analysis for the above circuit # q0 q1 output # 0 1 0 1 # 1 1 1 1 # Getting the plot and visualization get_plot(qc_output) # Applying a CNOT gate from qubit q0 to qubit q1: qc_output.cx(0,1) qc_output.draw() # Drawing the Quantum Circuit # Measuring the results for qubit in range(num_qubits): qc_output.measure(qubit, qubit) # Visualizing the Quantum Circuit using Simulator qc_output.draw() # Drawing the Quantum Circuit # Quantum State analysis for the previously measure circuit # q0 q1 output # 0 1 0 1 # 1 1 1 1 # Applying CNOT Gate on from q0 to q1 will conditionally flip the q1 qubit # q0 q1 output # 0 1 0 1 # 1 1 1 0 # Getting the plot and visualization get_plot(qc_output)
https://github.com/Harcipan/QAI_GroverSim
Harcipan
import numpy as np import math from qiskit import QuantumCircuit from qiskit.circuit.library import GroverOperator, MCMT, ZGate from qiskit.visualization import plot_distribution from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session from qiskit.providers.basic_provider import BasicProvider from qiskit.visualization import plot_histogram from qiskit import transpile from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(num_qubits=5) def grover_oracle(marked_states, i, j, k): if not isinstance(marked_states, list): marked_states = [marked_states] num_qubits = len(marked_states[0]) qc = QuantumCircuit(num_qubits) for target in marked_states: rev_target = target[::-1] zero_inds = [ind for ind in range(num_qubits) if rev_target.startswith("0", ind)] qc.x(zero_inds) """ZAJ 1""" qc.rx(i,zero_inds) qc.ry(j,zero_inds) qc.rz(k,zero_inds) qc.compose(MCMT(ZGate(), num_qubits - 1, 1), inplace=True) qc.x(zero_inds) return qc def printToConsole(): # Format counts data formatted_output = "" #for state in ['000', '001', '010', '011', '100', '101', '110', '111']: for state in ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']: formatted_output += f"{counts.get(state, 0)} " # Write counts data to a text file with open('counts_data.txt', 'a') as file: file.write(formatted_output) file.write(f"{x} {y} {z}\n") if(printDebug): import matplotlib.pyplot as plt # Parse counts data counts_data = {state: counts.get(state, 0) for state in ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']} #for state in ['000', '001', '010', '011', '100', '101', '110', '111']} # Plot counts plt.bar(counts_data.keys(), counts_data.values()) plt.xlabel('States') plt.ylabel('Counts') plt.title('Quantum Circuit Measurement Results') plt.show() print(counts_data) marked_states = ["0010", "1000"] printDebug = False randomXYZ = False #RX, RY, RZ trasformators causing error in the grover oracle by rotating state by v/100 fromRot = -100 toRot = 101 XYZ = 2 #1->RX, 2->RY, 3->RZ num_simulations = 10 #averaging this many simulations, (good for graphing) for i in range(fromRot, toRot,1): # Initialize empty dictionary for averages averages = {} x=0 y=0 z=0 # Loop for multiple simulations for _ in range(num_simulations): zaj=i if(randomXYZ): k = random.randrange(-100,100)#-1 - +1 fok kozott random zaj if XYZ == 1: x=zaj/100 elif XYZ == 2: y=zaj/100 elif XYZ == 3: z=zaj/100 oracle = grover_oracle(marked_states, x, y, z) grover_op = GroverOperator(oracle) optimal_num_iterations = math.floor(math.pi / 4 * math.sqrt(2 ** grover_op.num_qubits / len(marked_states))) qc = QuantumCircuit(grover_op.num_qubits) qc.h(range(grover_op.num_qubits)) qc.compose(grover_op.power(optimal_num_iterations), inplace=True) qc.measure_all() backend = GenericBackendV2(num_qubits=4) transpiled_circuit = transpile(qc, backend) job = backend.run(transpiled_circuit) counts = job.result().get_counts() # Update averages for each state #for state in ['000', '001', '010', '011', '100', '101', '110', '111']: for state in ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']: averages[state] = averages.get(state, 0) + counts.get(state, 0) # Calculate averages for state in averages: averages[state] /= num_simulations # Write averages to a text file with open('averages_data.txt', 'a') as file: for state in averages: file.write(f"{int(averages[state])} ") file.write(f"{x} {y} {z}") file.write("\n") if(printDebug): printToConsole() print("All done")
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
from qiskit import * from qiskit.tools.visualization import plot_histogram import numpy as np qr = QuantumRegister(1) cr = ClassicalRegister(1) error = {} for n in range(1,11): # Create a blank circuit qc = QuantumCircuit(qr,cr) # Implement an approximate Hadamard theta = np.pi/np.sqrt(2) # here we correctly choose theta=pi/sqrt(2) for j in range(n): qc.rx(theta/n,qr[0]) qc.rz(theta/n,qr[0]) # We need to measure how good the above approximation is. Here's a simple way to do this. # Step 1: Use a real hadamard to cancel the above approximation. # For a good approximatuon, the qubit will return to state 0. For a bad one, it will end up as some superposition. qc.h(qr[0]) # Step 2: Run the circuit, and see how many times we get the outcome 1. # Since it should return 0 with certainty, the fraction of 1s is a measure of the error. qc.measure(qr,cr) shots = 20000 job = execute(qc, Aer.get_backend('qasm_simulator'),shots=shots) try: error[n] = (job.result().get_counts()['1']/shots) except: pass plot_histogram(error) # The linear nature of error^(-1/2) shows that the error has a quadratic decay. inverse_square_of_error = {} for n in error: inverse_square_of_error[n] = (error[n])**(-1/2) plot_histogram(inverse_square_of_error) qr = QuantumRegister(1) cr = ClassicalRegister(1) error = {} for n in range(1,11): # Create a blank circuit qc = QuantumCircuit(qr,cr) # Implement an approximate Hadamard theta = np.pi/np.sqrt(2) # here we correctly use theta=pi/sqrt(2) for j in range(n): qc.rz(theta/(2*n),qr[0]) qc.rx(theta/n,qr[0]) qc.rz(theta/(2*n),qr[0]) # We need to measure how good the above approximation is. Here's a simple way to do this. # Step 1: Use a real hadamard to cancel the above approximation. # For a good approximatuon, the qubit will return to state 0. For a bad one, it will end up as some superposition. qc.h(qr[0]) # Step 2: Run the circuit, and see how many times we get the outcome 1. # Since it should return 0 with certainty, the fraction of 1s is a measure of the error. qc.measure(qr,cr) shots = 100000 job = execute(qc, Aer.get_backend('qasm_simulator'),shots=shots) try: error[n] = (job.result().get_counts()['1']/shots) except: pass plot_histogram(error) # The linear nature of error^(-1/3) shows that the error has a cubic decay. # Note: this needs loads of shots to get a good result. inverse_cube_of_error = {} for n in error: error[n] inverse_cube_of_error[n] = (error[n])**(-1/3) plot_histogram(inverse_cube_of_error)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import json import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit import ParameterVector from qiskit.circuit.library import ZFeatureMap from qiskit.quantum_info import SparsePauliOp from qiskit.utils import algorithm_globals from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier from qiskit_machine_learning.neural_networks import EstimatorQNN from sklearn.model_selection import train_test_split algorithm_globals.random_seed = 12345 # We now define a two qubit unitary as defined in [3] def conv_circuit(params): target = QuantumCircuit(2) target.rz(-np.pi / 2, 1) target.cx(1, 0) target.rz(params[0], 0) target.ry(params[1], 1) target.cx(0, 1) target.ry(params[2], 1) target.cx(1, 0) target.rz(np.pi / 2, 0) return target # Let's draw this circuit and see what it looks like params = ParameterVector("θ", length=3) circuit = conv_circuit(params) circuit.draw("mpl") def conv_layer(num_qubits, param_prefix): qc = QuantumCircuit(num_qubits, name="Convolutional Layer") qubits = list(range(num_qubits)) param_index = 0 params = ParameterVector(param_prefix, length=num_qubits * 3) for q1, q2 in zip(qubits[0::2], qubits[1::2]): qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2]) qc.barrier() param_index += 3 for q1, q2 in zip(qubits[1::2], qubits[2::2] + [0]): qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2]) qc.barrier() param_index += 3 qc_inst = qc.to_instruction() qc = QuantumCircuit(num_qubits) qc.append(qc_inst, qubits) return qc circuit = conv_layer(4, "θ") circuit.decompose().draw("mpl") def pool_circuit(params): target = QuantumCircuit(2) target.rz(-np.pi / 2, 1) target.cx(1, 0) target.rz(params[0], 0) target.ry(params[1], 1) target.cx(0, 1) target.ry(params[2], 1) return target params = ParameterVector("θ", length=3) circuit = pool_circuit(params) circuit.draw("mpl") def pool_layer(sources, sinks, param_prefix): num_qubits = len(sources) + len(sinks) qc = QuantumCircuit(num_qubits, name="Pooling Layer") param_index = 0 params = ParameterVector(param_prefix, length=num_qubits // 2 * 3) for source, sink in zip(sources, sinks): qc = qc.compose(pool_circuit(params[param_index : (param_index + 3)]), [source, sink]) qc.barrier() param_index += 3 qc_inst = qc.to_instruction() qc = QuantumCircuit(num_qubits) qc.append(qc_inst, range(num_qubits)) return qc sources = [0, 1] sinks = [2, 3] circuit = pool_layer(sources, sinks, "θ") circuit.decompose().draw("mpl") def generate_dataset(num_images): images = [] labels = [] hor_array = np.zeros((6, 8)) ver_array = np.zeros((4, 8)) j = 0 for i in range(0, 7): if i != 3: hor_array[j][i] = np.pi / 2 hor_array[j][i + 1] = np.pi / 2 j += 1 j = 0 for i in range(0, 4): ver_array[j][i] = np.pi / 2 ver_array[j][i + 4] = np.pi / 2 j += 1 for n in range(num_images): rng = algorithm_globals.random.integers(0, 2) if rng == 0: labels.append(-1) random_image = algorithm_globals.random.integers(0, 6) images.append(np.array(hor_array[random_image])) elif rng == 1: labels.append(1) random_image = algorithm_globals.random.integers(0, 4) images.append(np.array(ver_array[random_image])) # Create noise for i in range(8): if images[-1][i] == 0: images[-1][i] = algorithm_globals.random.uniform(0, np.pi / 4) return images, labels images, labels = generate_dataset(50) train_images, test_images, train_labels, test_labels = train_test_split( images, labels, test_size=0.3 ) fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []}) for i in range(4): ax[i // 2, i % 2].imshow( train_images[i].reshape(2, 4), # Change back to 2 by 4 aspect="equal", ) plt.subplots_adjust(wspace=0.1, hspace=0.025) feature_map = ZFeatureMap(8) feature_map.decompose().draw("mpl") feature_map = ZFeatureMap(8) ansatz = QuantumCircuit(8, name="Ansatz") # First Convolutional Layer ansatz.compose(conv_layer(8, "с1"), list(range(8)), inplace=True) # First Pooling Layer ansatz.compose(pool_layer([0, 1, 2, 3], [4, 5, 6, 7], "p1"), list(range(8)), inplace=True) # Second Convolutional Layer ansatz.compose(conv_layer(4, "c2"), list(range(4, 8)), inplace=True) # Second Pooling Layer ansatz.compose(pool_layer([0, 1], [2, 3], "p2"), list(range(4, 8)), inplace=True) # Third Convolutional Layer ansatz.compose(conv_layer(2, "c3"), list(range(6, 8)), inplace=True) # Third Pooling Layer ansatz.compose(pool_layer([0], [1], "p3"), list(range(6, 8)), inplace=True) # Combining the feature map and ansatz circuit = QuantumCircuit(8) circuit.compose(feature_map, range(8), inplace=True) circuit.compose(ansatz, range(8), inplace=True) observable = SparsePauliOp.from_list([("Z" + "I" * 7, 1)]) # we decompose the circuit for the QNN to avoid additional data copying qnn = EstimatorQNN( circuit=circuit.decompose(), observables=observable, input_params=feature_map.parameters, weight_params=ansatz.parameters, ) circuit.draw("mpl") def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() with open("11_qcnn_initial_point.json", "r") as f: initial_point = json.load(f) classifier = NeuralNetworkClassifier( qnn, optimizer=COBYLA(maxiter=200), # Set max iterations here callback=callback_graph, initial_point=initial_point, ) x = np.asarray(train_images) y = np.asarray(train_labels) objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) classifier.fit(x, y) # score classifier print(f"Accuracy from the train data : {np.round(100 * classifier.score(x, y), 2)}%") y_predict = classifier.predict(test_images) x = np.asarray(test_images) y = np.asarray(test_labels) print(f"Accuracy from the test data : {np.round(100 * classifier.score(x, y), 2)}%") # Let's see some examples in our dataset fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []}) for i in range(0, 4): ax[i // 2, i % 2].imshow(test_images[i].reshape(2, 4), aspect="equal") if y_predict[i] == -1: ax[i // 2, i % 2].set_title("The QCNN predicts this is a Horizontal Line") if y_predict[i] == +1: ax[i // 2, i % 2].set_title("The QCNN predicts this is a Vertical Line") plt.subplots_adjust(wspace=0.1, hspace=0.5) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open(filename, "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 import nbimporter from typing import Dict, Tuple, List import numpy as np from tqdm import tqdm QUBITS_NUM = 4 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 50 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals seed = 50 algorithm_globals.random_seed = seed simulator_backend = Aer.get_backend('qasm_simulator') from scipy.optimize import minimize from linear_entangelment_and_full_entangelment_ansatz_circuits import * def get_ansatz_state(thetas, ansatz_entangelment, input_state): if ansatz_entangelment=="full": return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state) if ansatz_entangelment=="linear": return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state) def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List: pauli_operators = hamiltonian.to_pauli_op().settings['oplist'] pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators)) pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators)) return pauli_coeffs, pauli_strings from qiskit.circuit.library.standard_gates import HGate, SGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister reducing_to_pauli_z_mapping = { 'I': 'I', 'Z': 'Z', 'X': 'Z', 'Y': 'Z' } def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str: reduced_pauli_string = "" for matrix_index in range(QUBITS_NUM): pauli_matrix = str(pauli_string[matrix_index]) reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix] reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string return reduced_pauli_string def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit): quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit") additional_circuit_layer = QuantumCircuit(quantum_registers) for quantum_register_index, pauli_matrix in enumerate(pauli_string): if pauli_matrix == "X": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) if pauli_string == "Y": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]]) extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer) return extended_quantum_circuit def get_probability_distribution(counts: Dict) -> Dict: proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()} return proba_distribution def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict: quantum_state_circuit.measure_all() transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend) Qobj = assemble(transpiled_quantum_state_circuit) result = simulator_backend.run(Qobj).result() counts = result.get_counts(quantum_state_circuit) return get_probability_distribution(counts) def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict: return dict(sorted(proba_distribution.items())) def reset_power_of_minus_1(power_of_minus_1): power_of_minus_1 = 0 return power_of_minus_1 def convert_pauli_string_into_str(pauli_string) -> str: return str(pauli_string) def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit): pauli_string_expectation_value = 0 power_of_minus_1 = 0 pauli_string_str = convert_pauli_string_into_str(pauli_string) extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit) probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit) reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string) sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution) for qubits_string, proba in sorted_probas_distribuition.items(): for string_index in range(QUBITS_NUM): if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"): power_of_minus_1 += 1 pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1) return pauli_string_expectation_value def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings): total_expection_value = 0 for pauli_coeff, pauli_string in zip(pauli_coeffs, pauli_strings): total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas( pauli_string, ansatz_circuit) return total_expection_value from qiskit import assemble, transpile def cost_function(thetas, hamiltonian, ansatz_entangelment): initial_eigenvector = np.identity(N)[0] pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector) L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings) insert_approximated_energy_to_list_of_all_approximated_energies(L) return L def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment): initial_thetas = np.random.uniform(low=0, high=360, size=PARAMS_NUM) optimizer_result = minimize(cost_function, x0=initial_thetas, args=(hamiltonian, ansatz_entangelment), method="BFGS", options={"maxiter":NUM_ITERATIONS, "disp": True}) optimal_thetas = optimizer_result.x return optimal_thetas def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment): optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment) print(optimal_thetas) initial_eigenvector = np.identity(N)[0] optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings) return approximated_eigenvalue from numpy import linalg as LA def get_approximation_error(exact_eigenvalue, approximated_eigenvalue): return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue) def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian): eigen_values = LA.eigvals(hamiltonian.to_matrix()) print(sorted(eigen_values)) return min(sorted(eigen_values)) def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue): exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian) print("Exact Eigenvalue:") print(exact_eigenvalue) print("\nApproximated Eigenvalue:") print(approximated_eigenvalue) print("\nApproximation Error") print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue)) plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin=3) approximated_energies = [] def insert_approximated_energy_to_list_of_all_approximated_energies(energy): approximated_energies.append(energy) import matplotlib.pyplot as plt def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin): plt.title("convergence of optimization process to the exact eigenvalue") plt.margins(0, margin) plt.plot(approximated_energies[-NUM_ITERATIONS:]) plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-') plt.grid() plt.xlabel("# of iterations") plt.ylabel("Energy") def plot_fidelity(): plt.plot(LiH_approximated_energies) plt.xlabel("# of iterations") plt.ylabel("Energy") from qiskit.opflow import X, Z, I, H, Y LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) transverse_ising_4_qubits = 0.0 * (I^I^I^I) \ + 0.8398088405253477 * (X^I^I^I) \ + 0.7989496312070936 * (I^X^I^I) \ + 0.38189710487113193 * (Z^Z^I^I) \ + 0.057753122422666725 * (I^I^X^I) \ + 0.5633292636970458 * (Z^I^Z^I) \ + 0.3152740621483513 * (I^Z^Z^I) \ + 0.07209487981989715 * (I^I^I^X) \ + 0.17892334004292654 * (Z^I^I^Z) \ + 0.2273896497668042 * (I^Z^I^Z) \ + 0.09762902934216211 * (I^I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 3 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 50 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit.opflow import X, Z, I transverse_ising_3_qubits = 0.0 * (I^I^I) \ + 0.012764169333459807 * (X^I^I) \ + 0.7691573729160869 * (I^X^I) \ + 0.398094746026449 * (Z^Z^I) \ + 0.15250261906586637 * (I^I^X) \ + 0.2094051920882264 * (Z^I^Z) \ + 0.5131291860752999 * (I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 2 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 50 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \ + 0.43305656297810435 * (X^I) \ + 0.8538597608997253 * (Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) from qiskit.opflow import X, Z, I H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
https://github.com/DuarteSerranoR/qiskit_quantum_algorithms
DuarteSerranoR
from qiskit import * from qiskit.result import * from qiskit.extensions import * from qiskit.tools.visualization import * import numpy as np pi = np.pi def BoxIsVain(n): qreg_q = QuantumRegister(2, 'q') creg_c = ClassicalRegister(2, 'c') qc = QuantumCircuit(qreg_q, creg_c) qc.reset(0) for i in range(n): qc.reset(1) qc.rx(pi/(2*n), 0) # Bomb is a CNot gate, will send the result to secundary qubit #qc.cx(0, 1) #qc.measure(0, 0) qc.measure(1, 0) # output from qubit 2 is measured # We'll run the program on a simulator backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend,memory=True) output = job.result().get_memory()[0] display(plot_histogram(job.result().get_counts(qc))) return qc, output def BoxIsBomb(n): qr = QuantumRegister(4, 'q') cr = ClassicalRegister(4, 'c') qc = QuantumCircuit(qr, cr) qc.reset(0) for i in range(n): qc.reset(1) qc.rx(pi/(2*n), 0) # Bomb is a CNot gate, will send the result to secundary qubit qc.cx(0, 1) # Or gate qc.ccx(1,2,3) qc.cx(1,3) qc.cx(2,3) #qc.measure(0, 0) qc.measure(3, 0) # output from qubit 4 is measured # We'll run the program on a simulator backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend,memory=True) output = job.result().get_memory()[0] display(plot_histogram(job.result().get_counts(qc))) return qc, output ## Test the functions n=1 print("Test with 1 iteration => [ n=1 ] :") print('\n') qc, output = BoxIsVain(n) print('Box is Vain: Number of iterations n=',n,' gives output=Succeed Vain') display(qc.draw()) print('\n') qc, output = BoxIsBomb(n) if output[3] == '0': print('Box is Bomb: Number of iterations n=',n,' gives output=Succeed Bomb') elif output[3] == '1': print('Box is Bomb: Number of iterations n=',n,' gives output=blown up') display(qc.draw()) print('\n') n=2 print("Test with 2 iterations => [ n=2 ] :") print('\n') qc, output = BoxIsVain(n) print('Box is Vain: Number of iterations n=',n,' gives output=Succeed Vain') display(qc.draw()) print('\n') qc, output = BoxIsBomb(n) if output[3] == '0': print('Box is Bomb: Number of iterations n=',n,' gives output=Succeed Bomb') elif output[3] == '1': print('Box is Bomb: Number of iterations n=',n,' gives output=blown up') display(qc.draw()) print('\n') n=500 print("Test with 500 iterations => [ n=500 ] :") print('\n') qc, output = BoxIsVain(n) print('Box is Vain: Number of iterations n=',n,' gives output=Succeed Vain') display(qc.draw()) print('\n') qc, output = BoxIsBomb(n) if output[3] == '0': print('Box is Bomb: Number of iterations n=',n,' gives output=Succeed Bomb') elif output[3] == '1': print('Box is Bomb: Number of iterations n=',n,' gives output=blown up') display(qc.draw()) print('\n')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Operator from qiskit.transpiler.passes import UnitarySynthesis circuit = QuantumCircuit(1) circuit.rx(0.8, 0) unitary = Operator(circuit).data unitary_circ = QuantumCircuit(1) unitary_circ.unitary(unitary, [0]) synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk") out = synth(unitary_circ) out.draw('mpl')
https://github.com/Axect/QuantumAlgorithms
Axect
from qiskit import QuantumCircuit,Aer, execute from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt def check_computational_basis(basis): n = int(np.log2(len(basis))) qc = QuantumCircuit(n,n) initial_state = np.array(basis) / np.linalg.norm(basis) qc.initialize(initial_state, reversed(range(n))) # Input : LSB -> MSB qc.measure(range(n), reversed(range(n))) # Readout: LSB -> MSB backend = Aer.get_backend('qasm_simulator') counts = execute(qc,backend).result().get_counts().keys() return counts def gen_bases(n): return np.eye(2**n) bases = gen_bases(3) for i in range(bases.shape[0]): basis = bases[i].tolist() print(f"basis: {basis} -> {check_computational_basis(basis)}") def convert_zbasis_to_cbasis(zbasis): """ Converts a basis state in the Z basis to the computational basis Example: Input: [0,0] -> Output: [1,0,0,0] Input: [0,1] -> Output: [0,1,0,0] Input: [1,0] -> Output: [0,0,1,0] Input: [1,1] -> Output: [0,0,0,1] """ n = 2**len(zbasis) # z basis to binary number bin_str = "".join([str(x) for x in zbasis]) num = int(bin_str,2) # binary number to computational basis cbasis = np.zeros(n) cbasis[num] = 1 return cbasis def cswap_test(x): qc = QuantumCircuit(len(x)+1, 1) input_state = convert_zbasis_to_cbasis(x) qc.initialize(input_state, reversed(range(1,len(x)+1))) qc.barrier() qc.h(0) qc.cswap(0,1,2) qc.h(0) qc.measure(0,0) backend = Aer.get_backend('qasm_simulator') return qc, execute(qc,backend).result().get_counts() qc, counts = cswap_test([0,1]) qc.draw(output='mpl', style='iqx') plot_histogram(counts) states = [ [0,0], [0,1], [1,0], [1,1] ] fig, ax = plt.subplots(1,4, figsize=(16,4)) for i, state in enumerate(states): _, counts = cswap_test(state) plot_histogram(counts, ax=ax[i]) ax[i].set_title(f"Input: {state}") plt.tight_layout() plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeManilaV2 from qiskit import transpile from qiskit.tools.visualization import plot_histogram # Get a fake backend from the fake provider backend = FakeManilaV2() # Create a simple circuit circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0,1) circuit.cx(0,2) circuit.measure_all() circuit.draw('mpl') # Transpile the ideal circuit to a circuit that can be directly executed by the backend transpiled_circuit = transpile(circuit, backend) transpiled_circuit.draw('mpl') # Run the transpiled circuit using the simulated fake backend job = backend.run(transpiled_circuit) counts = job.result().get_counts() plot_histogram(counts)
https://github.com/Slope86/QiskitExtension
Slope86
"""Module to construct, simulate, and visualize quantum circuit""" from __future__ import annotations import itertools import typing from typing import List import numpy as np from IPython.display import Latex from numpy.typing import NDArray from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, quantum_info, transpile from qiskit.visualization import plot_histogram from qiskit_aer import AerSimulator from qiskit_extension import latex_drawer from qiskit_extension.state_vector2 import StateVector2 if typing.TYPE_CHECKING: import matplotlib.figure class QuantumCircuit2(QuantumCircuit): """An extended class of QuantumCircuit from Qiskit: https://qiskit.org/documentation/stubs/qiskit.circuit.QuantumCircuit.html Args: number_of_qubits (int, optional): Number of qubits. Defaults to 1. """ def __init__(self, number_of_qubits: int = 1): # Use Aer's qasm_simulator self.simulator = AerSimulator() self.n = number_of_qubits q = QuantumRegister(self.n, "q") c = ClassicalRegister(self.n, "c") super().__init__(q, c) def to_matrix(self) -> NDArray[np.complex128]: """Return matrix form of the quantum circuit""" reverse_qc = self.reverse_bits() # REVERSE the order of qubits to fit textbook notation return quantum_info.Operator(reverse_qc).data def show_matrix(self): """Show the matrix form of the quantum circuit in LaTeX""" return latex_drawer.matrix_to_latex(self.to_matrix()) def show_circ(self) -> Latex: """Show the circuit in LaTeX""" return self.draw(output="latex", idle_wires=False) # type: ignore def show_measure_all(self) -> matplotlib.figure.Figure: """Measure every qubit at the end of the circuit, then plot the result Returns: matplotlib.figure.Figure: A histogram of the measurement result """ for i in range(self.n): self.measure(i, i) # compile the circuit down to low-level QASM instructions # supported by the backend (not needed for simple circuits) compiled_circuit = transpile(self, self.simulator) # Execute the circuit on the qasm simulator job = self.simulator.run(compiled_circuit, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(self) print(f"\nTotal count : {counts}\n") # Plot a histogram return plot_histogram(counts) def get_state(self) -> StateVector2: """Initialize the state to ground state, then evolve the state by the quantum circuit. Returns: StateVector2: Final state of the quantum circuit """ # Set the initial state of the simulator to the ground state using from_int state = StateVector2.from_int(i=0, dims=2**self.n) # Evolve the state by the quantum circuit state = state.evolve(self) return state def phase_shift(self, theta, qubit) -> None: """Phase shift gate Args: theta (_type_): phase shift angle qubit (_type_): which qubit to apply the gate """ self.p(theta, qubit) self.x(qubit) self.p(theta, qubit) self.x(qubit) def h_all(self) -> None: """Perform H gate on every qubit""" for i in range(self.n): self.h(i) def cz_line_all(self) -> None: """Perform CZ gate on qubit(0,1), qubit(1,2), qubit(2,3) ... , qubit(n-1,n)""" for i in range(self.n - 1): self.cz(i, i + 1) def cz_star_all(self, center=0) -> None: """Perform CZ gate on (center qubit, every other qubit) Args: center (int, optional): Center qubit. Defaults to 0. """ for i in range(self.n): if i == center: continue self.cz(center, i) def cz_complete(self) -> None: """Perform CZ gate on every possible combination of qubits""" for qubit_c, qubit_t in itertools.combinations(range(self.n), 2): self.cz(qubit_c, qubit_t) def z2epr_pair(self, qubit_c: List[int] | int, qubit_t: List[int] | int) -> None: """Perform Z to EPR pair transformation Args: qubit_c (List[int] | int): control qubit qubit_t (List[int] | int): target qubit """ if isinstance(qubit_c, int) and isinstance(qubit_t, int): qubit_c, qubit_t = [qubit_c], [qubit_t] if isinstance(qubit_c, list) and isinstance(qubit_t, list): if len(qubit_c) != len(qubit_t): raise ValueError("qubit_c and qubit_t must have the same length") for c, t in zip(qubit_c, qubit_t): self.h(c) self.cx(c, t) else: raise TypeError("qubit_c and qubit_t must be List[int] or int") def epr2z_basis(self, qubit_c: List[int] | int, qubit_t: List[int] | int) -> None: """Perform EPR pair to Z basis transformation Args: qubit_c (List[int] | int): control qubit qubit_t (List[int] | int): target qubit """ if isinstance(qubit_c, int) and isinstance(qubit_t, int): qubit_c, qubit_t = [qubit_c], [qubit_t] if isinstance(qubit_c, list) and isinstance(qubit_t, list): if len(qubit_c) != len(qubit_t): raise ValueError("qubit_c and qubit_t must have the same length") for c, t in zip(qubit_c, qubit_t): self.cx(c, t) self.h(c) else: raise TypeError("qubit_c and qubit_t must both be List[int] or both be int")
https://github.com/ashishpatel26/IBM-Quantum-Challenge-Africa-2021
ashishpatel26
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, execute from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.providers.aer import QasmSimulator backend = Aer.get_backend('statevector_simulator') qc1 = QuantumCircuit(4) # perform gate operations on individual qubits qc1.x(0) qc1.y(1) qc1.z(2) qc1.s(3) # Draw circuit qc1.draw() # Plot blochshere out1 = execute(qc1,backend).result().get_statevector() plot_bloch_multivector(out1) qc2 = QuantumCircuit(4) # initialize qubits qc2.x(range(4)) # perform gate operations on individual qubits qc2.x(0) qc2.y(1) qc2.z(2) qc2.s(3) # Draw circuit qc2.draw() # Plot blochshere out2 = execute(qc2,backend).result().get_statevector() plot_bloch_multivector(out2) qc3 = QuantumCircuit(4) # initialize qubits qc3.h(range(4)) # perform gate operations on individual qubits qc3.x(0) qc3.y(1) qc3.z(2) qc3.s(3) # Draw circuit qc3.draw() # Plot blochshere out3 = execute(qc3,backend).result().get_statevector() plot_bloch_multivector(out3) qc4 = QuantumCircuit(4) # initialize qubits qc4.x(range(4)) qc4.h(range(4)) # perform gate operations on individual qubits qc4.x(0) qc4.y(1) qc4.z(2) qc4.s(3) # Draw circuit qc4.draw() # Plot blochshere out4 = execute(qc4,backend).result().get_statevector() plot_bloch_multivector(out4) qc5 = QuantumCircuit(4) # initialize qubits qc5.h(range(4)) qc5.s(range(4)) # perform gate operations on individual qubits qc5.x(0) qc5.y(1) qc5.z(2) qc5.s(3) # Draw circuit qc5.draw() # Plot blochshere out5 = execute(qc5,backend).result().get_statevector() plot_bloch_multivector(out5) qc6 = QuantumCircuit(4) # initialize qubits qc6.x(range(4)) qc6.h(range(4)) qc6.s(range(4)) # perform gate operations on individual qubits qc6.x(0) qc6.y(1) qc6.z(2) qc6.s(3) # Draw circuit qc6.draw() # Plot blochshere out6 = execute(qc6,backend).result().get_statevector() plot_bloch_multivector(out6) import qiskit qiskit.__qiskit_version__
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
def qc_alice_encoding(cb): from qiskit import QuantumCircuit qc = QuantumCircuit(1, name='AE') if cb == '00': qc.id(0) elif cb == '01': qc.x(0) elif cb == '10': qc.z(0) elif cb == '11': qc.x(0); qc.z(0) return qc cb = '11' qcae = qc_alice_encoding(cb) qcae.draw('mpl') from qiskit import QuantumCircuit # só pra mostrar o circuito quântico qc = QuantumCircuit(2,2) qc.h(0) qc.cx(0,1) qc.barrier() qcae = qc_alice_encoding(cb) qc.append(qcae, [0]) qc.barrier() qc.cx(0,1) qc.h(0) qc.measure([0,1],[0,1]) qc.draw('mpl') def qc_dense_coding(cb): from qiskit import QuantumCircuit qc = QuantumCircuit(2, name='DC') qc.h(0); qc.cx(0,1) # compartilha o par emaranhado qcae = qc_alice_encoding(cb); qc.append(qcae, [0]) # codificação da Alice qc.cx(0,1); qc.h(0)#; qc.measure([0,1],[0,1]) # decodificação, medida na BB, do Bob # OBS. Não consegui incluir um subcircuito que contenha medidas return qc from qiskit import QuantumCircuit qc = QuantumCircuit(2,2) qcdc = qc_dense_coding('00') qc.append(qcdc, [0,1]) qc.draw('mpl') from qiskit import Aer, execute, QuantumCircuit; simulator = Aer.get_backend('qasm_simulator') nshots = 2**13; from qiskit import QuantumCircuit qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('00'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram; plot_histogram(counts) from qiskit import Aer, execute, QuantumCircuit simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 from qiskit import QuantumCircuit qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('01'); qc.append(qcdc, [0,1]) qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) from qiskit import Aer, execute, QuantumCircuit simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 from qiskit import QuantumCircuit qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('10'); qc.append(qcdc, [0,1]) qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) from qiskit import Aer, execute, QuantumCircuit simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 from qiskit import QuantumCircuit qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('11'); qc.append(qcdc, [0,1]) qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) import qiskit qiskit.IBMQ.save_account('72f5d1e3769658b4908c384492eb3a9bd6d6ac4ab1fdf613d7fbe72884114d62728d6fd60a8bf8d0b6698f2f5463a605742658fee1ce3318181105c6acb8120e', overwrite = True) qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') from qiskit import QuantumCircuit, execute device = provider.get_backend('ibm_nairobi') nshots = 2**13 qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('00'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmj6f1m0t6t00085y6r0') from qiskit.tools.visualization import plot_histogram; plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit, execute device = provider.get_backend('ibm_nairobi') nshots = 2**13 qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('01'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmj6f7c0t6t00085y6rg') plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit, execute device = provider.get_backend('ibm_nairobi') nshots = 2**13 qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('10'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmj6f9nstv5g008dwdb0') plot_histogram(job.result().get_counts()) #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') from qiskit import QuantumCircuit, execute; device = provider.get_backend('ibm_nairobi'); nshots = 2**13 qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('11'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmj6g3g0t6t00085y6sg') plot_histogram(job.result().get_counts()) import qiskit qiskit.IBMQ.save_account('e20d3045c7c23a3be753606794714e9b47d4331ec46a41b2281e2d601bae27b2b3c1baa0b5cb54f3282a8b5248e552b14c9c556699010660fb94b11d00ff1073', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 from qiskit import QuantumRegister, execute from qiskit.ignis.mitigation.measurement import complete_meas_cal qr_ = QuantumRegister(2) qubit_list_ = [0, 1] # qubits para os quais aplicaremos calibracao de medidas meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list_, qr = qr_) meas_calibs # circuitos que serão executados para mitigação dos erros state_labels # estados que serão preparados/medidos/corrigidos job = execute(meas_calibs, backend=device, shots=nshots) print(job.job_id()) from qiskit.ignis.mitigation.measurement import CompleteMeasFitter job = device.retrieve_job('cmm4vmyrcq000080ceqg') cal_results = job.result() # função que usaremos para corrigir resultados experimentais meas_fitter = CompleteMeasFitter(cal_results, state_labels) # OBS. Uma vez feito isso para um chip e para uns certos qubits, depois é só usar job = device.retrieve_job('cmj6f1m0t6t00085y6r0') # dados do experimento da codificação densa para '00' unmitigated_counts = job.result().get_counts() mitigated_results = meas_fitter.filter.apply(job.result()) # corrige os resultados usando mitigação mitigated_counts = mitigated_results.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit']) def prob_erro(counts, target, nshots): # Calcula a probabilidade de erro if target in counts: pacerto = counts[target]/nshots perro = 1 - pacerto return perro print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '00', nshots)) print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '00',nshots)) job = device.retrieve_job('cmj6f7c0t6t00085y6rg') # dados do experimento da codificação densa para '01' unmitigated_counts = job.result().get_counts() mitigated_results = meas_fitter.filter.apply(job.result()) # corrige os resultados usando mitigação mitigated_counts = mitigated_results.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit']) print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '10', nshots)) print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '10',nshots)) job = device.retrieve_job('cmj6f9nstv5g008dwdb0'); unmitigated_counts = job.result().get_counts() mitigated_results = meas_fitter.filter.apply(job.result()) # corrige os resultados usando mitigação mitigated_counts = mitigated_results.get_counts(); from qiskit.tools.visualization import plot_histogram plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit']) print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '01', nshots)) print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '01',nshots)) job = device.retrieve_job('cmj6g3g0t6t00085y6sg') # dados do experimento da codificação densa para '11' unmitigated_counts = job.result().get_counts(); mitigated_results = meas_fitter.filter.apply(job.result()) mitigated_counts = mitigated_results.get_counts(); from qiskit.tools.visualization import plot_histogram plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit']) print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '11', nshots)) print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '11',nshots)) def qc_Eswap(): from qiskit import QuantumCircuit qc = QuantumCircuit(4, name='Eswap') qc.h([0,3]); qc.cx(0,1); qc.cx(3,2) # cria os pares emaranhados qc.barrier() qc.cx(1,2); qc.h(1) # muda da base computacional para a base de Bell qc.barrier() qc.cx(2,3); qc.cz(1,3) # envia a informação 'clássica' return qc qces = qc_Eswap(); qces.draw('mpl') from qiskit import Aer, QuantumCircuit; import qiskit from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.visualization import plot_state_city simulator = Aer.get_backend('qasm_simulator'); qc = QuantumCircuit(4); qces = qc_Eswap(); qc.append(qces, [0,1,2,3]) qstc = state_tomography_circuits(qc, [0,3]); job = execute(qstc, backend=simulator, shots=nshots) qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq'); plot_state_city(rho) from qiskit.quantum_info import state_fidelity F = state_fidelity(rho,Phip); print('F = ',F) import qiskit qiskit.IBMQ.save_account('72f5d1e3769658b4908c384492eb3a9bd6d6ac4ab1fdf613d7fbe72884114d62728d6fd60a8bf8d0b6698f2f5463a605742658fee1ce3318181105c6acb8120e', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 from qiskit import QuantumCircuit, execute qc = QuantumCircuit(4); qces = qc_Eswap(); qc.append(qces, [0,1,2,3]) qstc = state_tomography_circuits(qc, [0,3]) job = execute(qstc, backend=device, shots=nshots) jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmjp9zf5mym0008dvmzg') qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq') from qiskit.visualization import plot_state_city; plot_state_city(rho) rho import math; import numpy as np Phip = np.array([1/math.sqrt(2),0,0,1/math.sqrt(2)]); Phip from qiskit.quantum_info import state_fidelity F = state_fidelity(rho,Phip); print('F = ',F) import qiskit qiskit.IBMQ.save_account('dabd4674f7b3794f740813fec0c5478bfefdebb7d1dca9b7acd41e3f90ed2c8a8b80af26fb3236289fbfc70d0ea334829a836453ac46f96fee68abcb22495ef4', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 from qiskit import QuantumRegister, execute from qiskit.ignis.mitigation.measurement import complete_meas_cal qr = QuantumRegister(4) qubit_list = [0, 3] meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = execute(meas_calibs, backend=device, shots=nshots) print(job.job_id()) from qiskit.ignis.mitigation.measurement import CompleteMeasFitter job = device.retrieve_job('cmr2snercp70008sfsw0') cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels) from qiskit import QuantumCircuit, execute qc = QuantumCircuit(4); qces = qc_Eswap(); qc.append(qces, [0,1,2,3]) from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter qstc = state_tomography_circuits(qc, [0,3]) job = device.retrieve_job('cmjp9zf5mym0008dvmzg') mitigated_results = meas_fitter.filter.apply(job.result()) qstf = StateTomographyFitter(mitigated_results, qstc) rho = qstf.fit(method='lstsq') from qiskit.visualization import plot_state_city; plot_state_city(rho) import numpy as np import math from qiskit.quantum_info import state_fidelity Phip = np.array([1/math.sqrt(2),0,0,1/math.sqrt(2)]) F = state_fidelity(rho,Phip) print('F = ',F)
https://github.com/Qiskit/feedback
Qiskit
from qiskit.quantum_info.operators import SparsePauliOp H2_op = SparsePauliOp( ["II", "IZ", "ZI", "ZZ", "XX"], coeffs=[ -1.052373245772859, 0.39793742484318045, -0.39793742484318045, -0.01128010425623538, 0.18093119978423156, ], ) aux_op1 = SparsePauliOp(["ZZ"], coeffs=[2.0]) aux_op2 = SparsePauliOp(["XX"], coeffs=[-2.0]) from IPython.display import clear_output import matplotlib.pyplot as plt counts = [] values = [] def plot_energy(eval_count, parameters, mean, metadata): counts.append(eval_count) values.append(mean) clear_output(wait=True) plt.plot(counts, values) plt.xlabel("Evaluation count") plt.ylabel("Energy") plt.title("Energy convergence") plt.show() from qiskit.circuit.library import TwoLocal from qiskit.primitives import Estimator from qiskit.algorithms.minimum_eigensolvers import VQE, VQEResult from qiskit.algorithms.optimizers import SLSQP # Reset plotting arrays. counts.clear() values.clear() # Define the central primitive. estimator = Estimator() # Define our ansatz ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") slsqp = SLSQP() # Instantiate VQE. Note that all arguments after the optimizer must be specified by keyword. vqe = VQE(estimator, ansatz, slsqp, callback=plot_energy) # Compute the minimum eigenvalue. Not the primary operator is the H2_op. The auxillary operators are just variants for illustration. # Note that None values are no longer supported. Zero values will be interpreted as a zero operator. result = vqe.compute_minimum_eigenvalue(H2_op, [aux_op1, aux_op2, 0]) print(result) # Reset plotting arrays. counts.clear() values.clear() result = vqe.compute_minimum_eigenvalue(H2_op, {"aux_op1": aux_op1, "aux_op2": aux_op2}) print(result) from IPython.display import clear_output import matplotlib.pyplot as plt import numpy as np counts = [] values = [] std_dev = [] def plot_energy_error(eval_count, parameters, mean, metadata): counts.append(eval_count) values.append(mean) variance = metadata.get("variance", 0.0) shots = metadata.get("shots", 0.0) std_dev.append(np.sqrt(variance / shots) if shots > 0 else 0.0) clear_output(wait=True) plt.errorbar(counts, values, std_dev) plt.xlabel("Evaluation count") plt.ylabel("Energy") plt.title("Energy convergence") plt.show() counts.clear() values.clear() from qiskit.algorithms.optimizers import COBYLA cobyla = COBYLA(maxiter=1000) estimator = Estimator(options={"shots": 1024}) vqe = VQE(estimator, ansatz, cobyla, callback=plot_energy_error) result = vqe.compute_minimum_eigenvalue(H2_op, [aux_op1, aux_op2]) print(result) counts.clear() values.clear() from qiskit.algorithms.gradients import FiniteDiffEstimatorGradient estimator = Estimator() gradient = FiniteDiffEstimatorGradient(estimator, epsilon=0.001) vqe = VQE(estimator, ansatz, slsqp, gradient=gradient, callback=plot_energy) result = vqe.compute_minimum_eigenvalue(H2_op, [H2_op ** 2, H2_op / 2]) print(result) counts.clear() values.clear() from qiskit.algorithms.gradients import ParamShiftEstimatorGradient from qiskit.algorithms.optimizers import GradientDescent estimator = Estimator() gradient = FiniteDiffEstimatorGradient(estimator, epsilon=0.001) vqe = VQE(estimator, ansatz, GradientDescent(maxiter=200, learning_rate=0.1), gradient=ParamShiftEstimatorGradient(estimator), ) result = vqe.compute_minimum_eigenvalue(H2_op, [H2_op ** 2, H2_op / 2]) print(result) from qiskit.circuit.library import TwoLocal from qiskit.primitives import Sampler from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.algorithms.optimizers import SLSQP # Reset plotting arrays. counts.clear() values.clear() # Define the central primitive. sampler = Sampler() # Instantiate SamplingVQE. Note that all arguments after the optimizer must be specified by keyword. sampling_vqe = SamplingVQE(sampler, ansatz, slsqp, callback=plot_energy) result = sampling_vqe.compute_minimum_eigenvalue(H2_op) # Reset plotting arrays. counts.clear() values.clear() diag_op = SparsePauliOp(["ZZ", "IZ", "II"], coeffs=[1, -0.5, 0.12]) sampler = Sampler() from qiskit.circuit.library import RealAmplitudes sampling_vqe = SamplingVQE( sampler, RealAmplitudes(2, reps=1), SLSQP(), aggregation=0.1, callback=plot_energy, ) sampling_vqe.compute_minimum_eigenvalue(operator=diag_op)
https://github.com/MansourZarrin/A-Simple-Guide-to-Quantum-Approaches-for-Solving-Max-Cut
MansourZarrin
# Import libraries import numpy as np import networkx as nx import matplotlib.pyplot as plt from qiskit import QuantumCircuit, Aer, execute import warnings # Step 1: Define the problem and setup num_vertices = 20 # Number of vertices in the graph edge_probability = 0.5 # Probability of creating an edge between any two vertices shots = 1000 # Number of shots for quantum circuit execution # Step 2: Generate a random graph using NetworkX def generate_random_graph(num_vertices, edge_probability): """ Generate a random graph using NetworkX. Parameters: num_vertices (int): Number of vertices in the graph. edge_probability (float): Probability of creating an edge between any two vertices. Returns: np.array: Adjacency matrix of the generated graph. """ with warnings.catch_warnings(): warnings.simplefilter("ignore") graph = nx.erdos_renyi_graph(num_vertices, edge_probability) return nx.adjacency_matrix(graph).toarray() # Step 3: Implement quantum walk on graph def quantum_walk(graph): """ Implement a quantum walk on a graph. Parameters: graph (np.array): Adjacency matrix representing the graph. Returns: dict: Dictionary containing counts of measurement outcomes. """ num_vertices = len(graph) qc = QuantumCircuit(num_vertices) for i in range(num_vertices): qc.h(i) for i in range(num_vertices): for j in range(i+1, num_vertices): if graph[i][j] == 1: qc.cp(np.pi, i, j) qc.measure_all() simulator = Aer.get_backend('qasm_simulator') result = execute(qc, simulator, shots=shots).result() counts = result.get_counts(qc) return counts # Step 4: Quantum Approximation Algorithm (Max-Cut) def max_cut_approximation(graph, counts): """ Implement the Quantum Approximation Algorithm (Max-Cut). Parameters: graph (np.array): Adjacency matrix representing the graph. counts (dict): Dictionary containing counts of measurement outcomes. Returns: tuple: Tuple containing the max cut size and the partition string. """ max_cut = 0 partition = None for partition_string in counts.keys(): cut = 0 for i in range(len(partition_string)): for j in range(i+1, len(partition_string)): if partition_string[i] != partition_string[j] and graph[i][j] == 1: cut += 1 if cut > max_cut: max_cut = cut partition = partition_string return max_cut, partition # Step 5: Decode the partitioning and visualize the resulting graph with cut def decode_partition(graph, partition): """ Decode the partitioning and visualize the resulting graph with the cut. Parameters: graph (np.array): Adjacency matrix representing the graph. partition (str): String representing the partition of the vertices. Returns: None """ G = nx.from_numpy_array(graph) colors = ['skyblue', 'salmon'] node_colors = [colors[int(partition[node])] for node in G.nodes()] # Identify edges crossing the partition cut_edges = [(u, v) for u, v in G.edges() if partition[u] != partition[v]] # Draw graph with nodes colored based on partition and cut edges highlighted pos = nx.spring_layout(G) # Positions for all nodes nx.draw(G, pos, with_labels=True, node_color=node_colors, node_size=1000, font_size=12) nx.draw_networkx_edges(G, pos, edgelist=cut_edges, width=2, alpha=0.5, edge_color='red') # Draw cut edges plt.title("Resulted Partitioned Graph with Cut") plt.show() # Execute the steps # Generate random graph graph = generate_random_graph(num_vertices, edge_probability) # Implement quantum walk counts = quantum_walk(graph) # Find max-cut approximation max_cut, partition = max_cut_approximation(graph, counts) print("Max-Cut:", max_cut) print(f"The value {max_cut} indicates the maximum number of edges that can be cut by partitioning the vertices into two sets.") print(f"In other words, if we divide the vertices into two groups according to the partition obtained, we can cut a maximum of {max_cut} edges between these two groups.") print() print("Partition:", partition) print(f"The binary string {partition} represents the partitioning of vertices.") print(f"Each digit in the string corresponds to a vertex in the graph.") print(f"In this case, there are {num_vertices} vertices, so the binary string has {num_vertices} digits.") print("The value '1' indicates that the corresponding vertex belongs to one set (Partition 1), and the value '0' indicates that the vertex belongs to the other set (Partition 0).") # Decode partition and visualize resulting graph decode_partition(graph, partition)
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
alejomonbar
%load_ext autoreload %autoreload 2 #!pip install pennylane #improt pennylane dependnecies import pennylane as qml from pennylane import numpy as np from pennylane.optimize import NesterovMomentumOptimizer # load the csv files import pandas as pd # plot the historical acc and cost import matplotlib.pyplot as plt import seaborn as sns from IPython.display import clear_output clear_output(wait=False) import os data_train = pd.read_csv("dataset/fair_train.csv") X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values data_test = pd.read_csv("dataset/classic_test.csv") X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values (X_train.shape, y_train.shape),(X_test.shape, y_test.shape) dev = qml.device("default.qubit", wires=4) def layer_1(W): qml.RY(W[0], wires=0) qml.RY(W[1], wires=1) qml.RY(W[2], wires=2) qml.RY(W[3], wires=3) qml.Hadamard(wires=0) qml.Hadamard(wires=1) qml.Hadamard(wires=2) qml.Hadamard(wires=3) qml.RZ(W[4], wires=0) qml.RZ(W[5], wires=1) qml.RZ(W[6], wires=2) qml.RZ(W[7], wires=3) qml.CNOT(wires=[1,0]) qml.RY(W[8], wires=1) qml.CNOT(wires=[2,0]) qml.RY(W[9], wires=2) qml.CNOT(wires=[3,0]) qml.RY(W[10], wires=3) qml.CNOT(wires=[2,1]) qml.RY(W[11], wires=2) qml.CNOT(wires=[3,1]) qml.RY(W[12], wires=3) # qml.Hadamard(wires=0) # qml.Hadamard(wires=1) # qml.Hadamard(wires=2) # qml.Hadamard(wires=3) #qml.CNOT(wires=[1,0]) #qml.CNOT(wires=[2,0]) #qml.CNOT(wires=[3,0]) def block(weights, wires): qml.CNOT(wires=[wires[0],wires[1]]) qml.RY(weights[0], wires=wires[0]) qml.RY(weights[1], wires=wires[1]) n_wires = 4 n_block_wires = 2 n_params_block = 2 n_blocks = qml.MPS.get_n_blocks(range(n_wires),n_block_wires) n_blocks @qml.qnode(dev) def circuit(weights, x): #statepreparation(x) qml.AmplitudeEmbedding(x, wires=[0,1,2,3],normalize=True,pad_with=True) #for i in range(4): #qml.Hadamard(wires=i) #qml.RY(x[i], wires=i) #qml.Hadamard(wires=i) #qml.RX(x[i+4], wires=i) #qml.RX(x[i+8], wires=i) #qml.CNOT(wires=[0,1]) #qml.CNOT(wires=[1,2]) #qml.CNOT(wires=[2,3]) #qml.CNOT(wires=[3,0]) #qml.CNOT(wires=[4,0]) #qml.CNOT(wires=[0,1]) #qml.CNOT(wires=[1,2]) #qml.CNOT(wires=[2,3]) #qml.CNOT(wires=[3,0]) for w in weights: #layer_1(w[:13]) #layer_2(w[12:21]) #layer_2(w[16:24]) #layer_3(w[21:]) qml.MPS(range(n_wires),n_block_wires,block, n_params_block, w) #print(w) #print(x) return qml.expval(qml.PauliZ(3)) def variational_classifier(weights, bias, x): return circuit(weights, x) + bias def square_loss(labels, predictions): loss = 0 for l, p in zip(labels, predictions): loss = loss + (l - p) ** 2 loss = loss / len(labels) return loss def accuracy(labels, predictions): loss = 0 for l, p in zip(labels, predictions): if abs(l - p) < 1e-5: loss = loss + 1 loss = loss / len(labels) return loss def cost(weights, bias, X, Y): #print(1) predictions = [variational_classifier(weights, bias, x) for x in X] return square_loss(Y, predictions) np.random.seed(0) num_layers = 2 weights_init = 2*np.pi * np.random.randn(num_layers,3, 2, requires_grad=True) bias_init = np.array(0.0, requires_grad=True) print(weights_init, bias_init) print(qml.draw(circuit,expansion_strategy='device',wire_order=[0,1,2,3,4,5,6,7])(weights_init,np.asarray(X_train[0]))) for i in weights_init: print(i[0]) y_train = np.where(y_train < 1, -1, y_train) y_test = np.where(y_test < 1, -1, y_test) from sklearn.utils import shuffle X,y = shuffle(X_train, y_train, random_state=0) from sklearn.model_selection import train_test_split opt = NesterovMomentumOptimizer(0.4) batch_size = 32 num_data = len(y_train) num_train = 0.9 # train the variational classifier weights = weights_init bias = bias_init print() cost_g = [] acc_train = [] acc_test = [] plt.show() for it in range(50): X_train_70, X_test_30, y_train_70, y_test_30 =train_test_split(np.asarray(X), np.asarray(y), train_size=num_train, test_size=1.0-num_train, shuffle=True) # Update the weights by one optimizer step batch_index = np.random.randint(0, len(X_train_70), (batch_size,)) feats_train_batch = X_train_70[batch_index] Y_train_batch = y_train_70[batch_index] weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch) # Compute predictions on train and validation set predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in X_train_70] predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in X_test_30] # Compute accuracy on train and validation set acc_tra = accuracy(y_train_70, predictions_train) acc_val = accuracy(y_test_30, predictions_val) cost_train = cost(weights, bias,X_train, y_train) cost_g.append(cost_train) acc_train.append(acc_tra) acc_test.append(acc_val) clear_output(wait=True) plt.plot(cost_g,label='cost') plt.plot(acc_train,label='acc_train') plt.plot(acc_test,label='acc_test') plt.legend(['cost','acc_train','acc_test']) plt.show() print( "Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} " "".format(it + 1, cost_train, acc_tra, acc_val) ) print(weights) x_test = [] for x in X_test.tolist(): if sum(x) == 0: x[0]=1 x_test.append( x/ np.linalg.norm(x)) x_test[0] y_pred = [np.sign(variational_classifier(weights, bias, f)) for f in x_test] y_test_pred = [] for i in y_pred: if i < 0: y_test_pred.append(-1) else: y_test_pred.append(1) from sklearn.metrics import confusion_matrix, roc_curve, auc from sklearn.preprocessing import StandardScaler # demonstration of calculating metrics for a neural network model using sklearn from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score from sklearn.metrics import cohen_kappa_score from sklearn.metrics import roc_auc_score accuracy = accuracy_score(y_test, y_test_pred) print('Accuracy: %f' % accuracy) # precision tp / (tp + fp) precision = precision_score(y_test, y_test_pred) print('Precision: %f' % precision) # recall: tp / (tp + fn) recall = recall_score(y_test, y_test_pred) print('Recall: %f' % recall) # f1: 2 tp / (2 tp + fp + fn) f1 = f1_score(y_test, y_test_pred) print('F1 score: %f' % f1) # kappa kappa = cohen_kappa_score(y_test, y_test_pred) print('Cohens kappa: %f' % kappa) # ROC AUC auc = roc_auc_score(y_test, y_test_pred) print('ROC AUC: %f' % auc) # confusion matrix test_matrix = confusion_matrix(y_test, y_test_pred) print(test_matrix) ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g') ax.set_title('Seaborn Confusion Matrix with labels\n\n'); ax.set_xlabel('\nPredicted Values') ax.set_ylabel('Actual Values '); ax.xaxis.set_ticklabels(['0','1']) ax.yaxis.set_ticklabels(['0','1']) ## Display the visualization of the Confusion Matrix. plt.show() y_pred_1 = [int(i) for i in y_pred ] y_pred_1 = ["{}\n".format(i) for i in y_pred_1] with open(r'mps_2_layers.csv', 'w') as fp: fp.writelines(y_pred_1)
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Visualization function for a pass manager. Passes are grouped based on their flow controller, and coloured based on the type of pass. """ import os import inspect import tempfile from qiskit.utils import optionals as _optionals from qiskit.transpiler.basepasses import AnalysisPass, TransformationPass from .exceptions import VisualizationError DEFAULT_STYLE = {AnalysisPass: "red", TransformationPass: "blue"} @_optionals.HAS_GRAPHVIZ.require_in_call @_optionals.HAS_PYDOT.require_in_call def pass_manager_drawer(pass_manager, filename=None, style=None, raw=False): """ Draws the pass manager. This function needs `pydot <https://github.com/erocarrera/pydot>`__, which in turn needs `Graphviz <https://www.graphviz.org/>`__ to be installed. Args: pass_manager (PassManager): the pass manager to be drawn filename (str): file path to save image to style (dict or OrderedDict): keys are the pass classes and the values are the colors to make them. An example can be seen in the DEFAULT_STYLE. An ordered dict can be used to ensure a priority coloring when pass falls into multiple categories. Any values not included in the provided dict will be filled in from the default dict raw (Bool) : True if you want to save the raw Dot output not an image. The default is False. Returns: PIL.Image or None: an in-memory representation of the pass manager. Or None if no image was generated or PIL is not installed. Raises: MissingOptionalLibraryError: when nxpd or pydot not installed. VisualizationError: If raw=True and filename=None. Example: .. code-block:: %matplotlib inline from qiskit import QuantumCircuit from qiskit.compiler import transpile from qiskit.transpiler import PassManager from qiskit.visualization import pass_manager_drawer from qiskit.transpiler.passes import Unroller circ = QuantumCircuit(3) circ.ccx(0, 1, 2) circ.draw() pass_ = Unroller(['u1', 'u2', 'u3', 'cx']) pm = PassManager(pass_) new_circ = pm.run(circ) new_circ.draw(output='mpl') pass_manager_drawer(pm, "passmanager.jpg") """ import pydot passes = pass_manager.passes() if not style: style = DEFAULT_STYLE # create the overall graph graph = pydot.Dot() # identifiers for nodes need to be unique, so assign an id # can't just use python's id in case the exact same pass was # appended more than once component_id = 0 prev_node = None for index, controller_group in enumerate(passes): subgraph, component_id, prev_node = draw_subgraph( controller_group, component_id, style, prev_node, index ) graph.add_subgraph(subgraph) output = make_output(graph, raw, filename) return output def _get_node_color(pss, style): # look in the user provided dict first for typ, color in style.items(): if isinstance(pss, typ): return color # failing that, look in the default for typ, color in DEFAULT_STYLE.items(): if isinstance(pss, typ): return color return "black" @_optionals.HAS_GRAPHVIZ.require_in_call @_optionals.HAS_PYDOT.require_in_call def staged_pass_manager_drawer(pass_manager, filename=None, style=None, raw=False): """ Draws the staged pass manager. This function needs `pydot <https://github.com/erocarrera/pydot>`__, which in turn needs `Graphviz <https://www.graphviz.org/>`__ to be installed. Args: pass_manager (StagedPassManager): the staged pass manager to be drawn filename (str): file path to save image to style (dict or OrderedDict): keys are the pass classes and the values are the colors to make them. An example can be seen in the DEFAULT_STYLE. An ordered dict can be used to ensure a priority coloring when pass falls into multiple categories. Any values not included in the provided dict will be filled in from the default dict raw (Bool) : True if you want to save the raw Dot output not an image. The default is False. Returns: PIL.Image or None: an in-memory representation of the pass manager. Or None if no image was generated or PIL is not installed. Raises: MissingOptionalLibraryError: when nxpd or pydot not installed. VisualizationError: If raw=True and filename=None. Example: .. code-block:: %matplotlib inline from qiskit.providers.fake_provider import FakeLagosV2 from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager pass_manager = generate_preset_pass_manager(3, FakeLagosV2()) pass_manager.draw() """ import pydot # only include stages that have passes stages = list(filter(lambda s: s is not None, pass_manager.expanded_stages)) if not style: style = DEFAULT_STYLE # create the overall graph graph = pydot.Dot() # identifiers for nodes need to be unique, so assign an id # can't just use python's id in case the exact same pass was # appended more than once component_id = 0 # keep a running count of indexes across stages idx = 0 prev_node = None for st in stages: stage = getattr(pass_manager, st) if stage is not None: passes = stage.passes() stagegraph = pydot.Cluster(str(st), label=str(st), fontname="helvetica", labeljust="l") for controller_group in passes: subgraph, component_id, prev_node = draw_subgraph( controller_group, component_id, style, prev_node, idx ) stagegraph.add_subgraph(subgraph) idx += 1 graph.add_subgraph(stagegraph) output = make_output(graph, raw, filename) return output def draw_subgraph(controller_group, component_id, style, prev_node, idx): """Draw subgraph.""" import pydot # label is the name of the flow controller parameter label = "[{}] {}".format(idx, ", ".join(controller_group["flow_controllers"])) # create the subgraph for this controller subgraph = pydot.Cluster(str(component_id), label=label, fontname="helvetica", labeljust="l") component_id += 1 for pass_ in controller_group["passes"]: # label is the name of the pass node = pydot.Node( str(component_id), label=str(type(pass_).__name__), color=_get_node_color(pass_, style), shape="rectangle", fontname="helvetica", ) subgraph.add_node(node) component_id += 1 # the arguments that were provided to the pass when it was created arg_spec = inspect.getfullargspec(pass_.__init__) # 0 is the args, 1: to remove the self arg args = arg_spec[0][1:] num_optional = len(arg_spec[3]) if arg_spec[3] else 0 # add in the inputs to the pass for arg_index, arg in enumerate(args): nd_style = "solid" # any optional args are dashed # the num of optional counts from the end towards the start of the list if arg_index >= (len(args) - num_optional): nd_style = "dashed" input_node = pydot.Node( component_id, label=arg, color="black", shape="ellipse", fontsize=10, style=nd_style, fontname="helvetica", ) subgraph.add_node(input_node) component_id += 1 subgraph.add_edge(pydot.Edge(input_node, node)) # if there is a previous node, add an edge between them if prev_node: subgraph.add_edge(pydot.Edge(prev_node, node)) prev_node = node return subgraph, component_id, prev_node def make_output(graph, raw, filename): """Produce output for pass_manager.""" if raw: if filename: graph.write(filename, format="raw") return None else: raise VisualizationError("if format=raw, then a filename is required.") if not _optionals.HAS_PIL and filename: # pylint says this isn't a method - it is graph.write_png(filename) return None _optionals.HAS_PIL.require_now("pass manager drawer") with tempfile.TemporaryDirectory() as tmpdirname: from PIL import Image tmppath = os.path.join(tmpdirname, "pass_manager.png") # pylint says this isn't a method - it is graph.write_png(tmppath) image = Image.open(tmppath) os.remove(tmppath) if filename: image.save(filename, "PNG") return image
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.mappers import ParityMapper from qiskit_nature.second_q.properties import ParticleNumber from qiskit_nature.second_q.transformers import ActiveSpaceTransformer bond_distance = 2.5 # in Angstrom # specify driver driver = PySCFDriver( atom=f"Li 0 0 0; H 0 0 {bond_distance}", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() # specify active space transformation active_space_trafo = ActiveSpaceTransformer( num_electrons=problem.num_particles, num_spatial_orbitals=3 ) # transform the electronic structure problem problem = active_space_trafo.transform(problem) # construct the parity mapper with 2-qubit reduction qubit_mapper = ParityMapper(num_particles=problem.num_particles) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms.ground_state_solvers import GroundStateEigensolver np_solver = NumPyMinimumEigensolver() np_groundstate_solver = GroundStateEigensolver(qubit_mapper, np_solver) np_result = np_groundstate_solver.solve(problem) target_energy = np_result.total_energies[0] print(np_result) from qiskit.circuit.library import EfficientSU2 ansatz = EfficientSU2(num_qubits=4, reps=1, entanglement="linear", insert_barriers=True) ansatz.decompose().draw("mpl", style="iqx") import numpy as np from qiskit.utils import algorithm_globals # fix random seeds for reproducibility np.random.seed(5) algorithm_globals.random_seed = 5 from qiskit.algorithms.optimizers import SPSA optimizer = SPSA(maxiter=100) initial_point = np.random.random(ansatz.num_parameters) from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.primitives import Estimator estimator = Estimator() local_vqe = VQE( estimator, ansatz, optimizer, initial_point=initial_point, ) local_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, local_vqe) local_vqe_result = local_vqe_groundstate_solver.solve(problem) print(local_vqe_result) from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(group="open") # replace by your runtime provider backend = provider.get_backend("ibmq_qasm_simulator") # select a backend that supports the runtime from qiskit_nature.runtime import VQEClient runtime_vqe = VQEClient( ansatz=ansatz, optimizer=optimizer, initial_point=initial_point, provider=provider, backend=backend, shots=1024, measurement_error_mitigation=True, ) # use a complete measurement fitter for error mitigation runtime_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, runtime_vqe) runtime_vqe_result = runtime_vqe_groundstate_solver.solve(problem) print(runtime_vqe_result) runtime_result = runtime_vqe_result.raw_result history = runtime_result.optimizer_history loss = history["energy"] import matplotlib.pyplot as plt plt.rcParams["font.size"] = 14 # plot loss and reference value plt.figure(figsize=(12, 6)) plt.plot(loss + runtime_vqe_result.nuclear_repulsion_energy, label="Runtime VQE") plt.axhline(y=target_energy + 0.2, color="tab:red", ls=":", label="Target + 200mH") plt.axhline(y=target_energy, color="tab:red", ls="--", label="Target") plt.legend(loc="best") plt.xlabel("Iteration") plt.ylabel("Energy [H]") plt.title("VQE energy"); import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization.problems import QuadraticProgram # define a problem qp = QuadraticProgram() qp.binary_var("x") qp.integer_var(name="y", lowerbound=-1, upperbound=4) qp.maximize(quadratic={("x", "y"): 1}) qp.linear_constraint({"x": 1, "y": -1}, "<=", 0) print(qp.prettyprint()) from qiskit_optimization.algorithms import CplexOptimizer, GurobiOptimizer cplex_result = CplexOptimizer().solve(qp) gurobi_result = GurobiOptimizer().solve(qp) print("cplex") print(cplex_result.prettyprint()) print() print("gurobi") print(gurobi_result.prettyprint()) result = CplexOptimizer(disp=True, cplex_parameters={"threads": 1, "timelimit": 0.1}).solve(qp) print(result.prettyprint()) from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit_aer import Aer from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler meo = MinimumEigenOptimizer(QAOA(sampler=Sampler(), optimizer=COBYLA(maxiter=100))) result = meo.solve(qp) print(result.prettyprint()) print("\ndisplay the best 5 solution samples") for sample in result.samples[:5]: print(sample) # docplex model from docplex.mp.model import Model docplex_model = Model("docplex") x = docplex_model.binary_var("x") y = docplex_model.integer_var(-1, 4, "y") docplex_model.maximize(x * y) docplex_model.add_constraint(x <= y) docplex_model.prettyprint() # gurobi model import gurobipy as gp gurobipy_model = gp.Model("gurobi") x = gurobipy_model.addVar(vtype=gp.GRB.BINARY, name="x") y = gurobipy_model.addVar(vtype=gp.GRB.INTEGER, lb=-1, ub=4, name="y") gurobipy_model.setObjective(x * y, gp.GRB.MAXIMIZE) gurobipy_model.addConstr(x - y <= 0) gurobipy_model.update() gurobipy_model.display() from qiskit_optimization.translators import from_docplex_mp, from_gurobipy qp = from_docplex_mp(docplex_model) print("QuadraticProgram obtained from docpblex") print(qp.prettyprint()) print("-------------") print("QuadraticProgram obtained from gurobipy") qp2 = from_gurobipy(gurobipy_model) print(qp2.prettyprint()) from qiskit_optimization.translators import to_gurobipy, to_docplex_mp gmod = to_gurobipy(from_docplex_mp(docplex_model)) print("convert docplex to gurobipy via QuadraticProgram") gmod.display() dmod = to_docplex_mp(from_gurobipy(gurobipy_model)) print("\nconvert gurobipy to docplex via QuadraticProgram") print(dmod.export_as_lp_string()) ind_mod = Model("docplex") x = ind_mod.binary_var("x") y = ind_mod.integer_var(-1, 2, "y") z = ind_mod.integer_var(-1, 2, "z") ind_mod.maximize(3 * x + y - z) ind_mod.add_indicator(x, y >= z, 1) print(ind_mod.export_as_lp_string()) qp = from_docplex_mp(ind_mod) result = meo.solve(qp) # apply QAOA to QuadraticProgram print("QAOA") print(result.prettyprint()) print("-----\nCPLEX") print(ind_mod.solve()) # apply CPLEX directly to the Docplex model import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 42 from qiskit.circuit import Parameter from qiskit import QuantumCircuit params1 = [Parameter("input1"), Parameter("weight1")] qc1 = QuantumCircuit(1) qc1.h(0) qc1.ry(params1[0], 0) qc1.rx(params1[1], 0) qc1.draw("mpl") from qiskit.quantum_info import SparsePauliOp observable1 = SparsePauliOp.from_list([("Y" * qc1.num_qubits, 1)]) from qiskit_machine_learning.neural_networks import EstimatorQNN estimator_qnn = EstimatorQNN( circuit=qc1, observables=observable1, input_params=[params1[0]], weight_params=[params1[1]] ) estimator_qnn from qiskit.circuit import ParameterVector inputs2 = ParameterVector("input", 2) weights2 = ParameterVector("weight", 4) print(f"input parameters: {[str(item) for item in inputs2.params]}") print(f"weight parameters: {[str(item) for item in weights2.params]}") qc2 = QuantumCircuit(2) qc2.ry(inputs2[0], 0) qc2.ry(inputs2[1], 1) qc2.cx(0, 1) qc2.ry(weights2[0], 0) qc2.ry(weights2[1], 1) qc2.cx(0, 1) qc2.ry(weights2[2], 0) qc2.ry(weights2[3], 1) qc2.draw(output="mpl") from qiskit_machine_learning.neural_networks import SamplerQNN sampler_qnn = SamplerQNN(circuit=qc2, input_params=inputs2, weight_params=weights2) sampler_qnn estimator_qnn_input = algorithm_globals.random.random(estimator_qnn.num_inputs) estimator_qnn_weights = algorithm_globals.random.random(estimator_qnn.num_weights) print( f"Number of input features for EstimatorQNN: {estimator_qnn.num_inputs} \nInput: {estimator_qnn_input}" ) print( f"Number of trainable weights for EstimatorQNN: {estimator_qnn.num_weights} \nWeights: {estimator_qnn_weights}" ) sampler_qnn_input = algorithm_globals.random.random(sampler_qnn.num_inputs) sampler_qnn_weights = algorithm_globals.random.random(sampler_qnn.num_weights) print( f"Number of input features for SamplerQNN: {sampler_qnn.num_inputs} \nInput: {sampler_qnn_input}" ) print( f"Number of trainable weights for SamplerQNN: {sampler_qnn.num_weights} \nWeights: {sampler_qnn_weights}" ) estimator_qnn_forward = estimator_qnn.forward(estimator_qnn_input, estimator_qnn_weights) print( f"Forward pass result for EstimatorQNN: {estimator_qnn_forward}. \nShape: {estimator_qnn_forward.shape}" ) sampler_qnn_forward = sampler_qnn.forward(sampler_qnn_input, sampler_qnn_weights) print( f"Forward pass result for SamplerQNN: {sampler_qnn_forward}. \nShape: {sampler_qnn_forward.shape}" ) estimator_qnn_forward_batched = estimator_qnn.forward( [estimator_qnn_input, estimator_qnn_input], estimator_qnn_weights ) print( f"Forward pass result for EstimatorQNN: {estimator_qnn_forward_batched}. \nShape: {estimator_qnn_forward_batched.shape}" ) sampler_qnn_forward_batched = sampler_qnn.forward( [sampler_qnn_input, sampler_qnn_input], sampler_qnn_weights ) print( f"Forward pass result for SamplerQNN: {sampler_qnn_forward_batched}. \nShape: {sampler_qnn_forward_batched.shape}" ) estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward( estimator_qnn_input, estimator_qnn_weights ) print( f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad}" ) print( f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}" ) sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward( sampler_qnn_input, sampler_qnn_weights ) print( f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad}" ) print( f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}" ) estimator_qnn.input_gradients = True sampler_qnn.input_gradients = True estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward( estimator_qnn_input, estimator_qnn_weights ) print( f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad.shape}" ) print( f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}" ) sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward( sampler_qnn_input, sampler_qnn_weights ) print( f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad.shape}" ) print( f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}" ) observable2 = SparsePauliOp.from_list([("Z" * qc1.num_qubits, 1)]) estimator_qnn2 = EstimatorQNN( circuit=qc1, observables=[observable1, observable2], input_params=[params1[0]], weight_params=[params1[1]], ) estimator_qnn_forward2 = estimator_qnn2.forward(estimator_qnn_input, estimator_qnn_weights) estimator_qnn_input_grad2, estimator_qnn_weight_grad2 = estimator_qnn2.backward( estimator_qnn_input, estimator_qnn_weights ) print(f"Forward output for EstimatorQNN1: {estimator_qnn_forward.shape}") print(f"Forward output for EstimatorQNN2: {estimator_qnn_forward2.shape}") print(f"Backward output for EstimatorQNN1: {estimator_qnn_weight_grad.shape}") print(f"Backward output for EstimatorQNN2: {estimator_qnn_weight_grad2.shape}") parity = lambda x: "{:b}".format(x).count("1") % 2 output_shape = 2 # parity = 0, 1 sampler_qnn2 = SamplerQNN( circuit=qc2, input_params=inputs2, weight_params=weights2, interpret=parity, output_shape=output_shape, ) sampler_qnn_forward2 = sampler_qnn2.forward(sampler_qnn_input, sampler_qnn_weights) sampler_qnn_input_grad2, sampler_qnn_weight_grad2 = sampler_qnn2.backward( sampler_qnn_input, sampler_qnn_weights ) print(f"Forward output for SamplerQNN1: {sampler_qnn_forward.shape}") print(f"Forward output for SamplerQNN2: {sampler_qnn_forward2.shape}") print(f"Backward output for SamplerQNN1: {sampler_qnn_weight_grad.shape}") print(f"Backward output for SamplerQNN2: {sampler_qnn_weight_grad2.shape}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Alan-Robertson/QiskitPool
Alan-Robertson
''' qiskitpool/job.py Contains the QJob class ''' from functools import partial from qiskit import execute class QJob(): ''' QJob Job manager for asynch qiskit backends ''' def __init__(self, *args, qjob_id=None, **kwargs): ''' QJob.__init__ Initialiser for a qiksit job :: *args :: Args for qiskit execute :: **kwargs :: Kwargs for qiskit execute ''' self.job_fn = partial(execute, *args, **kwargs) self.job = None self.done = False self.test_count = 10 self.qjob_id = qjob_id def __call__(self): ''' QJob.__call__ Wrapper for QJob.run ''' return self.run() def run(self): ''' QJob.run Send async job to qiskit backend ''' self.job = self.job_fn() return self def poll(self): ''' QJob.poll Poll qiskit backend for job completion status ''' if self.job is not None: return self.job.done() return False def cancel(self): ''' QJob.cancel Cancel job on backend ''' if self.job is None: return None return self.job.cancel() def position(self): pos = self.job.queue_position() if pos is None: return 0 return pos def status(self): if self.job is None: return 'LOCAL QUEUE' else: status = self.job.status().value if 'running' in status: return 'RUNNING' if 'run' in status: return 'COMPLETE' if 'validated' in status: return 'VALIDATING' if 'queued' in status: pos = self.position() return f'QISKIT QUEUE: {self.position()}' def status_short(self): if self.job is None: return ' ' else: status = self.job.status().value if 'running' in status: return 'R' if 'run' in status: return 'C' if 'validated' in status: return 'V' if 'queued' in status: return str(self.position()) def result(self): ''' QJob.result Get result from backend Non blocking - returns False if a job is not yet ready ''' if self.poll(): return self.job.result() return False
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import json from urllib.parse import urlencode from urllib.request import urlopen from qiskit import * from qiskit.tools.monitor import job_monitor import ipywidgets as widgets from IPython.display import display import threading import os script_dir = os.path.dirname(__file__) IBMQ.load_accounts(hub=None) __all__ = ['quantum_slot_machine'] def quantum_slot_machine(): """A slot machine that uses random numbers generated by quantum mechanical processses. """ qslot = widgets.VBox(children=[slot, opts]) qslot.children[0].children[1].children[7].children[1]._qslot = qslot qslot.children[0].children[1].children[7].children[1].on_click(pull_slot) ibmq_thread = threading.Thread(target=get_ibmq_ints, args=(qslot,)) ibmq_thread.start() display(qslot) def get_slot_values(backend, qslot): if backend == 'qasm_simulator': back = BasicAer.get_backend('qasm_simulator') q = QuantumRegister(9, name='q') c = ClassicalRegister(9, name='c') qc = QuantumCircuit(q, c) for kk in range(9): qc.h(q[kk]) qc.measure(q, c) job = execute(qc, backend=back, shots=1) result = job.result() counts = list(result.get_counts().keys())[0] return int(counts[0:3], 2), int(counts[3:6], 2), int(counts[6:9], 2) elif backend == 'ibmq_5_tenerife': int1 = qslot.children[0]._stored_ints.pop(0) int2 = qslot.children[0]._stored_ints.pop(0) int3 = qslot.children[0]._stored_ints.pop(0) if len(qslot.children[0]._stored_ints) == 0: ibmq_thread = threading.Thread(target=get_ibmq_ints, args=(qslot,)) ibmq_thread.start() return int1, int2, int3 elif backend == 'ANU QRNG': URL = 'https://qrng.anu.edu.au/API/jsonI.php' url = URL + '?' + urlencode({'type': 'hex16', 'length': 3, 'size': 1}) data = json.loads(urlopen(url).read().decode('ascii')) rngs = [int(bin(int(kk, 16))[2:].zfill(8)[:3], 2) for kk in data['data']] return rngs[0], rngs[1], rngs[2] else: raise Exception('Invalid backend choice.') def set_images(a, b, c, qslot): slot0 = qslot.children[0].children[1].children[1] slot1 = qslot.children[0].children[1].children[3] slot2 = qslot.children[0].children[1].children[5] slot0.value = qslot.children[0]._images[a] slot1.value = qslot.children[0]._images[b] slot2.value = qslot.children[0]._images[c] def update_credits(change, qslot): qslot.children[0]._credits += change qslot.children[1].children[1].value = front_str + \ str(qslot.children[0]._credits)+back_str def compute_payout(ints, qslot): out = 1 #Paytable # all sevens if all([x == 7 for x in ints]): value = 700 # all watermelons elif all([x == 6 for x in ints]): value = 200 # all strawberry elif all([x == 5 for x in ints]): value = 10 # all orange elif all([x == 4 for x in ints]): value = 20 # all lemon elif all([x == 3 for x in ints]): value = 60 # all grape elif all([x == 2 for x in ints]): value = 15 # all cherry elif all([x == 1 for x in ints]): value = 40 # all bell elif all([x == 0 for x in ints]): value = 80 # two bells elif sum([x == 0 for x in ints])== 2: value = 5 # two bells elif sum([x == 0 for x in ints]) == 1: value = 1 else: value = 0 if value: update_credits(value, qslot) # if no credits left if qslot.children[0]._credits <= 0: qslot.children[1].children[1].value = front_str + \ "LOSE"+back_str out = 0 return out def pull_slot(b): qslot = b._qslot update_credits(-1, qslot) b.disabled = True set_images(-1, -1, -1, qslot) backend = qslot.children[1].children[0].value ints = get_slot_values(backend, qslot) set_images(ints[0], ints[1], ints[2], qslot) alive = compute_payout(ints, qslot) if alive: b.disabled = False # generate new ibm q values def get_ibmq_ints(qslot): qslot.children[1].children[0].options = ['qasm_simulator', 'ANU QRNG'] qslot.children[1].children[0].value = 'qasm_simulator' back = IBMQ.get_backend('ibmq_5_tenerife') q = QuantumRegister(3, name='q') c = ClassicalRegister(3, name='c') qc = QuantumCircuit(q, c) for kk in range(3): qc.h(q[kk]) qc.measure(q, c) job = execute(qc, backend=back, shots=300, memory=True) qslot.children[1].children[2].clear_output() with qslot.children[1].children[2]: job_monitor(job) qslot.children[0]._stored_ints = [ int(kk, 16) for kk in job.result().results[0].data.memory] qslot.children[1].children[0].options = ['qasm_simulator', 'ibmq_5_tenerife', 'ANU QRNG'] #top top_file = open(script_dir+"/machine/slot_top.png", "rb") top_image = top_file.read() slot_top = widgets.Image( value=top_image, format='png', width='100%', height='auto', layout=widgets.Layout(margin='0px 0px 0px 0px') ) #bottom bottom_file = open(script_dir+"/machine/slot_bottom.png", "rb") bottom_image = bottom_file.read() slot_bottom = widgets.Image( value=bottom_image, format='png', width='100%', height='auto', layout=widgets.Layout(margin='0px 0px 0px 0px') ) #left left_file = open(script_dir+"/machine/slot_left.png", "rb") left_image = left_file.read() left = widgets.Image( value=left_image, format='png', width='auto', height='auto', margin='0px 0px 0px 0px' ) #left right_file = open(script_dir+"/machine/slot_right.png", "rb") right_image = right_file.read() right = widgets.Image( value=right_image, format='png', width='auto', height='auto', margin='0px 0px 0px 0px' ) #mid mid_file = open(script_dir+"/machine/slot_middle.png", "rb") mid_image = mid_file.read() mid = widgets.Image( value=mid_image, format='png', width='auto', height='auto', margin='0px 0px 0px 0px' ) #symbols blank_sym = open(script_dir+"/symbols/blank.png", "rb") blank_img = blank_sym.read() slot0 = widgets.Image( value=blank_img, format='png', width='auto', height='auto', max_width='175px', max_height='175px' ) slot1 = widgets.Image( value=blank_img, format='png', width='auto', height='auto', max_width='175px', max_height='175px' ) slot2 = widgets.Image( value=blank_img, format='png', width='auto', height='auto', max_width='175px', max_height='175px' ) #arm arm_upper_file = open(script_dir+"/machine/slot_handle_upper.png", "rb") arm__upper_image = arm_upper_file.read() arm_upper = widgets.Image( value=arm__upper_image, format='png', width='auto') arm_lower_file = open(script_dir+"/machine/slot_handle_lower.png", "rb") arm__lower_image = arm_lower_file.read() arm_lower = widgets.Image( value=arm__lower_image, format='png', width='auto') arm_button = widgets.Button(description='PUSH', button_style='danger', layout=widgets.Layout(width='120px', height='auto', margin='0px 35px')) arm_button.style.font_weight = 'bold' arm = widgets.VBox(children=[arm_upper, arm_button, arm_lower], layout=widgets.Layout(width='auto', margin='0px 0px 0px 0px')) items = [left, slot0, mid, slot1, mid, slot2, right, arm] box_layout = widgets.Layout(display='flex', flex_flow='row', align_items='center', width='auto', margin='0px 0px 0px 0px') slot_middle = widgets.Box(children=items, layout=box_layout) slot = widgets.VBox(children=[slot_top, slot_middle, slot_bottom], layout=widgets.Layout(display='flex', flex_flow='column', align_items='center', width='auto', margin='0px 0px 0px 0px')) slot._stored_ints = [] imgs = ['waiting.png', 'bell.png', 'cherry.png', 'grape.png', 'lemon.png', 'orange.png', 'strawberry.png', 'watermelon.png', 'seven.png'] slot._images = {} for kk, img in enumerate(imgs): slot._images[kk-1] = open(script_dir+"/symbols/%s" % img, "rb").read() slot._credits = 20 solver = widgets.Dropdown( options=['qasm_simulator', 'ibmq_5_tenerife', 'ANU QRNG'], value='qasm_simulator', description='', disabled=False, layout=widgets.Layout(width='25%', padding='10px') ) front_str = "<div style = 'background-color:#000000; height:70px; text-align:right;padding:10px' > <p style='color:#FFFFFF; font-size: 60px;margin: 10px'>" back_str = "</p></div>" payout = widgets.HTML( value=front_str+str(20)+back_str, placeholder='', description='', layout=widgets.Layout(width='33%', height='70px') ) out = widgets.Output(layout=widgets.Layout(width='33%', padding='10px')) opts = widgets.HBox(children=[solver, payout, out], layout=widgets.Layout(width='100%', justify_content='center', border='2px solid black'))
https://github.com/AmirhoseynpowAsghari/Qiskit-Tutorials
AmirhoseynpowAsghari
import numpy as np import matplotlib.pyplot as plt # Define a function to create a random Hermitian matrix of size n def create_random_hermitian_matrix(n): A = np.random.rand(n, n) + 1j * np.random.rand(n, n) return A + A.conj().T # Define the size of the matrix n = 10 # Create the unperturbed density matrix (ground state) rho_0_large = create_random_hermitian_matrix(n) rho_0_large = (rho_0_large + rho_0_large.conj().T) / 2 # Ensure it's Hermitian # Create a small perturbation matrix perturbation_large = create_random_hermitian_matrix(n) * 0.05 # Scale it to be a small perturbation # Linear response: rho(t) = rho_0 + perturbation rho_linear_large = rho_0_large + perturbation_large # Multiplicative response: rho(t) = rho_0 * perturbation (element-wise multiplication) rho_multiplicative_large = rho_0_large * perturbation_large # Compute the eigenvalues eigenvalues_rho_0_large = np.linalg.eigvals(rho_0_large) eigenvalues_linear_large = np.linalg.eigvals(rho_linear_large) eigenvalues_multiplicative_large = np.linalg.eigvals(rho_multiplicative_large) # Plot the eigenvalues fig, ax = plt.subplots(figsize=(12, 6)) x = np.arange(n) ax.plot(x, eigenvalues_rho_0_large.real, 'o-', label='rho_0') ax.plot(x, eigenvalues_linear_large.real, 's-', label='Linear (rho_0 + perturbation)') ax.plot(x, eigenvalues_multiplicative_large.real, 'd-', label='Multiplicative (rho_0 * perturbation)') ax.set_xticks(x) ax.set_xticklabels([f'Eigenvalue {i+1}' for i in x]) ax.set_ylabel('Eigenvalues (Real Part)') ax.set_title('Eigenvalues of the Density Matrix for a Large System') ax.legend() plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qc1 = QuantumCircuit(2) qc1.x(0) qc1.h(1) custom = qc1.to_gate().control(2) qc2 = QuantumCircuit(4) qc2.append(custom, [0, 3, 1, 2]) qc2.draw('mpl')
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
ahkatlio
from qiskit import QuantumCircuit from qiskit.visualization import visualize_transition qc = QuantumCircuit(1) qc.z(0) qc.draw('mpl') visualize_transition(qc) qc1 = QuantumCircuit(1) qc1.x(0) qc1.z(0) qc1.draw('mpl') visualize_transition(qc1)
https://github.com/allanwing-qc/DTQW_General_Coin
allanwing-qc
#pip install qiskit #pip install qiskit[visualization] import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer from qiskit.circuit.library import MCMT from qiskit.circuit.library import MCMTVChain from qiskit.circuit.library import SXdgGate from qiskit.quantum_info.operators import Operator, Pauli import qiskit.quantum_info as qi import numpy as np import math as m from qiskit import * from qiskit import Aer qreg = qiskit.QuantumRegister(4) creg = qiskit.ClassicalRegister(2) circuit = qiskit.QuantumCircuit(qreg,creg) n_steps=1 for i in range(n_steps): circuit.h(2) circuit.h(3) circuit.cx(3,1) circuit.cx(2,0) circuit.measure(0,0) circuit.measure(1,1) circuit.draw('mpl') #Changing the simulator sim = qiskit.Aer.get_backend('qasm_simulator') #job execution and getting the result as an object job = execute(circuit, sim,shots=100000) result = job.result() counts = job.result().get_counts() factor=1.0/sum(counts.values()) probabilities1 = {k: v*factor for k, v in counts.items()} qiskit.visualization.plot_histogram(probabilities1) q = QuantumRegister(4) c = ClassicalRegister(2) qc = QuantumCircuit(q,c) csxdg_gate = SXdgGate().control(2) for i in range(n_steps): qc.x(0) qc.x(1) qc.append(csxdg_gate, [0,1,2]) qc.append(csxdg_gate, [0,1,3]) qc.x(0) qc.x(1) qc.x(0) qc.append(MCMT('h',2,2), list(range(4))) qc.x(0) qc.x(1) qc.append(csxdg_gate, [0,1,2]) qc.append(csxdg_gate, [0,1,3]) qc.x(1) qc.append(MCMT('h',2,2), list(range(4))) qc.cx(3,1) qc.cx(2,0) qc.measure(q[0],c[0]) qc.measure(q[1],c[1]) qc.draw('mpl') #Changing the simulator sim = qiskit.Aer.get_backend('qasm_simulator') #job execution and getting the result as an object job = execute(qc, sim,shots=100000) result = job.result() counts = job.result().get_counts() factor=1.0/sum(counts.values()) probabilities2 = {k: v*factor for k, v in counts.items()} qiskit.visualization.plot_histogram(probabilities2) legend = ['Hadamard coin', 'General coin'] qiskit.visualization.plot_histogram([probabilities1, probabilities2], color=['midnightblue','crimson'], title="Step 6")
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test OptimizeSwapBeforeMeasure pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.transpiler import PassManager from qiskit.transpiler.passes import OptimizeSwapBeforeMeasure, DAGFixedPoint from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestOptimizeSwapBeforeMeasure(QiskitTestCase): """Test swap-followed-by-measure optimizations.""" def test_optimize_1swap_1measure(self): """Remove a single swap qr0:--X--m-- qr0:---- | | qr1:--X--|-- ==> qr1:--m- | | cr0:-----.-- cr0:--.- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[1], cr[0]) pass_ = OptimizeSwapBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_1swap_2measure(self): """Remove a single swap affecting two measurements qr0:--X--m-- qr0:--m---- | | | qr1:--X--|--m ==> qr1:--|--m- | | | | cr0:-----.--|-- cr0:--|--.- cr1:--------.-- cr1:--.---- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.measure(qr[1], cr[0]) expected.measure(qr[0], cr[1]) pass_ = OptimizeSwapBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_nswap_nmeasure(self): """Remove severals swap affecting multiple measurements ┌─┐ ┌─┐ q_0: ─X──X─────X────┤M├───────────────────────────────── q_0: ──────┤M├─────────────── │ │ │ └╥┘ ┌─┐ ┌─┐└╥┘ q_1: ─X──X──X──X──X──╫─────X────┤M├───────────────────── q_1: ───┤M├─╫──────────────── │ │ ║ │ └╥┘ ┌─┐ ┌─┐└╥┘ ║ q_2: ───────X──X──X──╫──X──X─────╫──X────┤M├──────────── q_2: ┤M├─╫──╫──────────────── │ ║ │ ║ │ └╥┘┌─┐ └╥┘ ║ ║ ┌─┐ q_3: ─X─────X──X─────╫──X──X──X──╫──X─────╫─┤M├───────── q_3: ─╫──╫──╫────┤M├───────── │ │ ║ │ │ ║ ║ └╥┘┌─┐ ║ ║ ║ └╥┘ ┌─┐ q_4: ─X──X──X──X─────╫──X──X──X──╫──X─────╫──╫─┤M├────── ==> q_4: ─╫──╫──╫─────╫───────┤M├ │ │ ║ │ ║ │ ║ ║ └╥┘┌─┐ ║ ║ ║ ┌─┐ ║ └╥┘ q_5: ────X──X──X──X──╫──X──X─────╫──X──X──╫──╫──╫─┤M├─── q_5: ─╫──╫──╫─┤M├─╫────────╫─ │ │ ║ │ ║ │ ║ ║ ║ └╥┘┌─┐ ║ ║ ║ └╥┘ ║ ┌─┐ ║ q_6: ─X──X──X──X──X──╫──X──X─────╫─────X──╫──╫──╫──╫─┤M├ q_6: ─╫──╫──╫──╫──╫─┤M├────╫─ │ │ │ ║ │ ┌─┐ ║ ║ ║ ║ ║ └╥┘ ║ ║ ║ ║ ║ └╥┘┌─┐ ║ q_7: ─X──X─────X─────╫──X─┤M├────╫────────╫──╫──╫──╫──╫─ q_7: ─╫──╫──╫──╫──╫──╫─┤M├─╫─ ║ └╥┘ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ └╥┘ ║ c: 8/════════════════╩═════╩═════╩════════╩══╩══╩══╩══╩═ c: 8/═╩══╩══╩══╩══╩══╩══╩══╩═ 0 7 1 2 3 4 5 6 0 1 2 3 4 5 6 7 """ circuit = QuantumCircuit(8, 8) circuit.swap(3, 4) circuit.swap(6, 7) circuit.swap(0, 1) circuit.swap(6, 7) circuit.swap(4, 5) circuit.swap(0, 1) circuit.swap(5, 6) circuit.swap(3, 4) circuit.swap(1, 2) circuit.swap(6, 7) circuit.swap(4, 5) circuit.swap(2, 3) circuit.swap(0, 1) circuit.swap(5, 6) circuit.swap(1, 2) circuit.swap(6, 7) circuit.swap(4, 5) circuit.swap(2, 3) circuit.swap(3, 4) circuit.swap(3, 4) circuit.swap(5, 6) circuit.swap(1, 2) circuit.swap(4, 5) circuit.swap(2, 3) circuit.swap(5, 6) circuit.measure(range(8), range(8)) dag = circuit_to_dag(circuit) expected = QuantumCircuit(8, 8) expected.measure(0, 2) expected.measure(1, 1) expected.measure(2, 0) expected.measure(3, 4) expected.measure(4, 7) expected.measure(5, 3) expected.measure(6, 5) expected.measure(7, 6) pass_ = OptimizeSwapBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_cannot_optimize(self): """Cannot optimize when swap is not at the end in all of the successors qr0:--X-----m-- | | qr1:--X-[H]-|-- | cr0:--------.-- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]) circuit.h(qr[1]) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) pass_ = OptimizeSwapBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(circuit), after) def test_if_else(self): """Test that the pass recurses into a simple if-else.""" pass_ = OptimizeSwapBeforeMeasure() base_test = QuantumCircuit(2, 1) base_test.swap(0, 1) base_test.measure(0, 0) base_expected = QuantumCircuit(2, 1) base_expected.measure(1, 0) test = QuantumCircuit(2, 1) test.if_else( (test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits ) expected = QuantumCircuit(2, 1) expected.if_else( (expected.clbits[0], True), base_expected.copy(), base_expected.copy(), expected.qubits, expected.clbits, ) self.assertEqual(pass_(test), expected) def test_nested_control_flow(self): """Test that the pass recurses into nested control flow.""" pass_ = OptimizeSwapBeforeMeasure() base_test = QuantumCircuit(2, 1) base_test.swap(0, 1) base_test.measure(0, 0) base_expected = QuantumCircuit(2, 1) base_expected.measure(1, 0) body_test = QuantumCircuit(2, 1) body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits) body_expected = QuantumCircuit(2, 1) body_expected.for_loop( (0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits ) test = QuantumCircuit(2, 1) test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits) expected = QuantumCircuit(2, 1) expected.while_loop( (expected.clbits[0], True), body_expected, expected.qubits, expected.clbits ) self.assertEqual(pass_(test), expected) class TestOptimizeSwapBeforeMeasureFixedPoint(QiskitTestCase): """Test swap-followed-by-measure optimizations in a transpiler, using fixed point.""" def test_optimize_undone_swap(self): """Remove redundant swap qr0:--X--X--m-- qr0:--m--- | | | | qr1:--X--X--|-- ==> qr1:--|-- | | cr0:--------.-- cr0:--.-- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]) circuit.swap(qr[0], qr[1]) circuit.measure(qr[0], cr[0]) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) pass_manager = PassManager() pass_manager.append( [OptimizeSwapBeforeMeasure(), DAGFixedPoint()], do_while=lambda property_set: not property_set["dag_fixed_point"], ) after = pass_manager.run(circuit) self.assertEqual(expected, after) def test_optimize_overlap_swap(self): """Remove two swaps that overlap qr0:--X-------- qr0:--m-- | | qr1:--X--X----- qr1:--|-- | ==> | qr2:-----X--m-- qr2:--|-- | | cr0:--------.-- cr0:--.-- """ qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]) circuit.swap(qr[1], qr[2]) circuit.measure(qr[2], cr[0]) expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr[0]) pass_manager = PassManager() pass_manager.append( [OptimizeSwapBeforeMeasure(), DAGFixedPoint()], do_while=lambda property_set: not property_set["dag_fixed_point"], ) after = pass_manager.run(circuit) self.assertEqual(expected, after) def test_no_optimize_swap_with_condition(self): """Do not remove swap if it has a condition qr0:--X--m-- qr0:--X--m-- | | | | qr1:--X--|-- ==> qr1:--X--|-- | | | | cr0:--1--.-- cr0:--1--.-- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]).c_if(cr, 1) circuit.measure(qr[0], cr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.swap(qr[0], qr[1]).c_if(cr, 1) expected.measure(qr[0], cr[0]) pass_ = OptimizeSwapBeforeMeasure() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.utils import algorithm_globals from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import ( MinimumEigenOptimizer, RecursiveMinimumEigenOptimizer, SolutionSample, OptimizationResultStatus, ) from qiskit_optimization import QuadraticProgram from qiskit.visualization import plot_histogram from typing import List, Tuple import numpy as np # create a QUBO qubo = QuadraticProgram() qubo.binary_var("x") qubo.binary_var("y") qubo.binary_var("z") qubo.minimize(linear=[1, -2, 3], quadratic={("x", "y"): 1, ("x", "z"): -1, ("y", "z"): 2}) print(qubo.prettyprint()) op, offset = qubo.to_ising() print("offset: {}".format(offset)) print("operator:") print(op) qp = QuadraticProgram() qp.from_ising(op, offset, linear=True) print(qp.prettyprint()) algorithm_globals.random_seed = 10598 qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 0.0]) exact_mes = NumPyMinimumEigensolver() qaoa = MinimumEigenOptimizer(qaoa_mes) # using QAOA exact = MinimumEigenOptimizer(exact_mes) # using the exact classical numpy minimum eigen solver exact_result = exact.solve(qubo) print(exact_result.prettyprint()) qaoa_result = qaoa.solve(qubo) print(qaoa_result.prettyprint()) print("variable order:", [var.name for var in qaoa_result.variables]) for s in qaoa_result.samples: print(s) def get_filtered_samples( samples: List[SolutionSample], threshold: float = 0, allowed_status: Tuple[OptimizationResultStatus] = (OptimizationResultStatus.SUCCESS,), ): res = [] for s in samples: if s.status in allowed_status and s.probability > threshold: res.append(s) return res filtered_samples = get_filtered_samples( qaoa_result.samples, threshold=0.005, allowed_status=(OptimizationResultStatus.SUCCESS,) ) for s in filtered_samples: print(s) fvals = [s.fval for s in qaoa_result.samples] probabilities = [s.probability for s in qaoa_result.samples] np.mean(fvals) np.std(fvals) samples_for_plot = { " ".join(f"{qaoa_result.variables[i].name}={int(v)}" for i, v in enumerate(s.x)): s.probability for s in filtered_samples } samples_for_plot plot_histogram(samples_for_plot) rqaoa = RecursiveMinimumEigenOptimizer(qaoa, min_num_vars=1, min_num_vars_optimizer=exact) rqaoa_result = rqaoa.solve(qubo) print(rqaoa_result.prettyprint()) filtered_samples = get_filtered_samples( rqaoa_result.samples, threshold=0.005, allowed_status=(OptimizationResultStatus.SUCCESS,) ) samples_for_plot = { " ".join(f"{rqaoa_result.variables[i].name}={int(v)}" for i, v in enumerate(s.x)): s.probability for s in filtered_samples } samples_for_plot plot_histogram(samples_for_plot) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/AmirhoseynpowAsghari/Qiskit-Tutorials
AmirhoseynpowAsghari
from qiskit import QuantumCircuit, Aer, execute import matplotlib.pyplot as plt # Function to generate a random bit using a quantum circuit def generate_random_bit(): # Create a quantum circuit with one qubit and one classical bit qc = QuantumCircuit(1, 1) # Apply Hadamard gate to put the qubit in superposition qc.h(0) # Measure the qubit qc.measure(0, 0) # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator result = execute(qc, simulator, shots=1).result() # Get the measurement result counts = result.get_counts(qc) bit = int(list(counts.keys())[0]) return bit # Generate a random bit random_bit = generate_random_bit() print(f"Random bit: {random_bit}") # Generate multiple random bits num_bits = 10 random_bits = [generate_random_bit() for _ in range(num_bits)] print(f"Random bits: {random_bits}") # Plot the random bits plt.bar(range(num_bits), random_bits, tick_label=range(num_bits)) plt.xlabel('Bit index') plt.ylabel('Random bit value') plt.title('Quantum Random Number Generation') plt.show()
https://github.com/qctrl/python-qiskit
qctrl
# Copyright 2022 Q-CTRL # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Tests conversion to Qiskit Circuit """ import numpy as np from qctrlopencontrols import ( new_carr_purcell_sequence, new_cpmg_sequence, new_periodic_sequence, new_quadratic_sequence, new_spin_echo_sequence, new_uhrig_sequence, new_walsh_sequence, new_x_concatenated_sequence, new_xy_concatenated_sequence, ) from qiskit import ( BasicAer, execute, ) from qctrlqiskit import convert_dds_to_qiskit_quantum_circuit _callable = { "Spin echo": new_spin_echo_sequence, "Carr-Purcell": new_carr_purcell_sequence, "Carr-Purcell-Meiboom-Gill": new_cpmg_sequence, "Uhrig single-axis": new_uhrig_sequence, "periodic single-axis": new_periodic_sequence, "quadratic": new_quadratic_sequence, "Walsh single-axis": new_walsh_sequence, "Quadratic": new_quadratic_sequence, "X concatenated": new_x_concatenated_sequence, "XY concatenated": new_xy_concatenated_sequence, } def _create_test_sequence(sequence_scheme, pre_post_rotation): """ Create a DD sequence of choice. Parameters ---------- sequence_scheme : str One of 'Spin echo', 'Carr-Purcell', 'Carr-Purcell-Meiboom-Gill', 'Uhrig single-axis', 'Periodic single-axis', 'Walsh single-axis', 'Quadratic', 'X concatenated', 'XY concatenated' pre_post_rotation : bool If True, adds a :math:`X_{\\pi/2}` gate on either ends Returns ------- DynamicDecouplingSequence The Dynamical Decoupling Sequence instance built from supplied schema information """ dd_sequence_params = {} dd_sequence_params["duration"] = 4 dd_sequence_params["pre_post_rotation"] = pre_post_rotation # 'spin_echo' does not need any additional parameter if sequence_scheme in [ "Carr-Purcell", "Carr-Purcell-Meiboom-Gill", "Uhrig single-axis", "periodic single-axis", ]: dd_sequence_params["offset_count"] = 2 elif sequence_scheme in ["Walsh single-axis"]: dd_sequence_params["paley_order"] = 5 elif sequence_scheme in ["quadratic"]: dd_sequence_params["duration"] = 16 dd_sequence_params["outer_offset_count"] = 4 dd_sequence_params["inner_offset_count"] = 4 elif sequence_scheme in ["X concatenated", "XY concatenated"]: dd_sequence_params["duration"] = 16 dd_sequence_params["concatenation_order"] = 2 sequence = _callable[sequence_scheme](**dd_sequence_params) return sequence def _check_circuit_unitary(pre_post_rotation, algorithm): """ Checks that the unitary of a dynamic decoupling operation is the identity. """ backend = "unitary_simulator" number_of_shots = 1 backend_simulator = BasicAer.get_backend(backend) for sequence_scheme in [ "Carr-Purcell", "Carr-Purcell-Meiboom-Gill", "Uhrig single-axis", "periodic single-axis", "Walsh single-axis", "quadratic", "X concatenated", "XY concatenated", ]: sequence = _create_test_sequence(sequence_scheme, pre_post_rotation) quantum_circuit = convert_dds_to_qiskit_quantum_circuit( dynamic_decoupling_sequence=sequence, add_measurement=False, algorithm=algorithm, ) job = execute(quantum_circuit, backend_simulator, shots=number_of_shots) result = job.result() unitary = result.get_unitary(quantum_circuit) assert np.isclose(np.abs(np.trace(unitary)), 2.0) def test_identity_operation(): """Tests if the Dynamic Decoupling Sequence gives rise to Identity operation in Qiskit """ _check_circuit_unitary(False, "instant unitary") _check_circuit_unitary(True, "instant unitary") _check_circuit_unitary(False, "fixed duration unitary") _check_circuit_unitary(True, "fixed duration unitary") if __name__ == "__main__": pass
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.quantumcircuitdata import CircuitInstruction from qiskit.circuit import Measure from qiskit.circuit.library import HGate, CXGate qr = QuantumRegister(2) cr = ClassicalRegister(2) instructions = [ CircuitInstruction(HGate(), [qr[0]], []), CircuitInstruction(CXGate(), [qr[0], qr[1]], []), CircuitInstruction(Measure(), [qr[0]], [cr[0]]), CircuitInstruction(Measure(), [qr[1]], [cr[1]]), ] circuit = QuantumCircuit.from_instructions(instructions) circuit.draw("mpl")
https://github.com/googlercolin/Qiskit-Course
googlercolin
import numpy as np from qiskit.quantum_info import state_fidelity, Statevector def getStatevector(circuit): return Statevector(circuit).data import warnings warnings.filterwarnings('ignore') def P_haar(N, F): if F == 1: return 0 else: return (N - 1) * ((1 - F) ** (N - 2)) def KL(P, Q): epsilon = 1e-8 kl_divergence = 0.0 for p, q in zip(P, Q): kl_divergence += p * np.log( (p + epsilon) / (q + epsilon) ) return abs(kl_divergence) def expressibility(qubits, sampler, *, bins=100, epoch=3000, layer=1, encode=False, return_detail=False): unit = 1 / bins limits = [] probabilities = np.array([0] * bins) for i in range(1, bins + 1): limits.append(unit * i) for i in range(epoch): circuit_1 = sampler(layer=layer, qubits=qubits) circuit_2 = sampler(layer=layer, qubits=qubits) f = state_fidelity( getStatevector(circuit_1), getStatevector(circuit_2) ) for j in range(bins): if f <= limits[j]: probabilities[j] += 1 break pHaar_vqc = [ P_haar(2 ** qubits, f - (unit/2)) / bins for f in limits] probabilities = [ p / epoch for p in probabilities ] if return_detail: return pHaar_vqc, probabilities else: return KL(probabilities, pHaar_vqc)
https://github.com/AsishMandoi/VRP-explorations
AsishMandoi
import numpy as np from utils import compare_solvers class Initializer: def __init__(self, n, a, b): self.n = n self.a = a self.b = b def generate_nodes_and_weight_matrix(self): n = self.n a = self.a b = self.b np.random.seed(100*a + b) x = (np.random.rand(n) - 0.5) * 50 y = (np.random.rand(n) - 0.5) * 50 weight_matrix = np.zeros([n, n]) for i in range(n): for j in range(i+1, n): weight_matrix[i, j] = (x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2 weight_matrix[j, i] = weight_matrix[i, j] return x, y, weight_matrix ### Select the type of model to solve VRP # 1: Constrained Quadratic Model - A new model released by D-Wave Systems capable of encoding Quadratically Constrained Quadratic Programs (QCQPs) # 2: Binary Quadratic Model - A model that encodes Ising or QUBO problems model = 'CQM' ### The time limit (in seconds) for the solvers to run on the `LeapHybridCQMSampler` backend time_limit = 5 ### Select solver # 1: RAS (Route Activation Solver) # 2: FQS (Full QUBO Solver) # 3: GPS (Guillermo, Parfait, Saúl) (only using CQM) # 4: DBSCANS (Density-Based Spatial Clustering of Applications with Noise - Solver) # 5: SPS (Solution Partition Solver) solver = 'ras' # Number of iterations to get the average approximation ratio for a particular solver # Warning! More iterations will take more time and resources to run n_iter = 1 for n in range(10, 13): ### Here, (2, 6) could be replaced with the some other range of no. of locations you want. for instance in range(4): ### Here, (10) could be replaced with some other number of instcnces you want to generate for a particular no. of locations. initializer = Initializer(n, n, instance) xc, yc, cost = initializer.generate_nodes_and_weight_matrix() for m in range(1, n): comparison_table = compare_solvers(n-1, m, cost, xc, yc, n_iter=n_iter, time_limit=time_limit) print(f'\nn = {n}, m = {m}, instance = {instance}') print('Classical cost from best known solution:', comparison_table[0]['exact_min_cost']) for solver_id in comparison_table[1]: print(f'{solver_id}:', '\t', f'quantum cost = {comparison_table[1][solver_id]["avg_min_cost"]}', '\t', f'runtime = {comparison_table[1][solver_id]["avg_runtime"]}', '\t', f'number of variables = {comparison_table[1][solver_id]["num_vars"]}', '\t', f'approximation ratio = {comparison_table[1][solver_id]["approximation_ratio"]}' ) # for n in range(2, 6): ### Here, (2, 6) could be replaced with the some other range of no. of locations you want. # for instance in range(10): ### Here, (10) could be replaced with some other number of instcnces you want to generate for a particular no. of locations. # initializer = Initializer(n, n, instance) # xc, yc, cost = initializer.generate_nodes_and_weight_matrix() # for m in range(1, n): # comparison_table = compare_solvers(n-1, m, cost, xc, yc, n_iter=n_iter, time_limit=time_limit) # print(f'n = {n}, m = {m}, instance = {instance}') # print('Classical cost from best known solution:', comparison_table[0]['exact_min_cost']) # for solver_id in comparison_table[1]: # print(f'{solver_id}:', '\t', f'quantum cost = {comparison_table[1][solver_id]["avg_min_cost"]}', # '\t', f'runtime = {comparison_table[1][solver_id]["avg_runtime"]}', # '\t', f'number of variables = {comparison_table[1][solver_id]["num_vars"]}', # '\t', f'approximation ratio = {comparison_table[1][solver_id]["approximation_ratio"]}' # )
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.quantum_info import SparsePauliOp H2_op = SparsePauliOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) from qiskit.primitives import Estimator estimator = Estimator() import numpy as np from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SLSQP from qiskit.circuit.library import TwoLocal from qiskit.utils import algorithm_globals # we will iterate over these different optimizers optimizers = [COBYLA(maxiter=80), L_BFGS_B(maxiter=60), SLSQP(maxiter=60)] converge_counts = np.empty([len(optimizers)], dtype=object) converge_vals = np.empty([len(optimizers)], dtype=object) for i, optimizer in enumerate(optimizers): print("\rOptimizer: {} ".format(type(optimizer).__name__), end="") algorithm_globals.random_seed = 50 ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) vqe = VQE(estimator, ansatz, optimizer, callback=store_intermediate_result) result = vqe.compute_minimum_eigenvalue(operator=H2_op) converge_counts[i] = np.asarray(counts) converge_vals[i] = np.asarray(values) print("\rOptimization complete "); import pylab pylab.rcParams["figure.figsize"] = (12, 8) for i, optimizer in enumerate(optimizers): pylab.plot(converge_counts[i], converge_vals[i], label=type(optimizer).__name__) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence for various optimizers") pylab.legend(loc="upper right"); from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit.opflow import PauliSumOp numpy_solver = NumPyMinimumEigensolver() result = numpy_solver.compute_minimum_eigenvalue(operator=PauliSumOp(H2_op)) ref_value = result.eigenvalue.real print(f"Reference value: {ref_value:.5f}") pylab.rcParams["figure.figsize"] = (12, 8) for i, optimizer in enumerate(optimizers): pylab.plot( converge_counts[i], abs(ref_value - converge_vals[i]), label=type(optimizer).__name__, ) pylab.xlabel("Eval count") pylab.ylabel("Energy difference from solution reference value") pylab.title("Energy convergence for various optimizers") pylab.yscale("log") pylab.legend(loc="upper right"); from qiskit.algorithms.gradients import FiniteDiffEstimatorGradient estimator = Estimator() gradient = FiniteDiffEstimatorGradient(estimator, epsilon=0.01) algorithm_globals.random_seed = 50 ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") optimizer = SLSQP(maxiter=100) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) vqe = VQE( estimator, ansatz, optimizer, callback=store_intermediate_result, gradient=gradient ) result = vqe.compute_minimum_eigenvalue(operator=H2_op) print(f"Value using Gradient: {result.eigenvalue.real:.5f}") pylab.rcParams["figure.figsize"] = (12, 8) pylab.plot(counts, values, label=type(optimizer).__name__) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence using Gradient") pylab.legend(loc="upper right"); print(result) cost_function_evals = result.cost_function_evals initial_pt = result.optimal_point estimator1 = Estimator() gradient1 = FiniteDiffEstimatorGradient(estimator, epsilon=0.01) ansatz1 = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") optimizer1 = SLSQP(maxiter=1000) vqe1 = VQE( estimator1, ansatz1, optimizer1, gradient=gradient1, initial_point=initial_pt ) result1 = vqe1.compute_minimum_eigenvalue(operator=H2_op) print(result1) cost_function_evals1 = result1.cost_function_evals print() print( f"cost_function_evals is {cost_function_evals1} with initial point versus {cost_function_evals} without it." ) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the CX Direction pass""" import unittest from math import pi import ddt from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, pulse from qiskit.circuit import Parameter, Gate from qiskit.circuit.library import ( CXGate, CZGate, ECRGate, RXXGate, RYYGate, RZXGate, RZZGate, SwapGate, ) from qiskit.compiler import transpile from qiskit.transpiler import TranspilerError, CouplingMap, Target from qiskit.transpiler.passes import GateDirection from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase @ddt.ddt class TestGateDirection(QiskitTestCase): """Tests the GateDirection pass.""" def test_no_cnots(self): """Trivial map in a circuit without entanglement qr0:---[H]--- qr1:---[H]--- qr2:---[H]--- CouplingMap map: None """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.h(qr) coupling = CouplingMap() dag = circuit_to_dag(circuit) pass_ = GateDirection(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_direction_error(self): """The mapping cannot be fixed by direction mapper qr0:--------- qr1:---(+)--- | qr2:----.---- CouplingMap map: [2] <- [0] -> [1] """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) coupling = CouplingMap([[0, 1], [0, 2]]) dag = circuit_to_dag(circuit) pass_ = GateDirection(coupling) with self.assertRaises(TranspilerError): pass_.run(dag) def test_direction_correct(self): """The CX is in the right direction qr0:---(+)--- | qr1:----.---- CouplingMap map: [0] -> [1] """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) pass_ = GateDirection(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_direction_flip(self): """Flip a CX qr0:----.---- | qr1:---(+)--- CouplingMap map: [0] -> [1] qr0:-[H]-(+)-[H]-- | qr1:-[H]--.--[H]-- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.h(qr[0]) expected.h(qr[1]) expected.cx(qr[0], qr[1]) expected.h(qr[0]) expected.h(qr[1]) pass_ = GateDirection(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_ecr_flip(self): """Flip a ECR gate. ┌──────┐ q_0: ┤1 ├ │ ECR │ q_1: ┤0 ├ └──────┘ CouplingMap map: [0, 1] """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.ecr(qr[1], qr[0]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) # ┌─────────┐ ┌──────┐┌───┐ # qr_0: ┤ Ry(π/2) ├─┤0 ├┤ H ├ # ├─────────┴┐│ Ecr │├───┤ # qr_1: ┤ Ry(-π/2) ├┤1 ├┤ H ├ # └──────────┘└──────┘└───┘ expected = QuantumCircuit(qr) expected.ry(pi / 2, qr[0]) expected.ry(-pi / 2, qr[1]) expected.ecr(qr[0], qr[1]) expected.h(qr[0]) expected.h(qr[1]) pass_ = GateDirection(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_flip_with_measure(self): """ qr0: -(+)-[m]- | | qr1: --.---|-- | cr0: ------.-- CouplingMap map: [0] -> [1] qr0: -[H]--.--[H]-[m]- | | qr1: -[H]-(+)-[H]--|-- | cr0: --------------.-- """ qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[1], qr[0]) circuit.measure(qr[0], cr[0]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr, cr) expected.h(qr[0]) expected.h(qr[1]) expected.cx(qr[0], qr[1]) expected.h(qr[0]) expected.h(qr[1]) expected.measure(qr[0], cr[0]) pass_ = GateDirection(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_preserves_conditions(self): """Verify GateDirection preserves conditional on CX gates. ┌───┐ ┌───┐ q_0: |0>───■────┤ X ├───■──┤ X ├ ┌─┴─┐ └─┬─┘ ┌─┴─┐└─┬─┘ q_1: |0>─┤ X ├────■───┤ X ├──■── └─┬─┘ │ └───┘ ┌──┴──┐┌──┴──┐ c_0: 0 ╡ = 0 ╞╡ = 0 ╞══════════ └─────┘└─────┘ """ qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[1]).c_if(cr, 0) circuit.cx(qr[1], qr[0]).c_if(cr, 0) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) coupling = CouplingMap([[0, 1]]) dag = circuit_to_dag(circuit) # ┌───┐ ┌───┐ ┌───┐ ┌───┐ # q_0: ───■───────────┤ H ├────■───────────┤ H ├───■──┤ H ├──■──┤ H ├ # ┌─┴─┐ ┌───┐ └─╥─┘ ┌─┴─┐ ┌───┐ └─╥─┘ ┌─┴─┐├───┤┌─┴─┐├───┤ # q_1: ─┤ X ├──┤ H ├────╫────┤ X ├──┤ H ├────╫───┤ X ├┤ H ├┤ X ├┤ H ├ # └─╥─┘ └─╥─┘ ║ └─╥─┘ └─╥─┘ ║ └───┘└───┘└───┘└───┘ # ┌──╨──┐┌──╨──┐┌──╨──┐┌──╨──┐┌──╨──┐┌──╨──┐ # c: 1/╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞╡ 0x0 ╞════════════════════ # └─────┘└─────┘└─────┘└─────┘└─────┘└─────┘ expected = QuantumCircuit(qr, cr) expected.cx(qr[0], qr[1]).c_if(cr, 0) # Order of H gates is important because DAG comparison will consider # different conditional order on a creg to be a different circuit. # See https://github.com/Qiskit/qiskit-terra/issues/3164 expected.h(qr[1]).c_if(cr, 0) expected.h(qr[0]).c_if(cr, 0) expected.cx(qr[0], qr[1]).c_if(cr, 0) expected.h(qr[1]).c_if(cr, 0) expected.h(qr[0]).c_if(cr, 0) expected.cx(qr[0], qr[1]) expected.h(qr[1]) expected.h(qr[0]) expected.cx(qr[0], qr[1]) expected.h(qr[1]) expected.h(qr[0]) pass_ = GateDirection(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_regression_gh_8387(self): """Regression test for flipping of CZ gate""" qc = QuantumCircuit(3) qc.cz(1, 0) qc.barrier() qc.cz(2, 0) coupling_map = CouplingMap([[0, 1], [1, 2]]) _ = transpile( qc, basis_gates=["cz", "cx", "u3", "u2", "u1"], coupling_map=coupling_map, optimization_level=2, ) @ddt.data(CXGate(), CZGate(), ECRGate()) def test_target_static(self, gate): """Test that static 2q gates are swapped correctly both if available and not available.""" circuit = QuantumCircuit(2) circuit.append(gate, [0, 1], []) matching = Target(num_qubits=2) matching.add_instruction(gate, {(0, 1): None}) self.assertEqual(GateDirection(None, target=matching)(circuit), circuit) swapped = Target(num_qubits=2) swapped.add_instruction(gate, {(1, 0): None}) self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit) @ddt.data(CZGate(), RZXGate(pi / 3), RXXGate(pi / 3), RYYGate(pi / 3), RZZGate(pi / 3)) def test_target_trivial(self, gate): """Test that trivial 2q gates are swapped correctly both if available and not available.""" circuit = QuantumCircuit(2) circuit.append(gate, [0, 1], []) matching = Target(num_qubits=2) matching.add_instruction(gate, {(0, 1): None}) self.assertEqual(GateDirection(None, target=matching)(circuit), circuit) swapped = Target(num_qubits=2) swapped.add_instruction(gate, {(1, 0): None}) self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit) @ddt.data(CZGate(), SwapGate(), RXXGate(pi / 3), RYYGate(pi / 3), RZZGate(pi / 3)) def test_symmetric_gates(self, gate): """Test symmetric gates on single direction coupling map.""" circuit = QuantumCircuit(2) circuit.append(gate, [1, 0], []) expected = QuantumCircuit(2) expected.append(gate, [0, 1], []) coupling = CouplingMap.from_line(2, bidirectional=False) pass_ = GateDirection(coupling) self.assertEqual(pass_(circuit), expected) def test_target_parameter_any(self): """Test that a parametrised 2q gate is replaced correctly both if available and not available.""" circuit = QuantumCircuit(2) circuit.rzx(1.5, 0, 1) matching = Target(num_qubits=2) matching.add_instruction(RZXGate(Parameter("a")), {(0, 1): None}) self.assertEqual(GateDirection(None, target=matching)(circuit), circuit) swapped = Target(num_qubits=2) swapped.add_instruction(RZXGate(Parameter("a")), {(1, 0): None}) self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit) def test_target_parameter_exact(self): """Test that a parametrised 2q gate is detected correctly both if available and not available.""" circuit = QuantumCircuit(2) circuit.rzx(1.5, 0, 1) matching = Target(num_qubits=2) matching.add_instruction(RZXGate(1.5), {(0, 1): None}) self.assertEqual(GateDirection(None, target=matching)(circuit), circuit) swapped = Target(num_qubits=2) swapped.add_instruction(RZXGate(1.5), {(1, 0): None}) self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit) def test_target_parameter_mismatch(self): """Test that the pass raises if a gate is not supported due to a parameter mismatch.""" circuit = QuantumCircuit(2) circuit.rzx(1.5, 0, 1) matching = Target(num_qubits=2) matching.add_instruction(RZXGate(2.5), {(0, 1): None}) pass_ = GateDirection(None, target=matching) with self.assertRaises(TranspilerError): pass_(circuit) swapped = Target(num_qubits=2) swapped.add_instruction(RZXGate(2.5), {(1, 0): None}) pass_ = GateDirection(None, target=swapped) with self.assertRaises(TranspilerError): pass_(circuit) def test_coupling_map_control_flow(self): """Test that gates are replaced within nested control-flow blocks.""" circuit = QuantumCircuit(4, 1) circuit.h(0) circuit.measure(0, 0) with circuit.for_loop((1, 2)): circuit.cx(1, 0) circuit.cx(0, 1) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.ecr(3, 2) with else_: with circuit.while_loop((circuit.clbits[0], True)): circuit.rzx(2.3, 2, 1) expected = QuantumCircuit(4, 1) expected.h(0) expected.measure(0, 0) with expected.for_loop((1, 2)): expected.h([0, 1]) expected.cx(0, 1) expected.h([0, 1]) expected.cx(0, 1) with expected.if_test((circuit.clbits[0], True)) as else_: expected.ry(pi / 2, 2) expected.ry(-pi / 2, 3) expected.ecr(2, 3) expected.h([2, 3]) with else_: with expected.while_loop((circuit.clbits[0], True)): expected.h([1, 2]) expected.rzx(2.3, 1, 2) expected.h([1, 2]) coupling = CouplingMap.from_line(4, bidirectional=False) pass_ = GateDirection(coupling) self.assertEqual(pass_(circuit), expected) def test_target_control_flow(self): """Test that gates are replaced within nested control-flow blocks.""" circuit = QuantumCircuit(4, 1) circuit.h(0) circuit.measure(0, 0) with circuit.for_loop((1, 2)): circuit.cx(1, 0) circuit.cx(0, 1) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.ecr(3, 2) with else_: with circuit.while_loop((circuit.clbits[0], True)): circuit.rzx(2.3, 2, 1) expected = QuantumCircuit(4, 1) expected.h(0) expected.measure(0, 0) with expected.for_loop((1, 2)): expected.h([0, 1]) expected.cx(0, 1) expected.h([0, 1]) expected.cx(0, 1) with expected.if_test((circuit.clbits[0], True)) as else_: expected.ry(pi / 2, 2) expected.ry(-pi / 2, 3) expected.ecr(2, 3) expected.h([2, 3]) with else_: with expected.while_loop((circuit.clbits[0], True)): expected.h([1, 2]) expected.rzx(2.3, 1, 2) expected.h([1, 2]) target = Target(num_qubits=4) target.add_instruction(CXGate(), {(0, 1): None}) target.add_instruction(ECRGate(), {(2, 3): None}) target.add_instruction(RZXGate(Parameter("a")), {(1, 2): None}) pass_ = GateDirection(None, target) self.assertEqual(pass_(circuit), expected) def test_target_cannot_flip_message(self): """A suitable error message should be emitted if the gate would be supported if it were flipped.""" gate = Gate("my_2q_gate", 2, []) target = Target(num_qubits=2) target.add_instruction(gate, properties={(0, 1): None}) circuit = QuantumCircuit(2) circuit.append(gate, (1, 0)) pass_ = GateDirection(None, target) with self.assertRaisesRegex(TranspilerError, "'my_2q_gate' would be supported.*"): pass_(circuit) def test_target_cannot_flip_message_calibrated(self): """A suitable error message should be emitted if the gate would be supported if it were flipped.""" target = Target(num_qubits=2) target.add_instruction(CXGate(), properties={(0, 1): None}) gate = Gate("my_2q_gate", 2, []) circuit = QuantumCircuit(2) circuit.append(gate, (1, 0)) circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock()) pass_ = GateDirection(None, target) with self.assertRaisesRegex(TranspilerError, "'my_2q_gate' would be supported.*"): pass_(circuit) def test_target_unknown_gate_message(self): """A suitable error message should be emitted if the gate isn't valid in either direction on the target.""" gate = Gate("my_2q_gate", 2, []) target = Target(num_qubits=2) target.add_instruction(CXGate(), properties={(0, 1): None}) circuit = QuantumCircuit(2) circuit.append(gate, (0, 1)) pass_ = GateDirection(None, target) with self.assertRaisesRegex(TranspilerError, "'my_2q_gate'.*not supported on qubits .*"): pass_(circuit) def test_allows_calibrated_gates_coupling_map(self): """Test that the gate direction pass allows a gate that's got a calibration to pass through without error.""" cm = CouplingMap([(1, 0)]) gate = Gate("my_2q_gate", 2, []) circuit = QuantumCircuit(2) circuit.append(gate, (0, 1)) circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock()) pass_ = GateDirection(cm) self.assertEqual(pass_(circuit), circuit) def test_allows_calibrated_gates_target(self): """Test that the gate direction pass allows a gate that's got a calibration to pass through without error.""" target = Target(num_qubits=2) target.add_instruction(CXGate(), properties={(0, 1): None}) gate = Gate("my_2q_gate", 2, []) circuit = QuantumCircuit(2) circuit.append(gate, (0, 1)) circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock()) pass_ = GateDirection(None, target) self.assertEqual(pass_(circuit), circuit) if __name__ == "__main__": unittest.main()
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * #Comando para que las graficas se vean en el notebook %matplotlib inline qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.draw() circuit.draw(output='mpl') qr = QuantumRegister(2, 'quantum') cr = ClassicalRegister(2, 'classical') circuit.draw() circuit.draw(output='mpl') circuit.h(qr[0]) circuit.draw(output='mpl') circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') circuit.measure(qr, cr) circuit.draw(output='mpl') backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=backend).result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) ''' El IMB_TOKEN se puede obtener en: https://quantum-computing.ibm.com/account ''' #IBMQ.save_account('IMB_TOKEN', overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider(group='open') provider.backends() provider = IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmqx2') job = execute(circuit, backend=qcomp) from qiskit.tools.monitor import job_monitor job_monitor(job) result = job.result() plot_histogram(result.get_counts(circuit))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Necessary imports import numpy as np import matplotlib.pyplot as plt from torch import Tensor from torch.nn import Linear, CrossEntropyLoss, MSELoss from torch.optim import LBFGS from qiskit import QuantumCircuit from qiskit.utils import algorithm_globals from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN from qiskit_machine_learning.connectors import TorchConnector # Set seed for random generators algorithm_globals.random_seed = 42 # Generate random dataset # Select dataset dimension (num_inputs) and size (num_samples) num_inputs = 2 num_samples = 20 # Generate random input coordinates (X) and binary labels (y) X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1 y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1}, y01 will be used for SamplerQNN example y = 2 * y01 - 1 # in {-1, +1}, y will be used for EstimatorQNN example # Convert to torch Tensors X_ = Tensor(X) y01_ = Tensor(y01).reshape(len(y)).long() y_ = Tensor(y).reshape(len(y), 1) # Plot dataset for x, y_target in zip(X, y): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # Set up a circuit feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs) qc = QuantumCircuit(num_inputs) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) qc.draw("mpl") # Setup QNN qnn1 = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # Set up PyTorch module # Note: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn1.num_weights) - 1) model1 = TorchConnector(qnn1, initial_weights=initial_weights) print("Initial weights: ", initial_weights) # Test with a single input model1(X_[0, :]) # Define optimizer and loss optimizer = LBFGS(model1.parameters()) f_loss = MSELoss(reduction="sum") # Start training model1.train() # set model to training mode # Note from (https://pytorch.org/docs/stable/optim.html): # Some optimization algorithms such as LBFGS need to # reevaluate the function multiple times, so you have to # pass in a closure that allows them to recompute your model. # The closure should clear the gradients, compute the loss, # and return it. def closure(): optimizer.zero_grad() # Initialize/clear gradients loss = f_loss(model1(X_), y_) # Evaluate loss function loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer step4 optimizer.step(closure) # Evaluate model and compute accuracy y_predict = [] for x, y_target in zip(X, y): output = model1(Tensor(x)) y_predict += [np.sign(output.detach().numpy())[0]] print("Accuracy:", sum(y_predict == y) / len(y)) # Plot results # red == wrongly classified for x, y_target, y_p in zip(X, y, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # Define feature map and ansatz feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, entanglement="linear", reps=1) # Define quantum circuit of num_qubits = input dim # Append feature map and ansatz qc = QuantumCircuit(num_inputs) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # Define SamplerQNN and initial setup parity = lambda x: "{:b}".format(x).count("1") % 2 # optional interpret function output_shape = 2 # parity = 0, 1 qnn2 = SamplerQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, ) # Set up PyTorch module # Reminder: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn2.num_weights) - 1) print("Initial weights: ", initial_weights) model2 = TorchConnector(qnn2, initial_weights) # Define model, optimizer, and loss optimizer = LBFGS(model2.parameters()) f_loss = CrossEntropyLoss() # Our output will be in the [0,1] range # Start training model2.train() # Define LBFGS closure method (explained in previous section) def closure(): optimizer.zero_grad(set_to_none=True) # Initialize gradient loss = f_loss(model2(X_), y01_) # Calculate loss loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer (LBFGS requires closure) optimizer.step(closure); # Evaluate model and compute accuracy y_predict = [] for x in X: output = model2(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print("Accuracy:", sum(y_predict == y01) / len(y01)) # plot results # red == wrongly classified for x, y_target, y_ in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # Generate random dataset num_samples = 20 eps = 0.2 lb, ub = -np.pi, np.pi f = lambda x: np.sin(x) X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb y = f(X) + eps * (2 * algorithm_globals.random.random([num_samples, 1]) - 1) plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--") plt.plot(X, y, "bo") plt.show() # Construct simple feature map param_x = Parameter("x") feature_map = QuantumCircuit(1, name="fm") feature_map.ry(param_x, 0) # Construct simple feature map param_y = Parameter("y") ansatz = QuantumCircuit(1, name="vf") ansatz.ry(param_y, 0) qc = QuantumCircuit(1) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # Construct QNN qnn3 = EstimatorQNN(circuit=qc, input_params=[param_x], weight_params=[param_y]) # Set up PyTorch module # Reminder: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn3.num_weights) - 1) model3 = TorchConnector(qnn3, initial_weights) # Define optimizer and loss function optimizer = LBFGS(model3.parameters()) f_loss = MSELoss(reduction="sum") # Start training model3.train() # set model to training mode # Define objective function def closure(): optimizer.zero_grad(set_to_none=True) # Initialize gradient loss = f_loss(model3(Tensor(X)), Tensor(y)) # Compute batch loss loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer optimizer.step(closure) # Plot target function plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--") # Plot data plt.plot(X, y, "bo") # Plot fitted line y_ = [] for x in np.linspace(lb, ub): output = model3(Tensor([x])) y_ += [output.detach().numpy()[0]] plt.plot(np.linspace(lb, ub), y_, "g-") plt.show() # Additional torch-related imports import torch from torch import cat, no_grad, manual_seed from torch.utils.data import DataLoader from torchvision import datasets, transforms import torch.optim as optim from torch.nn import ( Module, Conv2d, Linear, Dropout2d, NLLLoss, MaxPool2d, Flatten, Sequential, ReLU, ) import torch.nn.functional as F # Train Dataset # ------------- # Set train shuffle seed (for reproducibility) manual_seed(42) batch_size = 1 n_samples = 100 # We will concentrate on the first 100 samples # Use pre-defined torchvision function to load MNIST train data X_train = datasets.MNIST( root="./data", train=True, download=True, transform=transforms.Compose([transforms.ToTensor()]) ) # Filter out labels (originally 0-9), leaving only labels 0 and 1 idx = np.append( np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples] ) X_train.data = X_train.data[idx] X_train.targets = X_train.targets[idx] # Define torch dataloader with filtered data train_loader = DataLoader(X_train, batch_size=batch_size, shuffle=True) n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) while n_samples_show > 0: images, targets = data_iter.__next__() axes[n_samples_show - 1].imshow(images[0, 0].numpy().squeeze(), cmap="gray") axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(targets[0].item())) n_samples_show -= 1 # Test Dataset # ------------- # Set test shuffle seed (for reproducibility) # manual_seed(5) n_samples = 50 # Use pre-defined torchvision function to load MNIST test data X_test = datasets.MNIST( root="./data", train=False, download=True, transform=transforms.Compose([transforms.ToTensor()]) ) # Filter out labels (originally 0-9), leaving only labels 0 and 1 idx = np.append( np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples] ) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] # Define torch dataloader with filtered data test_loader = DataLoader(X_test, batch_size=batch_size, shuffle=True) # Define and create QNN def create_qnn(): feature_map = ZZFeatureMap(2) ansatz = RealAmplitudes(2, reps=1) qc = QuantumCircuit(2) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # REMEMBER TO SET input_gradients=True FOR ENABLING HYBRID GRADIENT BACKPROP qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, input_gradients=True, ) return qnn qnn4 = create_qnn() # Define torch NN module class Net(Module): def __init__(self, qnn): super().__init__() self.conv1 = Conv2d(1, 2, kernel_size=5) self.conv2 = Conv2d(2, 16, kernel_size=5) self.dropout = Dropout2d() self.fc1 = Linear(256, 64) self.fc2 = Linear(64, 2) # 2-dimensional input to QNN self.qnn = TorchConnector(qnn) # Apply torch connector, weights chosen # uniformly at random from interval [-1,1]. self.fc3 = Linear(1, 1) # 1-dimensional output from QNN def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) # apply QNN x = self.fc3(x) return cat((x, 1 - x), -1) model4 = Net(qnn4) # Define model, optimizer, and loss function optimizer = optim.Adam(model4.parameters(), lr=0.001) loss_func = NLLLoss() # Start training epochs = 10 # Set number of epochs loss_list = [] # Store loss history model4.train() # Set model to training mode for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad(set_to_none=True) # Initialize gradient output = model4(data) # Forward pass loss = loss_func(output, target) # Calculate loss loss.backward() # Backward pass optimizer.step() # Optimize weights total_loss.append(loss.item()) # Store loss loss_list.append(sum(total_loss) / len(total_loss)) print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1])) # Plot loss convergence plt.plot(loss_list) plt.title("Hybrid NN Training Convergence") plt.xlabel("Training Iterations") plt.ylabel("Neg. Log Likelihood Loss") plt.show() torch.save(model4.state_dict(), "model4.pt") qnn5 = create_qnn() model5 = Net(qnn5) model5.load_state_dict(torch.load("model4.pt")) model5.eval() # set model to evaluation mode with no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model5(data) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print( "Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%".format( sum(total_loss) / len(total_loss), correct / len(test_loader) / batch_size * 100 ) ) # Plot predicted labels n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model5.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model5(data[0:1]) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(data[0].numpy().squeeze(), cmap="gray") axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title("Predicted {}".format(pred.item())) count += 1 import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Quantum-Ducks/QuBayes
Quantum-Ducks
# DATA SETUP ''' Note: for more information about our data pre-processing and categorizing into states, see the README in the data folder. We have cited sources for all data used and included a brief description of the states we decided on there.''' import numpy as np import pandas as pd from qubayes_tools import * from probabilities_temp import * ################################################# # COVID-19 EXAMPLES: def build_graph(ntwk_func, filename = None, **kwargs): if filename == None: nodes = ntwk_func(**kwargs) else: nodes = ntwk_func(filename = filename, **kwargs) graph = {} for node in nodes: if node.parents == []: #this is a root node, we just need to calculate probabilities ct = 1 probs = [] got_probs = get_probabilities(node) newkey = "" for state_i in node.states.keys(): state_key = node.name + "_" + state_i if ct == len(node.states.keys()): newkey += state_key else: newkey += state_key + "," probs.append(got_probs[state_key]) ct += 1 graph.update({newkey : ([], probs)}) else: #this is a child node, we need conditional probabilities! cond_probs = [] p_nodes = [] #initialize a list in which to place parent nodes p_names = [] #get names in same order! for anode in nodes: #loop thru all nodes in network if anode.name in node.parents: p_nodes.append(anode) p_names.append(str.join(",",[(anode.name + '_' + s) for s in anode.states.keys()])) cond_prob_dict = get_conditional_probability(node, p_nodes) # i need to write func(node, p_node[0], p_node[1], ... p_node[n]) p_ct = 0 newkey = "" for p_str in generate_parent_str(p_nodes[:]): s_ct = 0 for state_i in node.states.keys(): cond_str = node.name + "_" + state_i + "|" + p_str cond_probs.append(cond_prob_dict[cond_str]) if p_ct == 0: if s_ct == 0: newkey += node.name + "_" + state_i else: newkey += "," + node.name + "_" + state_i s_ct += 1 p_ct += 1 graph.update({newkey : (p_names, cond_probs)}) return graph def get_lesser_model_nodes(filename='data/lesser_model_data.csv'): lesserdata = pd.read_csv(filename) statedataStayHome = {'MarHome' : lesserdata['MarHome'], 'AprHome' : lesserdata['AprHome'], 'MayHome' : lesserdata['MayHome'], 'JunHome' : lesserdata['JunHome']} StayHome = Node("StayHome", np.ndarray.flatten(np.array(pd.DataFrame(data=statedataStayHome))), states = {"No" : 0, "Yes" : 1}) statedataTests = {'MarTest' : lesserdata['MarTest'], 'AprTest' : lesserdata['AprTest'], 'MayTest' : lesserdata['MayTest'], 'JunTest' : lesserdata['JunTest']} Tests = Node("Tests", np.ndarray.flatten(np.array(pd.DataFrame(data=statedataTests))), states = {"GT5" : 0, "LE5" : 1}) statedataCases = {'MarCases' : lesserdata['MarCases'], 'AprCases' : lesserdata['AprCases'], 'MayCases' : lesserdata['MayCases'], 'JunCases' : lesserdata['JunCases']} Cases = Node("Cases", np.ndarray.flatten(np.array(pd.DataFrame(data=statedataCases))), states = {"Inc" : 0, "noInc" : 1}, parents = ["Tests", "StayHome"]) return Cases, Tests, StayHome def get_mallard_model_nodes(filename='data/mallardmodeldata.csv'): mallarddata = pd.read_csv(filename) Cases = Node("Cases", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarCases':mallarddata['MarCases'], 'AprCases':mallarddata['AprCases'], 'MayCases':mallarddata['MayCases'], 'JunCases':mallarddata['JunCases']}))), states = {"Inc" : 0, "Min" : 1, "Mod" : 2, "Maj" : 3}, parents = ["Test", "Mask", "Work", "Rec","Race","Poverty"]) Test = Node("Test", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarTest':mallarddata['MarTest'],'AprTest':mallarddata['AprTest'],'MayTest':mallarddata['MayTest'], 'JuneTest':mallarddata['JunTest']}))), states = {"GT5" : 0, "LE5" : 1}) Mask = Node("Mask", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarMask':mallarddata['MarMask'],'AprMask':mallarddata['AprMask'],'MayMask':mallarddata['MayMask'],'JunMask':mallarddata['JunMask']}))), states = {"No" : 0, "Yes" : 1}) Work = Node("Work", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarWork':mallarddata['MarWork'],'AprWork':mallarddata['AprWork'],'MayWork':mallarddata['MayWork'],'JunWork':mallarddata['JunWork']}))), states = {"Inc" : 0, "Min" : 1, "Mod" : 2, "Maj" : 3}) Rec = Node("Rec", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarRec':mallarddata['MarRec'],'AprRec':mallarddata['AprRec'],'MayRec':mallarddata['MayRec'],'JunRec':mallarddata['JunRec']}))), states = {"Inc" : 0, "Min" : 1, "Mod" : 2, "Maj" : 3}) Death = Node("Death", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarDeath':mallarddata['MarDeath'],'AprDeath':mallarddata['AprDeath'],'MayDeath':mallarddata['MayDeath'],'JunDeath':mallarddata['JunDeath']}))), states = {"Inc" : 0, "notInc" : 1}, parents = ["Cases", "Age"]) Age = Node("Age", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarAge':mallarddata['MarAge'],'AprAge':mallarddata['AprAge'],'MayAge':mallarddata['MayAge'],'JunAge':mallarddata['JunAge']}))), states = {"Old" : 0, "Young" : 1}) return Cases, Test, Mask, Work, Rec, Death, Age def get_alabio_model_nodes(filename='data/alabiomodeldata.csv'): alabiodata = pd.read_csv(filename) Cases = Node("Cases", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarCases':alabiodata['MarCases'], 'AprCases':alabiodata['AprCases'], 'MayCases':alabiodata['MayCases'], 'JunCases':alabiodata['JunCases']}))), states={"Inc":0,"Min":1,"Mod":2,"Maj":3}, parents=["Test", "Mask", "Work", "Rec", "Race", "Poverty"]) Test = Node("Test", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarTest':alabiodata['MarTest'],'AprTest':alabiodata['AprTest'],'MayTest':alabiodata['MayTest'], 'JuneTest':alabiodata['JunTest']}))), states={"GT5" : 0, "LE5" : 1}) Mask = Node("Mask", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarMask':alabiodata['MarMask'],'AprMask':alabiodata['AprMask'],'MayMask':alabiodata['MayMask'],'JunMask':alabiodata['JunMask']}))), states = {"No" : 0, "Yes" : 1}) Work = Node("Work", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarWork':alabiodata['MarWork'],'AprWork':alabiodata['AprWork'],'MayWork':alabiodata['MayWork'],'JunWork':alabiodata['JunWork']}))), states = {"Inc" : 0, "Min" : 1, "Mod" : 2, "Maj" : 3}) Rec = Node("Rec", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarRec':alabiodata['MarRec'],'AprRec':alabiodata['AprRec'],'MayRec':alabiodata['MayRec'],'JunRec':alabiodata['JunRec']}))), states = {"Inc" : 0, "Min" : 1, "Mod" : 2, "Maj" : 3}) Death = Node("Death", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarDeath':alabiodata['MarDeath'],'AprDeath':alabiodata['AprDeath'],'MayDeath':alabiodata['MayDeath'],'JunDeath':alabiodata['JunDeath']}))), states = {"Inc" : 0, "notInc" : 1}, parents = ["Cases", "Age", "Race", "Poverty", "Health"]) Age = Node("Age", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarAge':alabiodata['MarAge'],'AprAge':alabiodata['AprAge'],'MayAge':alabiodata['MayAge'],'JunAge':alabiodata['JunAge']}))), states = {"Old" : 0, "Young" : 1}) Race = Node("Race", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarRace':alabiodata['MarRace'],'AprRace':alabiodata['AprRace'],'MayRace':alabiodata['MayRace'],'JunRace':alabiodata['JunRace']}))), states = {"LE15":0, "15to30":1, "30to45":2, "GT45":3}) Poverty = Node("Poverty", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarPoverty':alabiodata['MarPoverty'],'AprPoverty':alabiodata['AprPoverty'],'MayPoverty':alabiodata['MayPoverty'],'JunPoverty':alabiodata['JunPoverty']}))), states={"LE11":0, "11to13":1, "13to15":2, "GT15":3}) Health = Node("Health", np.ndarray.flatten(np.array(pd.DataFrame(data={'MarHealth':alabiodata['MarHealth'],'AprHealth':alabiodata['AprHealth'],'MayHealth':alabiodata['MayHealth'],'JunHealth':alabiodata['JunHealth']}))), states={"Rare":0, "SomewhatCom":1, "Common":2, "VeryCom":3}) return Cases, Test, Mask, Work, Rec, Death, Age, Race, Poverty, Health ################################################# """ # MAKE YOUR OWN HERE! def MyDataSetup(*input, **kwargs): ########################## # INPUT # # input str filename with data # **kwargs whatever else you need # OUTPUT # # *data tuple of Nodes return data """ print(build_graph(get_mallard_model_nodes)) print(build_graph(get_lesser_model_nodes))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.visualization import dag_drawer q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) dag_drawer(dag)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
import warnings warnings.simplefilter(action='ignore', category=FutureWarning) warnings.simplefilter(action='ignore', category=RuntimeWarning) import pandas as pd import math import numpy as np import scipy.stats as sci from statsmodels.stats.proportion import proportions_ztest from qiskit import execute from qiskit.circuit import ClassicalRegister def assertPhase(backend, quantumCircuit, qubits_to_assert, expected_phases, measurements_to_make, alpha): ## if "qubits to assert" is just a single value, convert it to a list containing the single value if (not isinstance(qubits_to_assert, list)): qubits_to_assert = [qubits_to_assert] ## if "expected phases" is just a single value, convert it to a list containing the single value if (not isinstance(expected_phases, list)): expected_phases = [expected_phases] ## needs to make at least 2 measurements, one for x axis, one for y axis ## realistically we need more for any statistical significance if (measurements_to_make < 2): raise ValueError("Must make at least 2 measurements") ## classical register must be of same length as amount of qubits to assert ## if there is no classical register, add one if (quantumCircuit.num_clbits == 0): quantumCircuit.add_register(ClassicalRegister(len(qubits_to_assert))) elif (quantumCircuit.num_clbits != len(qubits_to_assert)): raise ValueError("QuantumCircuit classical register length not equal to qubits to assert") ## divide measurements to make by 2 as we need to run measurements twice, one for x and one for y measurements_to_make = measurements_to_make // 2 ## copy the circit and set measurement to y axis yQuantumCircuit = measure_y(quantumCircuit.copy(), qubits_to_assert) ## measure the x axis xQuantumCircuit = measure_x(quantumCircuit, qubits_to_assert) ## get y axis results yJob = execute(yQuantumCircuit, backend, shots=measurements_to_make, memory=True) yCounts = yJob.result().get_counts() ## get x axis results xJob = execute(xQuantumCircuit, backend, shots=measurements_to_make, memory=True) xCounts = xJob.result().get_counts() ## make a df to keep track of the predicted angles resDf = pd.DataFrame(columns=['+','i','-','-i']) ## fill the df with the x and y results of each qubit that is being asserted classical_qubit_index = 1 for qubit in qubits_to_assert: plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0 for experiment in xCounts: if (experiment[len(qubits_to_assert)-classical_qubit_index] == '0'): plus_amount += xCounts[experiment] else: minus_amount += xCounts[experiment] for experiment in yCounts: if (experiment[len(qubits_to_assert)-classical_qubit_index] == '0'): i_amount += yCounts[experiment] else: minus_i_amount += yCounts[experiment] df = {'+':plus_amount, 'i':i_amount, '-':minus_amount, '-i':minus_i_amount} resDf = resDf.append(df, ignore_index = True) classical_qubit_index+=1 ## convert the columns to a strict numerical type resDf['+'] = resDf['+'].astype(int) resDf['i'] = resDf['i'].astype(int) resDf['-'] = resDf['-'].astype(int) resDf['-i'] = resDf['-i'].astype(int) #print(f"full df \n {resDf}") xAmount = resDf['-'].tolist() yAmount = resDf['-i'].tolist() # print(f"x amounts {xAmount}") # print(f"y amounts {yAmount}") ## make a dataframe that contains p values of chi square tests to analyse results ## if x and y counts are both 25/25/25/25, it means that we cannot calculate a phase ## we assume that a qubit that is in |0> or |1> position to have 50% chance to fall ## either way, like a coin toss: We treat X and Y results like coin tosses pValues = pd.DataFrame(columns=['X','Y']) pValues['X'] = resDf.apply(lambda row: applyChiSquareX(row, measurements_to_make/2), axis=1) pValues['Y'] = resDf.apply(lambda row: applyChiSquareY(row, measurements_to_make/2), axis=1) ## check p values on chi square test, we use a low value to be sure that ## we only except if we are certain there is an issue with the x, y results pValues = pValues > 0.00001 ## if both pvalues are more than 0.00001, we are pretty certain that the results follow an even distribution ## likely that the qubit is not in the fourier basis (very likely in the |0> or |1> state) pValues.apply(lambda row: assertIfBothTrue(row), axis=1) ## this sequence of operations converts from measured results ## into an angle for phase: ## with 0 ( 0 rad) signifying the |+> state ## with 90 ( pi/2 rad) signifying the |i> state ## with 180 ( pi rad) signifying the |-> state ## with 270 (3 * pi/2 rad) signifying the |-i> state resDf = resDf / measurements_to_make resDf = resDf * 2 resDf = resDf - 1 resDf = np.arccos(resDf) resDf = resDf * 180 resDf = resDf / math.pi ## to get a final result for phase on each qubit: ## we must get the lowest 2 values for each column lowestDf = pd.DataFrame(columns=['lowest','lowest-location','second-lowest','second-lowest-location','estimated-phase']) ## store the lowest value as well as what column it is from lowestDf['lowest'] = resDf.min(axis=1) lowestDf['lowest-location'] = resDf.idxmin(axis=1) ## remove the lowest value from the dataframe lowestDf = lowestDf.apply(lambda row: setLowestCellToNan(row, resDf), axis=1) ## store the second lowest value from the dataframe as well as the column lowestDf['second-lowest'] = resDf.min(axis=1) lowestDf['second-lowest-location'] = resDf.idxmin(axis=1) ## estimate the phase and put it in a new column lowestDf['estimated-phase'] = lowestDf.apply(lambda row: setPhaseEstimate(row), axis=1) ## calculate what the expected row would be for the expected phase #expectedX, expectedY = expectedPhaseToRow(expected_phases[0],measurements_to_make) expectedX = np.zeros(len(expected_phases)).astype(int) expectedY = np.zeros(len(expected_phases)).astype(int) for idx, phase in enumerate(expected_phases): expectedX[idx], expectedY[idx] = expectedPhaseToRow(expected_phases[idx],measurements_to_make) #print(type(expectedX[0])) # print(f"expected x {expectedX}") # print(f"expected y {expectedY}") p_values = [] for i in range(len(qubits_to_assert)): ## set observed X values in a table observedXtable = [xAmount[i],measurements_to_make-xAmount[i]] ## set expected X values in a table expectedXtable = [expectedX[i],measurements_to_make-expectedX[i]] ## set observed Y values in a table observedYtable = [yAmount[i],measurements_to_make-yAmount[i]] ## set expected Y values in a table expectedYtable = [expectedY[i],measurements_to_make-expectedY[i]] xPvalue = sci.chisquare(f_obs=observedXtable, f_exp=expectedXtable)[1] yPvalue = sci.chisquare(f_obs=observedYtable, f_exp=expectedYtable)[1] #print(observedXtable) #print(expectedXtable) #print(sci.chisquare(f_obs=observedXtable, f_exp=expectedXtable)[1]) #print(observedYtable) #print(expectedYtable) print(sci.chisquare(f_obs=observedYtable, f_exp=expectedYtable)[1]) p_values.append(xPvalue) p_values.append(yPvalue) #if (yPvalue != np.NaN and yPvalue <= alpha): # raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in qubit {qubits_to_assert[i]} according to significance level {alpha}")) #if (xPvalue != np.NaN and xPvalue <= alpha): # raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in qubit {qubits_to_assert[i]} according to significance level {alpha}")) holm_bonferroni_correction(p_values, alpha) # ## set observed X values in a table # observedX = [xAmount,measurements_to_make-xAmount] # ## set expected X values in a table # expectedX = [expectedX,measurements_to_make-expectedX] # ## set observed Y values in a table # observedY = [yAmount,measurements_to_make-yAmount] # ## set expected Y values in a table # expectedY = [expectedY,measurements_to_make-expectedY] # print(observedX) # print(expectedX) # print(observedY) # print(expectedY) # print(sci.chisquare(f_obs=observedX, f_exp=expectedX)[1]) # xPvalue = sci.chisquare(f_obs=observedX, f_exp=expectedX)[1] # print(sci.chisquare(f_obs=observedY, f_exp=expectedY)[1]) # yPvalue = sci.chisquare(f_obs=observedY, f_exp=expectedY)[1] # if (yPvalue != np.NaN and yPvalue <= alpha): # raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) # if (xPvalue != np.NaN and xPvalue <= alpha): # raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) ## assert that 2 qubits are equal def assertEqual(backend, quantumCircuit, qubit1, qubit2, measurements_to_make, alpha): ## needs to make at least 2 measurements, one for x axis, one for y axis ## realistically we need more for any statistical significance if (measurements_to_make < 2): raise ValueError("Must make at least 2 measurements") ## classical register must be of same length as amount of qubits to assert ## if there is no classical register, add one if (quantumCircuit.num_clbits == 0): quantumCircuit.add_register(ClassicalRegister(2)) elif (quantumCircuit.num_clbits != 2): raise ValueError("QuantumCircuit classical register must be of length 2") ## divide measurements to make by 3 as we need to run measurements twice, one for x and one for y measurements_to_make = measurements_to_make // 3 ## copy the circit and set measurement to y axis yQuantumCircuit = measure_y(quantumCircuit.copy(), [qubit1, qubit2]) ## measure the x axis xQuantumCircuit = measure_x(quantumCircuit.copy(), [qubit1, qubit2]) ## measure the z axis zQuantumCircuit = measure_z(quantumCircuit, [qubit1, qubit2]) ## get y axis results yJob = execute(yQuantumCircuit, backend, shots=measurements_to_make, memory=True) yMemory = yJob.result().get_memory() yCounts = yJob.result().get_counts() ## get x axis results xJob = execute(xQuantumCircuit, backend, shots=measurements_to_make, memory=True) xMemory = xJob.result().get_memory() xCounts = xJob.result().get_counts() ## get z axis results zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True) zMemory = zJob.result().get_memory() zCounts = zJob.result().get_counts() # xDf = pd.DataFrame(columns=['q0', 'q1']) # yDf = pd.DataFrame(columns=['q0', 'q1']) # zDf = pd.DataFrame(columns=['q0', 'q1']) # for row in yMemory: # yDf = yDf.append({'q0':row[0], 'q1':row[1]}, ignore_index=True) # for row in xMemory: # xDf = xDf.append({'q0':row[0], 'q1':row[1]}, ignore_index=True) # for row in zMemory: # zDf = zDf.append({'q0':row[0], 'q1':row[1]}, ignore_index=True) # yDf = yDf.astype(int) # xDf = xDf.astype(int) # zDf = zDf.astype(int) #yStat, yPvalue = (sci.ttest_ind(yDf['q0'], yDf['q1'])) #xStat, xPvalue = (sci.ttest_ind(xDf['q0'], xDf['q1'])) #zStat, zPvalue = (sci.ttest_ind(zDf['q0'], zDf['q1'])) print(alpha) #print(f"Y p-value {yPvalue}") #print(f"X p-value {xPvalue}") #print(f"Z p-value {zPvalue}") # if (yPvalue != np.NaN and yPvalue <= alpha): # raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) # if (xPvalue != np.NaN and xPvalue <= alpha): # raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) # if (zPvalue != np.NaN and zPvalue <= alpha): # raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) ## make a df to keep track of the predicted angles resDf = pd.DataFrame(columns=['0','1','+','i','-','-i']) ## fill the df with the x and y results of each qubit that is being asserted classical_qubit_index = 1 for qubit in [qubit1,qubit2]: zero_amount, one_amount, plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0,0,0 for experiment in xCounts: if (experiment[2-classical_qubit_index] == '0'): plus_amount += xCounts[experiment] else: minus_amount += xCounts[experiment] for experiment in yCounts: if (experiment[2-classical_qubit_index] == '0'): i_amount += yCounts[experiment] else: minus_i_amount += yCounts[experiment] for experiment in zCounts: if (experiment[2-classical_qubit_index] == '0'): zero_amount += zCounts[experiment] else: one_amount += zCounts[experiment] df = {'0':zero_amount, '1':one_amount, '+':plus_amount, 'i':i_amount, '-':minus_amount,'-i':minus_i_amount} resDf = resDf.append(df, ignore_index = True) classical_qubit_index+=1 ## convert the columns to a strict numerical type resDf['+'] = resDf['+'].astype(int) resDf['i'] = resDf['i'].astype(int) resDf['-'] = resDf['-'].astype(int) resDf['-i'] = resDf['-i'].astype(int) resDf['0'] = resDf['0'].astype(int) resDf['1'] = resDf['1'].astype(int) print(resDf.astype(str)) print(resDf['1'][0].astype(int)) print(resDf['1'][1].astype(int)) print(resDf['-'][0].astype(int)) print(resDf['-'][1].astype(int)) print(resDf['-i'][0].astype(int)) print(resDf['-i'][1].astype(int)) zStat_z, zPvalue = proportions_ztest(count=[resDf['1'][0],resDf['1'][1]], nobs=[measurements_to_make, measurements_to_make], alternative='two-sided') zStat_x, xPvalue = proportions_ztest(count=[resDf['-'][0],resDf['-'][1]], nobs=[measurements_to_make, measurements_to_make], alternative='two-sided') zStat_y, yPvalue = proportions_ztest(count=[resDf['-i'][0],resDf['-i'][1]], nobs=[measurements_to_make, measurements_to_make], alternative='two-sided') print(zPvalue, zStat_z) print(xPvalue, zStat_x) print(yPvalue, zStat_y) if (yPvalue != np.NaN and yPvalue <= alpha): raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) if (xPvalue != np.NaN and xPvalue <= alpha): raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) if (zPvalue != np.NaN and zPvalue <= alpha): raise(AssertionError(f"Null hypothesis rejected, there is a significant enough difference in the qubits according to significance level {alpha}")) # ## apply t test to see if two populations of results on qu bits are expected to from the same population # resDf.apply(lambda row: applyTtest(row), axis=1) def measure_x(circuit, qubitIndexes): cBitIndex = 0 for index in qubitIndexes: circuit.h(index) circuit.measure(index, cBitIndex) cBitIndex+=1 return circuit def measure_y(circuit, qubit_indexes): cBitIndex = 0 for index in qubit_indexes: circuit.sdg(index) circuit.h(index) circuit.measure(index, cBitIndex) cBitIndex+=1 return circuit def measure_z(circuit, qubit_indexes): cBitIndex = 0 for index in qubit_indexes: circuit.measure(index, cBitIndex) cBitIndex+=1 return circuit def setLowestCellToNan(row, resDf): for col in row.index: resDf.iloc[row.name][row[col]] = np.nan return row def setPhaseEstimate(row): overallPhase = 0 if(row['lowest-location'] == '+'): if(row['second-lowest-location'] == 'i'): overallPhase = 0 + row['lowest'] elif (row['second-lowest-location'] == '-i'): overallPhase = 360 - row['lowest'] if (row['lowest'] == 0): overallPhase = 0 elif(row['lowest-location'] == 'i'): if(row['second-lowest-location'] == '+'): overallPhase = 90 - row['lowest'] elif (row['second-lowest-location'] == '-'): overallPhase = 90 + row['lowest'] elif(row['lowest-location'] == '-'): if(row['second-lowest-location'] == 'i'): overallPhase = 180 - row['lowest'] elif (row['second-lowest-location'] == '-i'): overallPhase = 180 + row['lowest'] elif(row['lowest-location'] == '-i'): if(row['second-lowest-location'] == '+'): overallPhase = 270 + row['lowest'] elif (row['second-lowest-location'] == '-'): overallPhase = 270 - row['lowest'] return overallPhase def expectedPhaseToRow(expected_phase, number_of_measurements): # print(expected_phase) # print(number_of_measurements) expected_phase_y = expected_phase - 90 expected_phase_y = expected_phase_y * math.pi expected_phase_y = expected_phase_y / 180 expected_phase_y = np.cos(expected_phase_y) expected_phase_y = expected_phase_y + 1 expected_phase_y = expected_phase_y / 2 expected_phase_y = expected_phase_y * number_of_measurements expected_phase = expected_phase * math.pi expected_phase = expected_phase / 180 expected_phase = np.cos(expected_phase) expected_phase = expected_phase + 1 expected_phase = expected_phase / 2 expected_phase = expected_phase * number_of_measurements # print(f"phase + {expected_phase} ---- phase - {number_of_measurements-expected_phase}") # print(f"phase i {expected_phase_y} ---- phase -i {number_of_measurements-expected_phase_y}") xRes = int(round(number_of_measurements-expected_phase)) yRes = int(round(number_of_measurements-expected_phase_y)) return((xRes, yRes)) def applyChiSquareX(row, expected_amount): observed = [row['+'],row['-']] expected = [expected_amount,expected_amount] return(sci.chisquare(f_obs=observed, f_exp=expected)[1]) def applyChiSquareY(row, expected_amount): observed = [row['i'],row['-i']] expected = [expected_amount,expected_amount] return(sci.chisquare(f_obs=observed, f_exp=expected)[1]) def assertIfBothTrue(row): if row.all(): raise AssertionError("Qubit does not appear to have a phase applied to it!") def holm_bonferroni_correction(p_values, family_wise_alpha): print("holm") p_values = [1 if math.isnan(x) else x for x in p_values] p_values.sort() print(p_values) for i in range(len(p_values)): if (p_values[i] <= (family_wise_alpha/(len(p_values)-i))): print("failed it !") raise(AssertionError(f"Null hypothesis rejected")) # def assertIfExpectedDoNotFitTolerance(row, expected, tolerance): # deltaAngle = (row['estimated-phase'] - expected[row.name] + 180 + 360) % 360 - 180 # print('observed: ' + str(row['estimated-phase'])) # print('predicted: ' + str(expected[row.name])) # print('diff: ' + str(deltaAngle)) # if (abs(deltaAngle) > tolerance): # raise AssertionError(f"The estimated angle ({row['estimated-phase']}) is off the prediction ({expected[row.name]}) +- tolerance value ({tolerance}) specified")
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Non-string identifiers for circuit and record identifiers test""" import unittest from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase class TestAnonymousIds(QiskitTestCase): """Test the anonymous use of registers.""" def test_create_anonymous_classical_register(self): """ClassicalRegister with no name.""" cr = ClassicalRegister(size=3) self.assertIsInstance(cr, ClassicalRegister) def test_create_anonymous_quantum_register(self): """QuantumRegister with no name.""" qr = QuantumRegister(size=3) self.assertIsInstance(qr, QuantumRegister) def test_create_anonymous_classical_registers(self): """Several ClassicalRegister with no name.""" cr1 = ClassicalRegister(size=3) cr2 = ClassicalRegister(size=3) self.assertNotEqual(cr1.name, cr2.name) def test_create_anonymous_quantum_registers(self): """Several QuantumRegister with no name.""" qr1 = QuantumRegister(size=3) qr2 = QuantumRegister(size=3) self.assertNotEqual(qr1.name, qr2.name) def test_create_anonymous_mixed_registers(self): """Several Registers with no name.""" cr0 = ClassicalRegister(size=3) qr0 = QuantumRegister(size=3) # Get the current index count of the registers cr_index = int(cr0.name[1:]) qr_index = int(qr0.name[1:]) cr1 = ClassicalRegister(size=3) _ = QuantumRegister(size=3) qr2 = QuantumRegister(size=3) # Check that the counters for each kind are incremented separately. cr_current = int(cr1.name[1:]) qr_current = int(qr2.name[1:]) self.assertEqual(cr_current, cr_index + 1) self.assertEqual(qr_current, qr_index + 2) def test_create_circuit_noname(self): """Create_circuit with no name.""" qr = QuantumRegister(size=3) cr = ClassicalRegister(size=3) qc = QuantumCircuit(qr, cr) self.assertIsInstance(qc, QuantumCircuit) class TestInvalidIds(QiskitTestCase): """Circuits and records with invalid IDs""" def test_invalid_type_circuit_name(self): """QuantumCircuit() with invalid type name.""" qr = QuantumRegister(size=3) cr = ClassicalRegister(size=3) self.assertRaises(CircuitError, QuantumCircuit, qr, cr, name=1) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/Tojarieh97/VQE
Tojarieh97
import numpy as np np.random.seed(999999) target_distr = np.random.rand(2) # We now convert the random vector into a valid probability vector target_distr /= sum(target_distr) print(target_distr) from qiskit.circuit.library import EfficientSU2 ansatz = EfficientSU2(num_qubits=2, entanglement='linear') print(ansatz.parameters) from qiskit import QuantumCircuitc, ClassicalRegister, QuantumRegister qc = QuantumCircuit(qr, cr) qr = QuantumRegister(1, name="q") cr = ClassicalRegister(1, name='c') from qiskit import QuantumCircuitc, ClassicalRegister, QuantumRegister def get_var_form(params): qr = QuantumRegister(1, name="q") cr = ClassicalRegister(1, name='c') ansatz = EfficientSU2(num_qubits=2, entanglement='linear') ansatz.u3(params[0], params[1], params[2], qr[0]) ansatz.measure(qr, cr[0]) return qc from qiskit import Aer, transpile, assemble backend = Aer.get_backend("qasm_simulator") NUM_SHOTS = 10000 def get_probability_distribution(counts): output_distr = [v / NUM_SHOTS for v in counts.values()] if len(output_distr) == 1: output_distr.append(1 - output_distr[0]) return output_distr def objective_function(params): # Obtain a quantum circuit instance from the paramters qc = get_var_form(params) qc.draw() # Execute the quantum circuit to obtain the probability distribution associated with the current parameters t_qc = transpile(qc, backend) qobj = assemble(t_qc, shots=NUM_SHOTS) result = backend.run(qobj).result() # Obtain the counts for each measured state, and convert those counts into a probability vector output_distr = get_probability_distribution(result.get_counts(qc)) # Calculate the cost as the distance between the output distribution and the target distribution cost = sum([np.abs(output_distr[i] - target_distr[i]) for i in range(2)]) return cost from qiskit.algorithms.optimizers import L_BFGS_B import numpy as np bfgs_optimizer = L_BFGS_B(maxiter=60) # Create the initial parameters (noting that our single qubit variational form has 3 parameters) params = np.random.rand(3) ret = bfgs_optimizer.optimize(num_vars=3, objective_function=objective_function, initial_point=params) # Obtain the output distribution using the final parameters qc = get_var_form(ret[0]) t_qc = transpile(qc, backend) qobj = assemble(t_qc, shots=NUM_SHOTS) counts = backend.run(qobj).result().get_counts(qc) output_distr = get_probability_distribution(counts) print("Target Distribution:", target_distr) print("Obtained Distribution:", output_distr) print("Output Error (Manhattan Distance):", ret[1]) print("Parameters Found:", ret[0])