repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
shell-raiser
from qiskit import * from qiskit import QuantumCircuit, assemble, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * #quantum_widgets import * from math import pi, sqrt from qiskit.visualization import plot_bloch_multivector, plot_histogram qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) %matplotlib inline circuit.draw() circuit.h(0) circuit.draw(output='mpl') circuit.draw() circuit.cx(0,1) #control x 2 qubit operator circuit.draw() circuit.measure(qr,cr) circuit.draw() simulator = Aer.get_backend("qasm_simulator") execute(circuit, backend = simulator) result = execute(circuit, backend = simulator).result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) # load account IBMQ.load_account() provider = IBMQ.get_provider('ibm-q') #below one recommended # Hot fix, for open machines provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider.backends() qcomp = provider.get_backend('ibmq_bogota') 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
from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford, random_clifford qc = QuantumCircuit(3) cliff = random_clifford(2) qc.append(cliff, [0, 1]) qc.ccx(0, 1, 2) qc.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.tools.visualization import circuit_drawer q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram # Create a quantum circuit with 2 qubits # The default initial state of qubits will be |0> or [1,0] qc = QuantumCircuit(3) c1 = 0 c2 = 1 t=2 #Applying the x gate to change a to |1>, b will be |0> itself qc.x(c1) qc.x(c2) qc.x(t) qc.ch(c1,t) qc.cz(c2,t) qc.ch(c1,t) #Draw the circuit qc.draw('mpl') #Get the backend for the circuit to display unitary matrix backend = Aer.get_backend('unitary_simulator') #execute the circuit using the backend out = execute(qc,backend).result().get_unitary() #import qiskit_textbook and display the combined unitary matrix from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ") #Get the backend for the circuit (simulator or realtime system) backend = Aer.get_backend('statevector_simulator') #execute the circuit using the backend out = execute(qc,backend).result().get_statevector() #import qiskit_textbook and display the statevector #from qiskit_textbook.tools import array_to_latex array_to_latex(out, pretext = "\\text{Statevector} = ") #plot the result as a bloch sphere visualization plot_bloch_multivector(out) #execute the circuit and get the plain result out = execute(qc,backend).result() #getting the count of the result counts = out.get_counts() #plotting the histogram plot_histogram(counts)
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (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. """Test Variational Quantum Real Time Evolution algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter, ParameterVector from qiskit_algorithms.gradients import LinCombQGT, DerivativeType, LinCombEstimatorGradient from qiskit.primitives import Estimator from qiskit.utils import algorithm_globals from qiskit.quantum_info import SparsePauliOp, Pauli, Statevector from qiskit_algorithms import TimeEvolutionProblem, VarQRTE from qiskit_algorithms.time_evolvers.variational import ( RealMcLachlanPrinciple, ) from qiskit.circuit.library import EfficientSU2 @ddt class TestVarQRTE(QiskitAlgorithmsTestCase): """Test Variational Quantum Real Time Evolution algorithm.""" def setUp(self): super().setUp() self.seed = 11 np.random.seed(self.seed) def test_time_dependent_hamiltonian(self): """Simple test case with a time dependent Hamiltonian.""" t_param = Parameter("t") hamiltonian = SparsePauliOp(["Z"], np.array(t_param)) x = ParameterVector("x", 3) circuit = QuantumCircuit(1) circuit.rz(x[0], 0) circuit.ry(x[1], 0) circuit.rz(x[2], 0) initial_parameters = np.array([0, np.pi / 2, 0]) def expected_state(time): # possible with pen and paper as the Hamiltonian is diagonal return 1 / np.sqrt(2) * np.array([np.exp(-0.5j * time**2), np.exp(0.5j * time**2)]) final_time = 0.75 evolution_problem = TimeEvolutionProblem(hamiltonian, t_param=t_param, time=final_time) estimator = Estimator() varqrte = VarQRTE(circuit, initial_parameters, estimator=estimator) result = varqrte.evolve(evolution_problem) final_parameters = result.parameter_values[-1] final_state = Statevector(circuit.bind_parameters(final_parameters)).to_dict() final_expected_state = expected_state(final_time) for key, expected_value in final_state.items(): self.assertTrue(np.allclose(final_expected_state[int(key)], expected_value, 1e-02)) def test_run_d_1_with_aux_ops(self): """Test VarQRTE for d = 1 and t = 0.1 with evaluating auxiliary operators and the Forward Euler solver.""" observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) aux_ops = [Pauli("XX"), Pauli("YZ")] d = 1 ansatz = EfficientSU2(observable.num_qubits, reps=d) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) for i in range(len(parameters)): init_param_values[i] = np.pi / 2 init_param_values[0] = 1 time = 0.1 evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops) thetas_expected = [ 0.886841151529636, 1.53852629218265, 1.57099556659882, 1.5889216657174, 1.5996487153364, 1.57018939515742, 1.63950719260698, 1.53853696496673, ] thetas_expected_shots = [ 0.886975892820015, 1.53822607733397, 1.57058096749141, 1.59023223608564, 1.60105707043745, 1.57018042397236, 1.64010900210835, 1.53959523034133, ] with self.subTest(msg="Test exact backend."): algorithm_globals.random_seed = self.seed estimator = Estimator() qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qrte.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] expected_aux_ops = [0.06836996703935797, 0.7711574493422457] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected[i], decimal=2 ) np.testing.assert_array_almost_equal( [result[0] for result in aux_ops], expected_aux_ops ) with self.subTest(msg="Test shot-based backend."): algorithm_globals.random_seed = self.seed estimator = Estimator(options={"shots": 4 * 4096, "seed": self.seed}) qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qrte.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] expected_aux_ops = [ 0.070436, 0.777938, ] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected_shots[i], decimal=2 ) np.testing.assert_array_almost_equal( [result[0] for result in aux_ops], expected_aux_ops, decimal=2 ) def test_run_d_2(self): """Test VarQRTE for d = 2 and t = 1 with RK45 ODE solver.""" observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) d = 2 ansatz = EfficientSU2(observable.num_qubits, reps=d) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) for i in range(len(parameters)): init_param_values[i] = np.pi / 4 estimator = Estimator() qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) param_dict = dict(zip(parameters, init_param_values)) time = 1 var_qrte = VarQRTE(ansatz, param_dict, var_principle, ode_solver="RK45", num_timesteps=25) thetas_expected = [ 0.348407744196573, 0.919404626262464, 1.18189219371626, 0.771011177789998, 0.734384256533924, 0.965289520781899, 1.14441687204195, 1.17231927568571, 1.03014771379412, 0.867266309056347, 0.699606368428206, 0.610788576398685, ] self._test_helper(observable, thetas_expected, time, var_qrte) def test_run_d_1_time_dependent(self): """Test VarQRTE for d = 1 and a time-dependent Hamiltonian with the Forward Euler solver.""" t_param = Parameter("t") time = 1 observable = SparsePauliOp(["I", "Z"], np.array([0, t_param])) x, y, z = [Parameter(s) for s in "xyz"] ansatz = QuantumCircuit(1) ansatz.rz(x, 0) ansatz.ry(y, 0) ansatz.rz(z, 0) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) x_val = 0 y_val = np.pi / 2 z_val = 0 init_param_values[0] = x_val init_param_values[1] = y_val init_param_values[2] = z_val evolution_problem = TimeEvolutionProblem(observable, time, t_param=t_param) thetas_expected = [1.27675647831902e-18, 1.5707963267949, 0.990000000000001] thetas_expected_shots = [0.00534345821469238, 1.56260960200375, 0.990017403734316] # the expected final state is Statevector([0.62289306-0.33467034j, 0.62289306+0.33467034j]) with self.subTest(msg="Test exact backend."): algorithm_globals.random_seed = self.seed estimator = Estimator() qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=100 ) evolution_result = var_qrte.evolve(evolution_problem) parameter_values = evolution_result.parameter_values[-1] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected[i], decimal=2 ) with self.subTest(msg="Test shot-based backend."): algorithm_globals.random_seed = self.seed estimator = Estimator(options={"shots": 4 * 4096, "seed": self.seed}) qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=100 ) evolution_result = var_qrte.evolve(evolution_problem) parameter_values = evolution_result.parameter_values[-1] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected_shots[i], decimal=2 ) def _test_helper(self, observable, thetas_expected, time, var_qrte): evolution_problem = TimeEvolutionProblem(observable, time) evolution_result = var_qrte.evolve(evolution_problem) parameter_values = evolution_result.parameter_values[-1] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal(float(parameter_value), thetas_expected[i], decimal=4) if __name__ == "__main__": unittest.main()
https://github.com/0tt3r/QuaC-qiskit
0tt3r
# -*- coding: utf-8 -*- """This module contains test cases for ensuring gate scheduling is working properly in the library. """ import unittest from qiskit import QuantumCircuit, assemble, transpile from qiskit.test.mock import FakeBogota from quac_qiskit import Quac from quac_qiskit.simulators import list_schedule_experiment class ScheduleTestCase(unittest.TestCase): """Tests QuaC noise model functionality by recovering model parameters with Qiskit fitters """ def setUp(self): # Set up QuaC simulators self.quac_sim = Quac.get_backend("fake_yorktown_density_simulator", t1=True, t2=False, meas=False, zz=False) def test_list_schedule(self): example_circ = QuantumCircuit(5) example_circ.h(0) example_circ.x(2) example_circ.x(0) example_circ.cx(0, 2) example_circ.y(3) example_circ.y(2) example_circ.measure_all() qobj = assemble(transpile(example_circ, FakeBogota()), backend=FakeBogota()) list_scheduled_circ = list_schedule_experiment(qobj.experiments[0], FakeBogota().properties()) expected_gates = ['u3', 'u3', 'u2', 'cx', 'cx', 'cx', 'cx', 'u3', 'barrier', 'measure', 'measure', 'measure', 'measure', 'measure'] expected_times = [1, 1, 1, 72.11111111111111, 513.0, 918.3333333333333, 1359.2222222222222, 1693.4444444444443, 1764.5555555555554, 1764.5555555555554, 1764.5555555555554, 1764.5555555555554, 1764.5555555555554, 1764.5555555555554] index = 0 for gate, time in list_scheduled_circ: self.assertEqual(gate.name, expected_gates[index]) self.assertEqual(time, expected_times[index]) index += 1 if __name__ == '__main__': unittest.main()
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts 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("./") 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="lq") 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"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) print("created zne_qcs (length:", len(zne_qcs), ")") 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-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/murogrande/IBM-cert-exam-study-questions
murogrande
## import some libraries from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute, BasicAer, IBMQ from math import sqrt import qiskit print(qiskit.__qiskit_version__) qc =QuantumCircuit(3,3) qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.h(2) qc.cx(2,0) print(qc.depth()) qc = QuantumCircuit(1) qc.h(0) qc.t(0) simulator = Aer.get_backend('statevector_simulator') result = execute(qc,simulator).result() from qiskit.visualization import plot_bloch_multivector plot_bloch_multivector(result.get_statevector()) qc = QuantumCircuit(2) qc.cx(0,1) ## you won't see the next line in the exam. qc.draw('mpl') #Answer is D qc.draw('mpl',filename='test.png') ## check the folder where the notebook is located qc = QuantumCircuit(2,2) qc.h(0) qc.x(1) qc.measure([0,1],[0,1]) simulator=Aer.get_backend('qasm_simulator') ## Answer C ## here is the check from qiskit.visualization import plot_histogram job = execute(qc,simulator).result() counts = job.get_counts() print(counts) plot_histogram(counts) qreg_a = QuantumRegister(2) qreg_b = QuantumRegister(2) creg = ClassicalRegister(4) qc = QuantumCircuit(qreg_a,qreg_b,creg) qc.x(qreg_a[0]) qc.measure(qreg_a,creg[0:2]) qc.measure(qreg_b,creg[2:4]) simulator= BasicAer.get_backend('qasm_simulator') result= execute(qc,simulator).result() counts = result.get_counts(qc) ## check the answer print(counts) print("The answer is C ") qc.draw('mpl') from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) ##Answer is C qc.draw('png') # import image module from IPython.display import Image ### you won't see the following lines in the exam just the plot # get the image Image(url="random-unitary.png", width=600, height=600) ### in the exam you will just see the image # import image module from IPython.display import Image # get the image Image(url="circui1.png", width=300, height=300) ### in the exam you will just see the image # A. '''OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[2]; h.q[0]; barrier (q[0],q[1]); z.q[1]; barrier (q[0], q[1]); measure (q[0], c[0]); measure (q[1], c[1]); ''' # B qc = QuantumCircuit(2,2) qc.h(q[0]) qc.barrier(q[0],q[1]) qc.z(q[1]) qc.barrier(q[0],q[1]) m = measure(q[0] -> c[0]) m += measure(q[1] -> c[1]) qc=qc+m # C qc = QuantumCircuit(2,2) qc.h(0) qc.barrier(0,1) qc.z(1) qc.barrier(0,1) qc.measure([0,1],[0,1]) #D qc = QuantumCircuit(2,2) qc.h(q[0]) qc.barrier(q[0],q[1]) qc.z(q[1]) qc.barrier(q[0],q[1]) m = measure(q[0], c[0]) m = measure(q[1], c[1]) qc=qc+m ### you won't see the following lines of code in the exam from IPython.display import Image Image(url="circui2.png", width=150, height=150) # A qr = QuantumRegister(2,'q') a = QuantumRegister(1,'a') cr = ClassicalRegister(3,'c') qc = QuantumCircuit(qr,a,cr) qc.h(qr[0:2]) qc.x(a[0]) # B qr = QuantumRegister(2,'q') a = QuantumRegister (1,'a') cr = ClassicalRegister(3,'c') qc = QuantumCircuit(cr,a,qr) qc.h(qr[0:2]) qc.x(a[0]) #C qr = QuantumRegister(2,'q') a = QuantumRegister (1,'a') cr = ClassicalRegister(3,'c') qc = QuantumCircuit(qr,a,cr) qc.h(qr[0:1]) qc.x(a[0]) #D qr = QReg(2,'q') a = QReg (1,'a') cr = CReg(3,'c') qc = QuantumCircuit(qr,a,cr) qc.h(qr[0:2]) qc.x(a[0]) from qiskit.tools.monitor import * provider = IBMQ.load_account() #provider.backends() ## this line of code can be important becuase it could be a question of your exam. #In other words, how do you know the backends of the provider? backend= provider.get_backend('ibmq_qasm_simulator') qr = QuantumRegister(2) cr= ClassicalRegister(2) qc = QuantumCircuit(qr,cr) qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.measure(qr,cr) job = execute(qc,backend) job.status() job_monitor(job) #### another could be job_watcher for jupyternoote book from qiskit.tools.jupyter import job_watcher %qiskit_job_watcher job = backend.retrieve_job('61f20ee81faa0605383485a7') result = job.result() counts = result.get_counts() print(counts) qc = QuantumCircuit(3) qc.initialize('01',[0,2]) qc.draw() print(qc.decompose()) from qiskit.visualization import plot_error_map, plot_gate_map backend = provider.get_backend('ibmq_quito') plot_error_map(backend) plot_gate_map(backend) #A from qiskit import QuantumCircuit, Aer, execute from math import pi qc = QuantumCircuit(2) qc.crz(pi,0,1) qc.crz(-pi,0,1) u_sim = Aer.get_backend('unitary_simulator') unitary = execute(qc,u_sim).result().get_unitary() print(unitary) #B from qiskit import QuantumCircuit, Aer, execute from math import pi qc = QuantumCircuit(2) qc.crz(pi,0,1) qc.cp(pi,0,1) u_sim = Aer.get_backend('unitary_simulator') unitary = execute(qc,u_sim).result().get_unitary() print(unitary) #C from qiskit import QuantumCircuit, Aer, execute from math import pi qc = QuantumCircuit(2) qc.cz(0,1) qc.cz(1,0) u_sim = Aer.get_backend('unitary_simulator') unitary = execute(qc,u_sim).result().get_unitary() print(unitary) qc.draw() #D from qiskit import QuantumCircuit, Aer, execute from math import pi qc = QuantumCircuit(2) qc.cz(0,1) qc.cp(pi,0,1) u_sim = Aer.get_backend('unitary_simulator') unitary = execute(qc,u_sim).result().get_unitary() print(unitary) import qiskit.tools.jupyter %qiskit_backend_overview from qiskit import QuantumCircuit qc = QuantumCircuit(3) #insert code fragment here #Output ### you won't see the following lines of code in the exam, just focus on the figure from IPython.display import Image Image(url="imageassesment1.png", width=350, height=350) #A qc.measure_all() #B qc = QuantumCircuit(3) qc.measure() #C qc = QuantumCircuit(3) qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) #D qc = QuantumCircuit(3) for n in range(len(qc.qubits)): qc.measure(n,n) qc.qubits ## here you need to display each line or lines of code before each barrier in the Qsphere, the question is about #to put in order the sequence of states that will appear in the Qsphere. qc = QuantumCircuit(3) qc.x(1) qc.barrier() qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.z(1) qc.barrier() qc.h(0) qc.h(1) qc.h(2) qc.draw('mpl') from qiskit.visualization import plot_state_qsphere simulator= Aer.get_backend('statevector_simulator') result = execute(qc,simulator).result() statevector = result.get_statevector(qc) plot_state_qsphere(statevector) from qiskit import BasicAer, Aer, execute qc = QuantumCircuit(1) qc.h(0) #insert code fragment here print(unitary) #A simulator = BasicAer.get_backend('unitary_simulator') unitary = execute(qc,simulator).get_unitary(qc) #B simulator = Aer.get_backend('unitary_simulator') result = execute(qc,simulator).result() unitary = result.get_unitary(qc) #C simulator = Aer.get_backend('statevector_simulator') result = execute(qc,simulator).result() unitary = result.get_matrix_result(qc) #D simulator = BasicAer.get_backend('statevector_simulator') result = execute(qc,simulator).result() unitary = result.get_unitary(qc) #E simulator = BasicAer.get_backend('unitary_simulator') result = execute(qc,simulator).result() unitary = result.get_unitary() from qiskit.visualization import plot_bloch_vector from math import pi, sqrt plot_bloch_vector(vector) #A vector = [1,-1,0] #B vector = [pi/2,-pi/4,0] #C vector = [1/sqrt(2),-1/sqrt(2),0] #D vector = [1/sqrt(2),-1/sqrt(2),-1] from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(3) qc.h(0) #qc.z(0) qc.x(1) qc.cx(0,1) qc.x(2) qc.cx(1,2) backend = BasicAer.get_backend('statevector_simulator') job = execute(qc, backend).result() statevector= job.get_statevector() plot_state_qsphere(statevector) qc = QuantumCircuit(1) qc.x(0) qc.h(0) simulator = Aer.get_backend('unitary_simulator') job = execute(qc,simulator) result = job.result() outputstate = result.get_unitary(qc,1) print(outputstate) qc = QuantumCircuit(3,3) qc.h([0,1,2]) qc.barrier() qc.measure([0,1,2],range(3)) qc.draw() print(qc.qasm()) qasm_sim = Aer.get_backend('qasm_simulator') qc= QuantumCircuit(3) qc.x([0,1,2]) qc.ccx(0,1,2) qc.measure_all() result = execute(qc,qasm_sim).result() counts = result.get_counts() print(counts) qc= QuantumCircuit(3) qc.ct() from qiskit.quantum_info import DensityMatrix matrix1 = [ [1,0],[0,0] ] matrix2 = [ [0.5,0.5],[0.5,0.5] ] #A result= DensityMatrix.tensor(matrix1,matrix2) print(result) #B matrix1 = DensityMatrix(matrix1) print(matrix1.tensor(matrix2)) #C print(matrix1.tensor(matrix2)) #D print(DensityMatrix.tensor(matrix1,matrix2)) from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.cx(0,1) qc.z(0) simulator = BasicAer.get_backend('statevector_simulator') job = execute(qc,simulator).result() statevector = job.get_statevector() plot_state_city(statevector) qc = QuantumCircuit(1) #A #qc.ry(pi/2,0) #qc.s(0) #qc.rx(pi/2,0) #B #qc.ry(pi/2,0) #qc.rx(pi/2,0) #qc.s(0) #C #qc.s(0) #qc.ry(pi/2,0) #qc.rx(pi/2,0) #D qc.rx(pi/2,0) qc.s(0) qc.ry(pi/2,0) qc.measure_all() simulator = BasicAer.get_backend('qasm_simulator') job = execute(qc,simulator).result() counts = job.get_counts() print(counts) from qiskit.quantum_info import DensityMatrix qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc1= QuantumCircuit(2) qc1.h(0) qc1.x(1) qc1.cx(0,1) #qc.draw('mpl') rho_qc=DensityMatrix.from_instruction(qc) rho_qc.draw() rho1= DensityMatrix.from_instruction(qc1) rho1.draw() qc1new = qc1.decompose() qc1new.draw() #tensor1 = DensityMatrix.from_label('[[0,1],[1,0]]') qc = QuantumCircuit(2) #v1,v2 = [0,1],[0,1] v = [1/sqrt(2),0,0,1/sqrt(2)] qc.initialize(v,[0,1]) qc.draw(output='mpl') simulator = Aer.get_backend('statevector_simulator') result = execute(qc, simulator).result() statevector = result.get_statevector() print(statevector) from qiskit.circuit.library import CXGate ccx = CXGate().control() qc = QuantumCircuit(3) qc.append(ccx,[0,1,2]) qc.draw() from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute qc= QuantumCircuit(3) qc.barrier() qc.barrier([0]) qc.draw() qc = QuantumCircuit.from_qasm_file('myfile.qasm') qc.measure_all() qc.draw(output='latex_source') from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere, plot_state_paulivec, plot_state_city, plot_bloch_vector, plot_state_hinton, plot_bloch_multivector stavec = Statevector.from_label('001') plot_state_paulivec(stavec) import qiskit.tools.jupyter %qiskit_version_table import qiskit.tools.jupyter %qiskit_backend_overview
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
https://github.com/GBisi/QiskitFallFest2023
GBisi
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit from qiskit import(QuantumCircuit, QuantumRegister, ClassicalRegister, transpile) from qiskit.visualization import plot_histogram, plot_gate_map from qiskit.quantum_info import Statevector from qiskit.circuit.library import QFT from qiskit_aer import AerSimulator from qiskit_ibm_provider import IBMProvider plt.style.use('default') #IBMProvider.save_account('YOUR_TOKEN',overwrite=True) provider = IBMProvider(instance="ibm-q/open/main") print(provider.backends(min_num_qubits=5, simulator=False, operational=True)) print(provider.backends(min_num_qubits=5, simulator=True, operational=True)) backend = provider.get_backend("ibm_lagos") backend.status() props = backend.properties() def describe_qubit(qubit, properties): """Print a string describing some of reported properties of the given qubit.""" # Conversion factors from standard SI units us = 1e6 ns = 1e9 GHz = 1e-9 print("Qubit {0} has a \n" " - T1 time of {1} microseconds\n" " - T2 time of {2} microseconds\n" " - U2 gate error of {3}\n" " - U2 gate duration of {4} nanoseconds\n" " - resonant frequency of {5} GHz".format( qubit, properties.t1(qubit) * us, properties.t2(qubit) * us, properties.gate_error('x', qubit), properties.gate_length('x', qubit) * ns, properties.frequency(qubit) * GHz)) describe_qubit(0, props) plot_gate_map(backend) simulator = AerSimulator() backendSimulator = AerSimulator.from_backend(backend) qr = QuantumRegister(2, 'q') cr = ClassicalRegister(2, 'c') circuit = QuantumCircuit(qr, cr,name="bell state") circuit.h(0) circuit.cx(0,1) circuit.draw('mpl') vector=Statevector(circuit) display(vector.draw('latex')) circuit = QuantumCircuit(qr, cr,name="bell state") circuit.h(0) circuit.cx(0,1) circuit.measure([0,1],[0,1]) circuit.draw('mpl') counts=simulator.run(circuit,shots=1000).result().get_counts() display(counts) plot_histogram(counts) circuit = QuantumCircuit(qr, cr,name="bell state") circuit.h(0) circuit.cx(0,1) circuit.measure([0,1],[0,1]) circuit.draw('mpl') layout=[0,1] circuitTranspiled=transpile(circuit,backendSimulator,initial_layout=layout,optimization_level=1) circuitTranspiled.draw('mpl') counts=backendSimulator.run(circuitTranspiled,shots=1000).result().get_counts() display(counts) plot_histogram(counts) layout=[0,6] circuitTranspiled=transpile(circuit,backendSimulator,initial_layout=layout,optimization_level=1) circuitTranspiled.draw('mpl') counts=backendSimulator.run(circuitTranspiled,shots=1000).result().get_counts() display(counts) plot_histogram(counts) from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService(channel="ibm_quantum") backend = service.backend("ibmq_qasm_simulator") #backend = provider.get_backend("ibmq_qasm_simulator") from qiskit.circuit.random import random_circuit circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1) circuit.draw("mpl") from qiskit_ibm_runtime import Sampler sampler = Sampler(backend=backend) #from qiskit.primitives import Sampler #sampler = Sampler() job = sampler.run(circuit) print(f">>> Job ID: {job.job_id()}") print(f">>> Job Status: {job.status()}") result = job.result() print(f">>> {result}") print(f" > Quasi-probability distribution: {result.quasi_dists[0]}") print(f" > Metadata: {result.metadata[0]}") from qiskit_ibm_runtime import Options options = Options() options.optimization_level = 1 options.execution.shots = 2048 sampler = Sampler(backend=backend, options=options) job=sampler.run(circuit) print(f">>> Job ID: {job.job_id()}") print(f">>> Job Status: {job.status()}") result = job.result() print(f">>> Metadata: {result.metadata[0]}") from qiskit_aer.noise import NoiseModel device = provider.get_backend("ibm_lagos") noise_model = NoiseModel.from_backend(device) coupling_map = device.configuration().coupling_map basis_gates=device.configuration().basis_gates options_with_nm = Options() options_with_nm.simulator = { "noise_model": noise_model, "basis_gates": basis_gates, "coupling_map": coupling_map, "seed_simulator": 42 } # Set number of shots, optimization_level and resilience_level options_with_nm.execution.shots = 1000 options_with_nm.optimization_level = 0 # no optimization options_with_nm.resilience_level = 1 # M3 for Sampler and T-REx for Estimator sampler = Sampler(backend=backend, options=options_with_nm) job = sampler.run(circuit) print(f">>> Job ID: {job.job_id()}") print(f">>> Job Status: {job.status()}") result=job.result() print(f" > Quasi-probability distribution: {result.quasi_dists[0]}") plot_histogram(result.quasi_dists[0]) circuitList=[] for t in np.linspace(0,10000,101): circuit = QuantumCircuit(1, 1) circuit.x(0) #circuit.h(0) circuit.barrier() for i in range(int(t)): circuit.id(0) circuit.barrier() #circuit.h(0) circuit.measure(0,0) circuitList.append(circuit) circuitListTranspiled=transpile(circuitList,backendSimulator,initial_layout=[0],optimization_level=0) countsList=backendSimulator.run(circuitListTranspiled,shots=1000).result().get_counts() probabiltyVec=[] for counts in countsList: probabiltyVec.append(counts.get('1')/1000) timeVec=np.linspace(0,10000,101)* props.gate_length('id', 0) *10**6 plt.plot(timeVec,probabiltyVec) plt.xlabel('Time [$\mu$s]') plt.ylabel('$p_1$') plt.show() def func(x, amp, tau,c): return amp* np.exp(-x/tau)+c popt, pcov = curve_fit(func, timeVec, probabiltyVec) # scipy's curve fitting tool print(popt) plt.plot(timeVec,probabiltyVec) plt.plot(timeVec, func(timeVec, *popt), label="Fitted Curve") plt.xlabel('Time [$\mu$s]') plt.ylabel('$p_1$') plt.legend() plt.show() transpile(QFT(4,do_swaps=True,inverse=False,insert_barriers=True),simulator).draw('mpl') backend = provider.get_backend("ibm_brisbane") plot_gate_map(backend,figsize=(16,10)) backendSimulator = AerSimulator.from_backend(backend) circuitQFT=QFT(5,do_swaps=True,inverse=False) circuitQFT.draw('mpl') nQubit=8 qr = QuantumRegister(nQubit, 'q') circuit = QuantumCircuit(qr,name=" QFT calculation") #circuit.x(4) for i in range(nQubit): circuit.h(i) circuit.barrier() circuit.append(QFT(nQubit,do_swaps=True,inverse=True),range(nQubit)) circuit.draw('mpl') vector=Statevector(circuit) display( vector.draw('latex') ) circuit.measure_all() circuit.draw('mpl') layout=[0,34,4,8,100,45,12,5] circuitTranspiled=transpile(circuit,backendSimulator,initial_layout=layout,optimization_level=1) #circuitTranspiled.draw('mpl') # NON ESEGUIRE!!!!! counts=backendSimulator.run(circuitTranspiled,shots=1000).result().get_counts() layout=[0,1,2,3,4,5,6,7] circuitTranspiled=transpile(circuit,backendSimulator,initial_layout=layout,optimization_level=1) #circuitTranspiled.draw('mpl') counts=backendSimulator.run(circuitTranspiled,shots=1000).result().get_counts() #display(counts) plot_histogram(counts,figsize=(26,6)) nQubit=8 qr = QuantumRegister(nQubit, 'q') circuit = QuantumCircuit(qr,name=" QFT calculation") circuit.x(3) circuit.append(QFT(nQubit,do_swaps=False,inverse=False),range(nQubit)) circuit.barrier() circuit.append(QFT(nQubit,do_swaps=False,inverse=True),range(nQubit)) circuit.barrier() circuit.append(QFT(nQubit,do_swaps=False,inverse=False),range(nQubit)) circuit.barrier() circuit.append(QFT(nQubit,do_swaps=False,inverse=True),range(nQubit)) circuit.measure_all() layout=[0,1,2,3,4,5,6,7] circuitTranspiled=transpile(circuit,backendSimulator,initial_layout=layout,optimization_level=1) counts=backendSimulator.run(circuitTranspiled,shots=1000).result().get_counts() plot_histogram(counts,figsize=(40,6)) from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService(channel="ibm_quantum") backend = service.backend("ibmq_qasm_simulator") from qiskit.circuit.random import random_circuit circuit = random_circuit(2, 2, seed=0).decompose(reps=1) display(circuit.draw("mpl")) from qiskit.quantum_info import SparsePauliOp observable = SparsePauliOp("XZ") print(f">>> Observable: {observable.paulis}") from qiskit_ibm_runtime import Estimator estimator = Estimator(backend=backend) job = estimator.run(circuit, observable) print(f">>> Job ID: {job.job_id()}") print(f">>> Job Status: {job.status()}") result = job.result() print(f">>> {result}") print(f" > Expectation value: {result.values[0]}") circuits = ( random_circuit(2, 2, seed=0).decompose(reps=1), random_circuit(2, 2, seed=1).decompose(reps=1), ) observables = ( SparsePauliOp("XZ"), SparsePauliOp("IY"), ) job = estimator.run(circuits, observables) print(f">>> Job ID: {job.job_id()}") print(f">>> Job Status: {job.status()}") result = job.result() [display(cir.draw("mpl")) for cir in circuits] print(f">>> Observables: {[obs.paulis for obs in observables]}") print(f">>> Expectation values: {result.values.tolist()}") from qiskit.circuit.library import RealAmplitudes circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1) observable = SparsePauliOp("ZI") parameter_values = [0, 1, 2, 3, 4, 5] job = estimator.run(circuit, observable, parameter_values) print(f">>> Job ID: {job.job_id()}") print(f">>> Job Status: {job.status()}") result = job.result() display(circuit.draw("mpl")) print(f">>> Observable: {observable.paulis}") print(f">>> Parameter values: {parameter_values}") print(f">>> Expectation value: {result.values[0]}") # General imports import time import numpy as np # Pre-defined ansatz circuit and operator class for Hamiltonian from qiskit.circuit.library import EfficientSU2 from qiskit.quantum_info import SparsePauliOp # The IBM Qiskit Runtime / Primitives #from qiskit_ibm_runtime import QiskitRuntimeService #from qiskit_ibm_runtime import Estimator, Session from qiskit.primitives import Estimator # SciPy minimizer routine from scipy.optimize import minimize # Plotting functions import matplotlib.pyplot as plt hamiltonian = SparsePauliOp.from_list( [("YZ", 0.3980), ("ZI", -0.3980), ("ZZ", -0.0113), ("XX", 0.1810)] ) ansatz = EfficientSU2(hamiltonian.num_qubits) ansatz.draw("mpl") transpile(ansatz,simulator).draw('mpl') num_params = ansatz.num_parameters num_params def cost_func(params, ansatz, hamiltonian, estimator): """Return estimate of energy from estimator Parameters: params (ndarray): Array of ansatz parameters ansatz (QuantumCircuit): Parameterized ansatz circuit hamiltonian (SparsePauliOp): Operator representation of Hamiltonian estimator (Estimator): Estimator primitive instance Returns: float: Energy estimate """ energy = estimator.run(ansatz, hamiltonian, parameter_values=params).result().values[0] return energy x0 = 2 * np.pi * np.random.random(num_params) estimator = Estimator(options={"shots": int(1e4)}) res = minimize(cost_func, x0, args=(ansatz, hamiltonian, estimator), method="cobyla") display(res) def build_callback(ansatz, hamiltonian, estimator, callback_dict): """Return callback function that uses Estimator instance, and stores intermediate values into a dictionary. Parameters: ansatz (QuantumCircuit): Parameterized ansatz circuit hamiltonian (SparsePauliOp): Operator representation of Hamiltonian estimator (Estimator): Estimator primitive instance callback_dict (dict): Mutable dict for storing values Returns: Callable: Callback function object """ def callback(current_vector): """Callback function storing previous solution vector, computing the intermediate cost value, and displaying number of completed iterations and average time per iteration. Values are stored in pre-defined 'callback_dict' dictionary. Parameters: current_vector (ndarray): Current vector of parameters returned by optimizer """ # Keep track of the number of iterations callback_dict["iters"] += 1 # Set the prev_vector to the latest one callback_dict["prev_vector"] = current_vector # Compute the value of the cost function at the current vector callback_dict["cost_history"].append( estimator.run(ansatz, hamiltonian, parameter_values=current_vector).result().values[0] ) # Grab the current time current_time = time.perf_counter() # Find the total time of the execute (after the 1st iteration) if callback_dict["iters"] > 1: callback_dict["_total_time"] += current_time - callback_dict["_prev_time"] # Set the previous time to the current time callback_dict["_prev_time"] = current_time # Compute the average time per iteration and round it time_str = ( round(callback_dict["_total_time"] / (callback_dict["iters"] - 1), 2) if callback_dict["_total_time"] else "-" ) # Print to screen on single line print( "Iters. done: {} [Avg. time per iter: {}]".format(callback_dict["iters"], time_str), end="\r", flush=True, ) return callback callback_dict = { "prev_vector": None, "iters": 0, "cost_history": [], "_total_time": 0, "_prev_time": None,} estimator = Estimator(options={"shots": int(1e4)}) callback = build_callback(ansatz, hamiltonian, estimator, callback_dict) res = minimize(cost_func,x0,args=(ansatz, hamiltonian, estimator),method="cobyla",callback=callback) all(callback_dict["prev_vector"] == res.x) callback_dict["iters"] == res.nfev fig, ax = plt.subplots() ax.plot(range(callback_dict["iters"]), callback_dict["cost_history"]) ax.set_xlabel("Iterations") ax.set_ylabel("Cost"); # General imports import time import numpy as np # The IBM Qiskit Runtime / Primitives from qiskit.primitives import Sampler # SciPy minimizer routine from scipy.optimize import minimize # Datasets from sklearn.datasets import make_moons # Plotting functions import matplotlib.pyplot as plt # Set random seeds np.random.seed(42) # number of samples N=500 # Let's use the Moons dataset X, Y = make_moons(n_samples=N, noise=0.1) c = ["#1f77b4" if y_ == 0 else "#ff7f0e" for y_ in Y] # colours for each class #plt.axis("off") plt.scatter(X[:, 0], X[:, 1], c=c) plt.show() display(X,Y) from qiskit.circuit import ParameterVector # data re-uploading classifier circuit L=5 x=ParameterVector('x',2) thetas = ParameterVector('θ',3*L) qr = QuantumRegister(1, name="q") cr = ClassicalRegister(1, name='c') ansatz = QuantumCircuit(qr, cr) for k in range(L): ansatz.u(x[0],x[1],0.0,qr) ansatz.u(thetas[3*k+0], thetas[3*k+1], thetas[3*k+2], qr) # su(2) rotation ansatz.measure(qr, cr) ansatz.draw('mpl') num_params = ansatz.num_parameters display(num_params) params0 = 2 * np.pi * np.random.random(3*L) circuit=ansatz.assign_parameters({x:X[0], thetas:params0}) circuit.draw('mpl') sampler=Sampler() def loss(params, ansatz, x , y , sampler): """Return the loss for a pattern Parameters: params (ndarray): Array of ansatz parameters ansatz (QuantumCircuit): Parameterized ansatz circuit x (numpyArray): Array of the pattern features y (integer): Class of the pattern 0 or 1 sampler (Estimator): Sampler primitive instance Returns: float: loss function (cost function) """ parameter_values=np.concatenate((x,params)) job = sampler.run(ansatz, parameter_values=parameter_values) loss = 1 - job.result().quasi_dists[0].get(y) return loss def cost_func( params, ansatz, trainingX , trainingY , sampler): N=len(trainingY) return sum(loss(params,ansatz,trainingX[k],trainingY[k],sampler) for k in range(N))/N def predict(params,x,ansatz,sampler): if loss(params,ansatz,x,0,sampler) < 0.5: return 0 else: return 1 cost_func(params0,ansatz,X,Y,sampler) Ypred = [predict(params0,x,ansatz,sampler) for x in X] c = ["#1f77b4" if y == 0 else "#ff7f0e" for y in Y] # colours for each class cpred = ["#1f77b4" if y == 0 else "#ff7f0e" for y in Ypred] # colours for each class plt.figure(figsize=(15,5)) plt.subplot(1,2,1) plt.axis("off") plt.title("true") plt.scatter(X[:, 0], X[:, 1], c=c) plt.subplot(1,2,2) plt.axis("off") plt.title("predicted") plt.scatter(X[:, 0], X[:, 1], c=cpred) plt.show() trainingX=X[0:100] trainingY=Y[0:100] res = minimize(cost_func, params0, args=(ansatz, trainingX , trainingY , sampler), method="cobyla") res.fun paramsOpt=res.x Ypred = [predict(paramsOpt,x,ansatz,sampler) for x in X[200:]] c = ["#1f77b4" if y == 0 else "#ff7f0e" for y in Y[200:]] # colours for each class cpred = ["#1f77b4" if y == 0 else "#ff7f0e" for y in Ypred] # colours for each class plt.figure(figsize=(15,5)) plt.subplot(1,2,1) plt.axis("off") plt.title("true") plt.scatter(X[200:, 0], X[200:, 1], c=c) plt.subplot(1,2,2) plt.axis("off") plt.title("predicted") plt.scatter(X[200:, 0], X[200:, 1], c=cpred) plt.show() from qutip import basis,Bloch, expect, sigmax,sigmay,sigmaz #import qutip as qt L=5 x=ParameterVector('x',2) thetas = ParameterVector('θ',3*L) qr = QuantumRegister(1, name="q") cr = ClassicalRegister(1, name='c') qc = QuantumCircuit(qr, cr) for k in range(L): qc.u(x[0],x[1],0.0,qr) qc.u(thetas[3*k+0], thetas[3*k+1], thetas[3*k+2], qr) # su(2) rotation def blochPoints(X,Y,params,ansatz): xp1=[] yp1=[] zp1=[] xp0=[] yp0=[] zp0=[] for i in range(len(X)): circuit=ansatz.assign_parameters({x:X[i], thetas:params}) state=Statevector(circuit) pnt=state[0]*basis(2,0)+state[1]*basis(2,1) if Y[i]==0: xp0.append(expect(sigmax(),pnt)) yp0.append(expect(sigmay(),pnt)) zp0.append(expect(sigmaz(),pnt)) else: xp1.append(expect(sigmax(),pnt)) yp1.append(expect(sigmay(),pnt)) zp1.append(expect(sigmaz(),pnt)) return [[xp0,yp0,zp0],[xp1,yp1,zp1]] b1=Bloch() b2=Bloch() b1.add_points(blochPoints(X[200:300],Y[200:300],params0,qc)[0]) b1.add_points(blochPoints(X[200:300],Y[200:300],params0,qc)[1]) b2.add_points(blochPoints(X[200:300],Y[200:300],paramsOpt,qc)[0]) b2.add_points(blochPoints(X[200:300],Y[200:300],paramsOpt,qc)[1]) b1.show() b2.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # 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. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/Qiskit/feedback
Qiskit
import numpy as np import qiskit from qiskit import QuantumCircuit from qiskit import transpile from qiskit.providers.fake_provider import FakeManhattanV2 from qiskit.circuit.library import * from qiskit.synthesis import * from qiskit.quantum_info import * from qiskit.synthesis.linear import random_invertible_binary_matrix cliff = random_clifford(50) device = FakeManhattanV2() # 65 qubits num_qubits = device.num_qubits coupling_map = device.coupling_map qc = synth_clifford_greedy(cliff) print(f"original circuit has: " f"2q-depth {qc.depth(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"2q-count {qc.size(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"1q-count {qc.size(filter_function=lambda x: x.operation.num_qubits == 1)}. ") qc_trans = transpile(qc, basis_gates = ['rz', 'sx', 'cx'], coupling_map = edges, optimization_level = 3) print(f"transpiled circuit has: " f"2q-depth {qc_trans.depth(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"2q-count {qc_trans.size(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"1q-count {qc_trans.size(filter_function=lambda x: x.operation.num_qubits == 1)}. ") qc_lnn = synth_clifford_depth_lnn(cliff).decompose() print(f"LNN circuit has: " f"2q-depth {qc_lnn.depth(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"2q-count {qc_lnn.size(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"1q-count {qc_lnn.size(filter_function=lambda x: x.operation.num_qubits == 1)}. ") # layout is a line of connected qubits layout = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 10, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 26, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 38, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 54, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55] num_qubits = qc_lnn.num_qubits initial_layout = layout[0:num_qubits] qc_lnn_trans = transpile(qc_lnn, coupling_map=coupling_map, basis_gates=['rz', 'sx', 'cx'], optimization_level=1, initial_layout=initial_layout) print(f"transpiled LNN circuit has: " f"2q-depth {qc_lnn_trans.depth(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"2q-count {qc_lnn_trans.size(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"1q-count {qc_lnn_trans.size(filter_function=lambda x: x.operation.num_qubits == 1)}. ") num_qubits = 50 # input: random invertible binary matrix mat = random_invertible_binary_matrix(num_qubits) qc = synth_cnot_depth_line_kms(mat) print(f"Linear circuit has: " f"2q-depth {qc.depth(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"2q-count {qc.size(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"1q-count {qc.size(filter_function=lambda x: x.operation.num_qubits == 1)}. ") num_qubits = 50 # input: random permutation pattern = np.random.permutation(num_qubits) qc = synth_permutation_depth_lnn_kms(pattern) print(f"Permutation circuit has: " f"2q-depth {qc.depth(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"2q-count {qc.size(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"1q-count {qc.size(filter_function=lambda x: x.operation.num_qubits == 1)}. ") num_qubits = 50 # input: an upper-diagonal matrix representing the CZ circuit. mat[i][j]=1 for i<j represents a CZ(i,j) gate qc = synth_cz_depth_line_mr(mat) print(f"CZ circuit has: " f"2q-depth {qc.depth(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"2q-count {qc.size(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"1q-count {qc.size(filter_function=lambda x: x.operation.num_qubits == 1)}. ") cliff = random_clifford(5) qc = synth_clifford_layers(cliff) qc.draw('mpl') cliff = random_clifford(50) qc = synth_clifford_depth_lnn(cliff).decompose() print(f"Clifford circuit has: " f"2q-depth {qc.depth(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"2q-count {qc.size(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"1q-count {qc.size(filter_function=lambda x: x.operation.num_qubits == 1)}. ") cliff = random_clifford(5) stab = StabilizerState(cliff) qc = synth_stabilizer_layers(stab) qc.draw('mpl') cliff = random_clifford(50) stab = StabilizerState(cliff) qc = synth_stabilizer_depth_lnn(stab).decompose() print(f"Stabilizer circuit has: " f"2q-depth {qc.depth(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"2q-count {qc.size(filter_function=lambda x: x.operation.num_qubits == 2)}, " f"1q-count {qc.size(filter_function=lambda x: x.operation.num_qubits == 1)}. ")
https://github.com/xtophe388/QISKIT
xtophe388
import qiskit qiskit.__qiskit_version__ import numpy as np import matplotlib.pyplot as plt %matplotlib inline # 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) IBMQ.load_account() # get ibmq_16_melbourne configuration and coupling map backend = IBMQ.get_backend('ibmq_16_melbourne') # compile the circuit for ibmq_16_rueschlikon 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-hackathon-korea-22
qiskit-community
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, IBMQ, schedule import qiskit.pulse as pulse from qiskit.circuit import Parameter from qiskit_experiments.calibration_management import Calibrations import pandas as pd # Loading your IBM Quantum account(s) qubit = 1 phase = np.pi # Generating an instance of Calibrations class def setup_cals( backend ) -> Calibrations: """ A function to instantiate calibrations and add a couple of template schedules. """ # Instantiating Calibrations as cals cals = Calibrations.from_backend( backend ) # Parameters to sweep dur = Parameter( "dur" ) amp = Parameter( "amp" ) amp_2 = Parameter( "amp" ) sigma = Parameter( "σ" ) beta = Parameter( "β" ) beta_2 = Parameter( "β" ) drive = pulse.DriveChannel( Parameter( "ch0" ) ) # Define and add template schedules with pulse.build( name="xp" ) as xp: # X positive pulse.play( pulse.Drag( dur, amp, sigma, beta ), drive ) with pulse.build( name="x" ) as x: # X positive pulse.play( pulse.Drag( dur, amp, sigma, beta ), drive ) with pulse.build( name="y" ) as y: # Y positive pulse.shift_phase( phase, drive ) pulse.play( pulse.Drag( dur, amp, sigma, beta ), drive ) with pulse.build( name="xm" ) as xm: # X minus pulse.play( pulse.Drag( dur, -amp, sigma, beta ), drive ) with pulse.build( name="x90p" ) as x90p: # X/2 positive # Different pulse amplitude and correction pulse amplitude for X/2 pulse.play( pulse.Drag( dur, amp_2, sigma, beta_2 ), drive ) with pulse.build( name="sx" ) as sx: # X/2 positive # Different pulse amplitude and correction pulse amplitude for X/2 pulse.play( pulse.Drag( dur, amp_2, sigma, beta_2 ), drive ) cals.add_schedule( xp, num_qubits=1 ) cals.add_schedule( xm, num_qubits=1 ) cals.add_schedule( x90p, num_qubits=1 ) cals.add_schedule( x, num_qubits=1 ) cals.add_schedule( y, num_qubits=1 ) cals.add_schedule( sx, num_qubits=1 ) return cals def add_parameter_guesses( cals: Calibrations ): """ Add guesses for the parameter values to the calibrations. """ for sched in [ "x", "xp", "y", "sx", "x90p" ]: cals.add_parameter_value( 80, "σ", schedule=sched ) cals.add_parameter_value( 0.5, "β", schedule=sched ) cals.add_parameter_value( 320, "dur", schedule=sched ) cals.add_parameter_value( 0.5, "amp", schedule=sched ) # Calling calibration functions cals = setup_cals( backend ) add_parameter_guesses( cals ) # Using a default frequency import pandas as pd pd.DataFrame( **cals.parameters_table( qubit_list=[ qubit, () ], parameters="drive_freq" ) ) from qiskit_experiments.library.calibration import RoughXSXAmplitudeCal # Define Rabi amplitude sweep sequence rabi = RoughXSXAmplitudeCal( qubit, cals, amplitudes=np.linspace( -0.2, 0.2, 51 ), backend=backend ) # Run the experiment rabi_data = rabi.run().block_for_results() rabi_data.figure( 0 ) # Save pulse amplitude pi_amp = np.pi / ( 2*np.pi*rabi_data.analysis_results( "rabi_rate" ).value.value ) print( pi_amp ) defaults = backend.defaults() x_schedule = defaults.instruction_schedule_map.get( 'x', 1 ) print( x_schedule ) pd.DataFrame(**cals.parameters_table(qubit_list=[qubit, ()], parameters="amp")) cals.get_schedule("sx", qubit) cals.get_schedule("x", qubit) from qiskit_experiments.library import RoughDragCal # Define DRAG coefficient sweep sequence cal_drag = RoughDragCal( qubit, cals, backend=backend, betas=np.linspace( -20, 20, 51 ) ) cal_drag.set_experiment_options( reps=[ 3, 5, 7 ] ) # Run the DRAG measurement drag_data = cal_drag.run().block_for_results() drag_data.figure( 0 ) print( drag_data.analysis_results( "beta" ) ) # Save DRAG coefficient beta = drag_data.analysis_results( "beta" ).value.value print( beta ) # Define DRAG coefficient sweep sequence cal_drag = RoughDragCal( qubit, cals, backend=backend, schedule_name="sx", betas=np.linspace( -20, 20, 51 ) ) cal_drag.set_experiment_options( reps=[ 9, 11, 17 ] ) # Run the DRAG measurement drag_data = cal_drag.run().block_for_results() drag_data.figure( 0 ) # Save DRAG coefficient beta_2 = drag_data.analysis_results( "beta" ).value.value print( beta_2 ) pd.DataFrame(**cals.parameters_table(qubit_list=[qubit, ()], parameters="β")) #print( "Qubit frequency: ", qubit_freq / 1e9, " GHz" ) print( "π-pulse amplitude: ", pi_amp ) print( "DRAG coefficient β fox X: ", beta ) print( "DRAG coefficient β for SX: ", beta_2 ) from qiskit_experiments.library.calibration.fine_amplitude import FineXAmplitudeCal amp_x_cal = FineXAmplitudeCal(qubit, cals, backend=backend, schedule_name="x") amp_x_fine = amp_x_cal.run().block_for_results() amp_x_fine.figure(0) print( amp_x_fine.analysis_results( "d_theta" ) ) dtheta = amp_x_fine.analysis_results( "d_theta" ).value.value target_angle = np.pi scale = target_angle / ( target_angle + dtheta ) print( "Deviation of", dtheta, "is detected for", target_angle, "rotation." ) print( "Hence, switch the π-amplitude from", pi_amp, "to", pi_amp*scale ) fine_x_amp = pi_amp * scale # Check if we have better π-gate. # Note that we don't have to update cals as it is updated automatically. sanity_check = amp_x_cal.run().block_for_results() print( "d_theta has been decreased from", dtheta, "to", sanity_check.analysis_results( "d_theta" ).value.value ) from qiskit_experiments.library.calibration.fine_amplitude import FineSXAmplitudeCal amp_sx_cal = FineSXAmplitudeCal(qubit, cals, backend=backend, schedule_name="sx") amp_sx_fine = amp_sx_cal.run().block_for_results() print( amp_sx_fine.analysis_results( "d_theta" ) ) amp_sx_fine.figure(0) dtheta = amp_sx_fine.analysis_results( "d_theta" ).value.value target_angle = np.pi/2 scale = target_angle / ( target_angle + dtheta ) print( "Deviation of", dtheta, "is detected for", target_angle, "rotation." ) print( "Hence, switch the π/2-amplitude from", pi_amp/2, "to", pi_amp/2*scale ) fine_sx_amp = pi_amp/2 * scale from qiskit_experiments.library.calibration import FineXDragCal, FineSXDragCal drag_x_cal = FineXDragCal( qubit, cals, backend=backend ) drag_x_fine = drag_x_cal.run().block_for_results() drag_x_fine.figure(0) fine_beta = cals.get_parameter_value( "β", qubit, "x" ) print( fine_beta ) drag_sx_cal = FineSXDragCal( qubit, cals, backend=backend ) drag_sx_fine = drag_sx_cal.run().block_for_results() fine_beta_2 = cals.get_parameter_value( "β", qubit, "sx" ) print( fine_beta_2 ) pd.DataFrame(**cals.parameters_table(qubit_list=[qubit, ()], parameters="β")) from qiskit_experiments.library.calibration.half_angle_cal import HalfAngleCal half_angle_cal = HalfAngleCal( qubit, cals, backend=backend ) half_angle_fine = half_angle_cal.run().block_for_results() half_angle_fine.figure(0) finer_sx_amp = cals.get_parameter_value( "amp", qubit, "sx" ) print( finer_sx_amp ) # print( "Qubit frequency:", qubit_freq/1e9, "GHz to Fine Qubit frequency:", fine_qubit_freq/1e9, "GHz." ) print( "π-pulse amplitude:", pi_amp, "to Fine π-pulse amplitude:", fine_x_amp) print( "π/2-pulse amplitude:", pi_amp/2, "to Fine π/2-pulse amplitude:", finer_sx_amp) print( "DRAG coefficient β fox X:", beta, "to Fine DRAG coefficient β for X:", fine_beta ) print( "DRAG coefficient β for SX: ", beta_2, "to Fine DRAG coefficient β for SX:", fine_beta_2 ) # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, pulse, IBMQ # Importing RB-related libraries from qiskit_experiments.library import StandardRB, InterleavedRB from qiskit_experiments.framework import ParallelExperiment from qiskit_experiments.library.randomized_benchmarking import RBUtils import qiskit.circuit.library as circuits x_amp = fine_x_amp sx_amp = fine_sx_amp x_drag = fine_beta sx_drag = fine_beta_2 with pulse.build(backend) as X_pulse: drive_duration=320 drive_sigma=80 drive_chan=pulse.drive_channel(qubit) pulse.play(pulse.library.Drag(duration=drive_duration, amp=x_amp, sigma=drive_sigma, beta=x_drag, name='X pulse'), drive_chan) with pulse.build(backend) as SX_pulse: drive_duration=320 drive_sigma=80 drive_chan=pulse.drive_channel(qubit) pulse.play(pulse.library.Drag(duration=drive_duration, amp=sx_amp, sigma=drive_sigma, beta=sx_drag, name='SX pulse'), drive_chan) inst_map = backend.defaults().instruction_schedule_map print( inst_map.get('x',qubit) ) print( inst_map.get('sx',qubit) ) inst_map.add( 'x', qubit, X_pulse ) inst_map.add( 'sx', qubit, SX_pulse ) print( inst_map.get('x',qubit) ) print( inst_map.get('sx',qubit) ) lengths = np.arange( 1, 2000, 200 ) num_samples = 16 seed = 1010 qubits = [qubit] # Run an RB experiment on qubit 1 expDyn = StandardRB(qubits, lengths, num_samples=num_samples, seed=seed) expdataDyn = expDyn.run(backend=backend) # View result data display(expdataDyn.figure(0))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) # plot using a DensityMatrix state = DensityMatrix(qc) plot_state_city(state)
https://github.com/sebasmos/QuantumVE
sebasmos
# Quantum Kernel Alighment [Reference](https://quantumcomputing.com/Havry/projects/qiskit-runtime-quantum-kernel-alignment/files/main.py) API_KEY = "5bd4ecfdc74e6680da7c79998259781431661e5326ae2f88eea95dee8f74b87530ba63fbca8105404de4ffd36e4b484631907acff73c805580928218a5ccf0b3" import qiskit as q from qiskit import IBMQ,schedule import qiskit.pulse as pulse from qiskit.circuit import Parameter import numpy as np import pandas as pd from qka_files.qka import FeatureMap %matplotlib inline import sys sys.path.insert(0, '..') # Add qiskit_runtime directory to the path IBMQ.save_account(API_KEY, overwrite=True) IBMQ.load_account() # Details in: https://qiskit.org/documentation/install.html # -------------------------------- # ✅ SETUP YOUR PROVIDER # # Assuming you've enabled Runtime, this should automatically work. # If not, 👉 https://app.quantumcomputing.com/runtime/enable provider = IBMQ.get_provider("ibm-q", group="open", project="main") for backend in provider.backends(): try: qubit_count = len(backend.properties().quibits) except: qubit_count = "simulated" print(f"{backend.name()} has {backend.status().pending_jobs} queued and { qubit_count} qubits") # -------------------------------- # ✅ SELECT A BACKEND # You can run on the simulator 💻 (🐇) from qiskit.tools.monitor import job_monitor #backend = provider.get_backend("ibmq_lima") options = {'backend_name': "ibmq_lima"} # -------------------------------- # ✅ READ IN SOME DATA df = pd.read_csv('qka_files/dataset_graph7.csv',sep=',', header=None) # this date is the one that will be used for the classification problem data = df.values # choose number of training and test samples per class 👩‍🏫: num_train = 5 num_test = 5 # extract training and test sets and sort them by class label train = data[:2*num_train, :] test = data[2*num_train:2*(num_train+num_test), :] ind=np.argsort(train[:,-1]) x_train = train[ind][:,:-1] y_train = train[ind][:,-1] ind=np.argsort(test[:,-1]) x_test = test[ind][:,:-1] y_test = test[ind][:,-1] # feature dimension is twice the qubit number d = np.shape(data)[1]-1 # we'll match this to the 7-qubit graph em = [[0,2],[3,4],[2,5],[1,4],[2,3],[4,6]] # define the feature map fm = FeatureMap(feature_dimension=d, entangler_map=em) # set the initial parameter for the feature map initial_point = [0.1] # SVM soft-margin penalty C = 1 maxiters = 10 initial_layout = [0, 1, 2, 3, 4, 5, 6] # Setup a callback for our interim result def interim_result_callback(job_id, interim_result): print(f"interim result: {interim_result}\n") # Set our inputs program_inputs = { 'feature_map': fm, 'data': x_train, 'labels': y_train, 'initial_kernel_parameters': initial_point, 'maxiters': maxiters, 'C': C, 'initial_layout': initial_layout } # -------------------------------- # ✅ RUN THE PROGRAM job = provider.runtime.run(program_id="quantum-kernel-alignment", options=options, inputs=program_inputs, callback=interim_result_callback, ) print("🖼 Circuit for the feature map:") strangeworks.qiskit.extract_diagram(fm.construct_circuit(x=x_train[0], parameters=initial_point)) # -------------------------------- # ✅ GET THE FINAL RESULT # Execution will pause here until the result returns result = job.result() # And finally, we'll display the output strangeworks.print(result, type="log", label="Final Result") # 🎉 Yay, Runtime success! # # ⏭ Try other programs here: # https://app.quantumcomputing.com/runtime/
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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 StabilizerTable class.""" import unittest import numpy as np from scipy.sparse import csr_matrix from qiskit import QiskitError from qiskit.quantum_info.operators.symplectic import PauliTable, StabilizerTable from qiskit.test import QiskitTestCase def stab_mat(label): """Return stabilizer matrix from a stabilizer label""" mat = np.eye(1, dtype=complex) if label[0] == "-": mat *= -1 if label[0] in ["-", "+"]: label = label[1:] for i in label: if i == "I": mat = np.kron(mat, np.eye(2)) elif i == "X": mat = np.kron(mat, np.array([[0, 1], [1, 0]])) elif i == "Y": mat = np.kron(mat, np.array([[0, 1], [-1, 0]])) elif i == "Z": mat = np.kron(mat, np.array([[1, 0], [0, -1]])) else: raise QiskitError(f"Invalid stabilizer string {i}") return mat class TestStabilizerTableInit(QiskitTestCase): """Tests for StabilizerTable initialization.""" def test_array_init(self): """Test array initialization.""" with self.subTest(msg="bool array"): target = np.array([[False, False], [True, True]]) with self.assertWarns(DeprecationWarning): value = StabilizerTable(target)._array self.assertTrue(np.all(value == target)) with self.subTest(msg="bool array no copy"): target = np.array([[False, True], [True, True]]) with self.assertWarns(DeprecationWarning): value = StabilizerTable(target)._array value[0, 0] = not value[0, 0] self.assertTrue(np.all(value == target)) with self.subTest(msg="bool array raises"): array = np.array([[False, False, False], [True, True, True]]) with self.assertWarns(DeprecationWarning): self.assertRaises(QiskitError, StabilizerTable, array) def test_vector_init(self): """Test vector initialization.""" with self.subTest(msg="bool vector"): target = np.array([False, False, False, False]) with self.assertWarns(DeprecationWarning): value = StabilizerTable(target)._array self.assertTrue(np.all(value == target)) with self.subTest(msg="bool vector no copy"): target = np.array([False, True, True, False]) with self.assertWarns(DeprecationWarning): value = StabilizerTable(target)._array value[0, 0] = not value[0, 0] self.assertTrue(np.all(value == target)) def test_string_init(self): """Test string initialization.""" with self.subTest(msg='str init "I"'): with self.assertWarns(DeprecationWarning): value = StabilizerTable("I")._array target = np.array([[False, False]], dtype=bool) self.assertTrue(np.all(np.array(value == target))) with self.subTest(msg='str init "X"'): with self.assertWarns(DeprecationWarning): value = StabilizerTable("X")._array target = np.array([[True, False]], dtype=bool) self.assertTrue(np.all(np.array(value == target))) with self.subTest(msg='str init "Y"'): with self.assertWarns(DeprecationWarning): value = StabilizerTable("Y")._array target = np.array([[True, True]], dtype=bool) self.assertTrue(np.all(np.array(value == target))) with self.subTest(msg='str init "Z"'): with self.assertWarns(DeprecationWarning): value = StabilizerTable("Z")._array target = np.array([[False, True]], dtype=bool) self.assertTrue(np.all(np.array(value == target))) with self.subTest(msg='str init "IX"'): with self.assertWarns(DeprecationWarning): value = StabilizerTable("IX")._array target = np.array([[True, False, False, False]], dtype=bool) self.assertTrue(np.all(np.array(value == target))) with self.subTest(msg='str init "XI"'): with self.assertWarns(DeprecationWarning): value = StabilizerTable("XI")._array target = np.array([[False, True, False, False]], dtype=bool) self.assertTrue(np.all(np.array(value == target))) with self.subTest(msg='str init "YZ"'): with self.assertWarns(DeprecationWarning): value = StabilizerTable("YZ")._array target = np.array([[False, True, True, True]], dtype=bool) self.assertTrue(np.all(np.array(value == target))) with self.subTest(msg='str init "XIZ"'): with self.assertWarns(DeprecationWarning): value = StabilizerTable("XIZ")._array target = np.array([[False, False, True, True, False, False]], dtype=bool) self.assertTrue(np.all(np.array(value == target))) def test_table_init(self): """Test StabilizerTable initialization.""" with self.subTest(msg="StabilizerTable"): with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["XI", "IX", "IZ"]) value = StabilizerTable(target) self.assertEqual(value, target) with self.subTest(msg="StabilizerTable no copy"): with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["XI", "IX", "IZ"]) value = StabilizerTable(target) value[0] = "II" self.assertEqual(value, target) class TestStabilizerTableProperties(QiskitTestCase): """Tests for StabilizerTable properties.""" def test_array_property(self): """Test array property""" with self.subTest(msg="array"): with self.assertWarns(DeprecationWarning): stab = StabilizerTable("II") array = np.zeros([2, 4], dtype=bool) self.assertTrue(np.all(stab.array == array)) with self.subTest(msg="set array"): def set_array(): with self.assertWarns(DeprecationWarning): stab = StabilizerTable("XXX") stab.array = np.eye(4) return stab self.assertRaises(Exception, set_array) def test_x_property(self): """Test X property""" with self.subTest(msg="X"): with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["XI", "IZ", "YY"]) array = np.array([[False, True], [False, False], [True, True]], dtype=bool) self.assertTrue(np.all(stab.X == array)) with self.subTest(msg="set X"): with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["XI", "IZ"]) val = np.array([[False, False], [True, True]], dtype=bool) stab.X = val with self.assertWarns(DeprecationWarning): self.assertEqual(stab, StabilizerTable.from_labels(["II", "XY"])) with self.subTest(msg="set X raises"): def set_x(): with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["XI", "IZ"]) val = np.array([[False, False, False], [True, True, True]], dtype=bool) stab.X = val return stab self.assertRaises(Exception, set_x) def test_z_property(self): """Test Z property""" with self.subTest(msg="Z"): with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["XI", "IZ", "YY"]) array = np.array([[False, False], [True, False], [True, True]], dtype=bool) self.assertTrue(np.all(stab.Z == array)) with self.subTest(msg="set Z"): with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["XI", "IZ"]) val = np.array([[False, False], [True, True]], dtype=bool) stab.Z = val with self.assertWarns(DeprecationWarning): self.assertEqual(stab, StabilizerTable.from_labels(["XI", "ZZ"])) with self.subTest(msg="set Z raises"): def set_z(): with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["XI", "IZ"]) val = np.array([[False, False, False], [True, True, True]], dtype=bool) stab.Z = val return stab self.assertRaises(Exception, set_z) def test_shape_property(self): """Test shape property""" shape = (3, 8) with self.assertWarns(DeprecationWarning): stab = StabilizerTable(np.zeros(shape)) self.assertEqual(stab.shape, shape) def test_size_property(self): """Test size property""" with self.subTest(msg="size"): for j in range(1, 10): shape = (j, 8) with self.assertWarns(DeprecationWarning): stab = StabilizerTable(np.zeros(shape)) self.assertEqual(stab.size, j) def test_num_qubits_property(self): """Test num_qubits property""" with self.subTest(msg="num_qubits"): for j in range(1, 10): shape = (5, 2 * j) with self.assertWarns(DeprecationWarning): stab = StabilizerTable(np.zeros(shape)) self.assertEqual(stab.num_qubits, j) def test_phase_property(self): """Test phase property""" with self.subTest(msg="phase"): phase = np.array([False, True, True, False]) array = np.eye(4, dtype=bool) with self.assertWarns(DeprecationWarning): stab = StabilizerTable(array, phase) self.assertTrue(np.all(stab.phase == phase)) with self.subTest(msg="set phase"): phase = np.array([False, True, True, False]) array = np.eye(4, dtype=bool) with self.assertWarns(DeprecationWarning): stab = StabilizerTable(array) stab.phase = phase self.assertTrue(np.all(stab.phase == phase)) with self.subTest(msg="set phase raises"): phase = np.array([False, True, False]) array = np.eye(4, dtype=bool) with self.assertWarns(DeprecationWarning): stab = StabilizerTable(array) def set_phase_raise(): """Raise exception""" stab.phase = phase self.assertRaises(ValueError, set_phase_raise) def test_pauli_property(self): """Test pauli property""" with self.subTest(msg="pauli"): phase = np.array([False, True, True, False]) array = np.eye(4, dtype=bool) with self.assertWarns(DeprecationWarning): stab = StabilizerTable(array, phase) pauli = PauliTable(array) self.assertEqual(stab.pauli, pauli) with self.subTest(msg="set pauli"): phase = np.array([False, True, True, False]) array = np.zeros((4, 4), dtype=bool) with self.assertWarns(DeprecationWarning): stab = StabilizerTable(array, phase) pauli = PauliTable(np.eye(4, dtype=bool)) stab.pauli = pauli self.assertTrue(np.all(stab.array == pauli.array)) self.assertTrue(np.all(stab.phase == phase)) with self.subTest(msg="set pauli"): phase = np.array([False, True, True, False]) array = np.zeros((4, 4), dtype=bool) with self.assertWarns(DeprecationWarning): stab = StabilizerTable(array, phase) pauli = PauliTable(np.eye(4, dtype=bool)[1:]) def set_pauli_raise(): """Raise exception""" stab.pauli = pauli self.assertRaises(ValueError, set_pauli_raise) def test_eq(self): """Test __eq__ method.""" with self.assertWarns(DeprecationWarning): stab1 = StabilizerTable.from_labels(["II", "XI"]) stab2 = StabilizerTable.from_labels(["XI", "II"]) self.assertEqual(stab1, stab1) self.assertNotEqual(stab1, stab2) def test_len_methods(self): """Test __len__ method.""" for j in range(1, 10): labels = j * ["XX"] with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(labels) self.assertEqual(len(stab), j) def test_add_methods(self): """Test __add__ method.""" labels1 = ["+XXI", "-IXX"] labels2 = ["+XXI", "-ZZI", "+ZYZ"] with self.assertWarns(DeprecationWarning): stab1 = StabilizerTable.from_labels(labels1) stab2 = StabilizerTable.from_labels(labels2) target = StabilizerTable.from_labels(labels1 + labels2) self.assertEqual(target, stab1 + stab2) def test_add_qargs(self): """Test add method with qargs.""" with self.assertWarns(DeprecationWarning): stab1 = StabilizerTable.from_labels(["+IIII", "-YYYY"]) stab2 = StabilizerTable.from_labels(["-XY", "+YZ"]) with self.subTest(msg="qargs=[0, 1]"): with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["+IIII", "-YYYY", "-IIXY", "+IIYZ"]) self.assertEqual(stab1 + stab2([0, 1]), target) with self.subTest(msg="qargs=[0, 3]"): with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["+IIII", "-YYYY", "-XIIY", "+YIIZ"]) self.assertEqual(stab1 + stab2([0, 3]), target) with self.subTest(msg="qargs=[2, 1]"): with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["+IIII", "-YYYY", "-IYXI", "+IZYI"]) self.assertEqual(stab1 + stab2([2, 1]), target) with self.subTest(msg="qargs=[3, 1]"): with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["+IIII", "-YYYY", "-YIXI", "+ZIYI"]) self.assertEqual(stab1 + stab2([3, 1]), target) def test_getitem_methods(self): """Test __getitem__ method.""" with self.subTest(msg="__getitem__ single"): labels = ["+XI", "-IY"] with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(labels) self.assertEqual(stab[0], StabilizerTable(labels[0])) self.assertEqual(stab[1], StabilizerTable(labels[1])) with self.subTest(msg="__getitem__ array"): labels = np.array(["+XI", "-IY", "+IZ", "-XY", "+ZX"]) with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(labels) inds = [0, 3] with self.assertWarns(DeprecationWarning): self.assertEqual(stab[inds], StabilizerTable.from_labels(labels[inds])) inds = np.array([4, 1]) with self.assertWarns(DeprecationWarning): self.assertEqual(stab[inds], StabilizerTable.from_labels(labels[inds])) with self.subTest(msg="__getitem__ slice"): labels = np.array(["+XI", "-IY", "+IZ", "-XY", "+ZX"]) with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(labels) self.assertEqual(stab[:], stab) self.assertEqual(stab[1:3], StabilizerTable.from_labels(labels[1:3])) def test_setitem_methods(self): """Test __setitem__ method.""" with self.subTest(msg="__setitem__ single"): labels = ["+XI", "IY"] with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["+XI", "IY"]) stab[0] = "+II" self.assertEqual(stab[0], StabilizerTable("+II")) stab[1] = "-XX" self.assertEqual(stab[1], StabilizerTable("-XX")) def raises_single(): # Wrong size Pauli stab[0] = "+XXX" self.assertRaises(Exception, raises_single) with self.subTest(msg="__setitem__ array"): labels = np.array(["+XI", "-IY", "+IZ"]) with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(labels) target = StabilizerTable.from_labels(["+II", "-ZZ"]) inds = [2, 0] stab[inds] = target with self.assertWarns(DeprecationWarning): self.assertEqual(stab[inds], target) def raises_array(): with self.assertWarns(DeprecationWarning): stab[inds] = StabilizerTable.from_labels(["+YY", "-ZZ", "+XX"]) self.assertRaises(Exception, raises_array) with self.subTest(msg="__setitem__ slice"): labels = np.array(5 * ["+III"]) with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(labels) target = StabilizerTable.from_labels(5 * ["-XXX"]) stab[:] = target with self.assertWarns(DeprecationWarning): self.assertEqual(stab[:], target) target = StabilizerTable.from_labels(2 * ["+ZZZ"]) stab[1:3] = target self.assertEqual(stab[1:3], target) class TestStabilizerTableLabels(QiskitTestCase): """Tests for StabilizerTable label converions.""" def test_from_labels_1q(self): """Test 1-qubit from_labels method.""" labels = ["I", "X", "Y", "Z", "+I", "+X", "+Y", "+Z", "-I", "-X", "-Y", "-Z"] array = np.vstack( 3 * [np.array([[False, False], [True, False], [True, True], [False, True]], dtype=bool)] ) phase = np.array(8 * [False] + 4 * [True], dtype=bool) with self.assertWarns(DeprecationWarning): target = StabilizerTable(array, phase) value = StabilizerTable.from_labels(labels) self.assertEqual(target, value) def test_from_labels_2q(self): """Test 2-qubit from_labels method.""" labels = ["II", "-YY", "+XZ"] array = np.array( [[False, False, False, False], [True, True, True, True], [False, True, True, False]], dtype=bool, ) phase = np.array([False, True, False]) with self.assertWarns(DeprecationWarning): target = StabilizerTable(array, phase) value = StabilizerTable.from_labels(labels) self.assertEqual(target, value) def test_from_labels_5q(self): """Test 5-qubit from_labels method.""" labels = ["IIIII", "-XXXXX", "YYYYY", "ZZZZZ"] array = np.array( [10 * [False], 5 * [True] + 5 * [False], 10 * [True], 5 * [False] + 5 * [True]], dtype=bool, ) phase = np.array([False, True, False, False]) with self.assertWarns(DeprecationWarning): target = StabilizerTable(array, phase) value = StabilizerTable.from_labels(labels) self.assertEqual(target, value) def test_to_labels_1q(self): """Test 1-qubit to_labels method.""" array = np.vstack( 2 * [np.array([[False, False], [True, False], [True, True], [False, True]], dtype=bool)] ) phase = np.array(4 * [False] + 4 * [True], dtype=bool) with self.assertWarns(DeprecationWarning): value = StabilizerTable(array, phase).to_labels() target = ["+I", "+X", "+Y", "+Z", "-I", "-X", "-Y", "-Z"] self.assertEqual(value, target) def test_to_labels_1q_array(self): """Test 1-qubit to_labels method w/ array=True.""" array = np.vstack( 2 * [np.array([[False, False], [True, False], [True, True], [False, True]], dtype=bool)] ) phase = np.array(4 * [False] + 4 * [True], dtype=bool) with self.assertWarns(DeprecationWarning): value = StabilizerTable(array, phase).to_labels(array=True) target = np.array(["+I", "+X", "+Y", "+Z", "-I", "-X", "-Y", "-Z"]) self.assertTrue(np.all(value == target)) def test_labels_round_trip(self): """Test from_labels and to_labels round trip.""" target = ["+III", "-IXZ", "-XYI", "+ZZZ"] with self.assertWarns(DeprecationWarning): value = StabilizerTable.from_labels(target).to_labels() self.assertEqual(value, target) def test_labels_round_trip_array(self): """Test from_labels and to_labels round trip w/ array=True.""" labels = ["+III", "-IXZ", "-XYI", "+ZZZ"] target = np.array(labels) with self.assertWarns(DeprecationWarning): value = StabilizerTable.from_labels(labels).to_labels(array=True) self.assertTrue(np.all(value == target)) class TestStabilizerTableMatrix(QiskitTestCase): """Tests for StabilizerTable matrix converions.""" def test_to_matrix_1q(self): """Test 1-qubit to_matrix method.""" labels = ["+I", "+X", "+Y", "+Z", "-I", "-X", "-Y", "-Z"] targets = [stab_mat(i) for i in labels] with self.assertWarns(DeprecationWarning): values = StabilizerTable.from_labels(labels).to_matrix() self.assertTrue(isinstance(values, list)) for target, value in zip(targets, values): self.assertTrue(np.all(value == target)) def test_to_matrix_1q_array(self): """Test 1-qubit to_matrix method w/ array=True.""" labels = ["+I", "+X", "+Y", "+Z", "-I", "-X", "-Y", "-Z"] target = np.array([stab_mat(i) for i in labels]) with self.assertWarns(DeprecationWarning): value = StabilizerTable.from_labels(labels).to_matrix(array=True) self.assertTrue(isinstance(value, np.ndarray)) self.assertTrue(np.all(value == target)) def test_to_matrix_1q_sparse(self): """Test 1-qubit to_matrix method w/ sparse=True.""" labels = ["+I", "+X", "+Y", "+Z", "-I", "-X", "-Y", "-Z"] targets = [stab_mat(i) for i in labels] with self.assertWarns(DeprecationWarning): values = StabilizerTable.from_labels(labels).to_matrix(sparse=True) for mat, targ in zip(values, targets): self.assertTrue(isinstance(mat, csr_matrix)) self.assertTrue(np.all(targ == mat.toarray())) def test_to_matrix_2q(self): """Test 2-qubit to_matrix method.""" labels = ["+IX", "-YI", "-II", "+ZZ"] targets = [stab_mat(i) for i in labels] with self.assertWarns(DeprecationWarning): values = StabilizerTable.from_labels(labels).to_matrix() self.assertTrue(isinstance(values, list)) for target, value in zip(targets, values): self.assertTrue(np.all(value == target)) def test_to_matrix_2q_array(self): """Test 2-qubit to_matrix method w/ array=True.""" labels = ["-ZZ", "-XY", "+YX", "-IZ"] target = np.array([stab_mat(i) for i in labels]) with self.assertWarns(DeprecationWarning): value = StabilizerTable.from_labels(labels).to_matrix(array=True) self.assertTrue(isinstance(value, np.ndarray)) self.assertTrue(np.all(value == target)) def test_to_matrix_2q_sparse(self): """Test 2-qubit to_matrix method w/ sparse=True.""" labels = ["+IX", "+II", "-ZY", "-YZ"] targets = [stab_mat(i) for i in labels] with self.assertWarns(DeprecationWarning): values = StabilizerTable.from_labels(labels).to_matrix(sparse=True) for mat, targ in zip(values, targets): self.assertTrue(isinstance(mat, csr_matrix)) self.assertTrue(np.all(targ == mat.toarray())) def test_to_matrix_5q(self): """Test 5-qubit to_matrix method.""" labels = ["IXIXI", "YZIXI", "IIXYZ"] targets = [stab_mat(i) for i in labels] with self.assertWarns(DeprecationWarning): values = StabilizerTable.from_labels(labels).to_matrix() self.assertTrue(isinstance(values, list)) for target, value in zip(targets, values): self.assertTrue(np.all(value == target)) def test_to_matrix_5q_sparse(self): """Test 5-qubit to_matrix method w/ sparse=True.""" labels = ["-XXXYY", "IXIZY", "-ZYXIX", "+ZXIYZ"] targets = [stab_mat(i) for i in labels] with self.assertWarns(DeprecationWarning): values = StabilizerTable.from_labels(labels).to_matrix(sparse=True) for mat, targ in zip(values, targets): self.assertTrue(isinstance(mat, csr_matrix)) self.assertTrue(np.all(targ == mat.toarray())) class TestStabilizerTableMethods(QiskitTestCase): """Tests for StabilizerTable methods.""" def test_sort(self): """Test sort method.""" with self.subTest(msg="1 qubit"): unsrt = ["X", "-Z", "I", "Y", "-X", "Z"] srt = ["I", "X", "-X", "Y", "-Z", "Z"] with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(srt) value = StabilizerTable.from_labels(unsrt).sort() self.assertEqual(target, value) with self.subTest(msg="1 qubit weight order"): unsrt = ["X", "-Z", "I", "Y", "-X", "Z"] srt = ["I", "X", "-X", "Y", "-Z", "Z"] with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(srt) value = StabilizerTable.from_labels(unsrt).sort(weight=True) self.assertEqual(target, value) with self.subTest(msg="2 qubit standard order"): srt_p = [ "II", "IX", "IY", "XI", "XX", "XY", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "ZZ", ] srt_m = ["-" + i for i in srt_p] unsrt_p = srt_p.copy() np.random.shuffle(unsrt_p) unsrt_m = srt_m.copy() np.random.shuffle(unsrt_m) # Sort with + cases all first in shuffled list srt = [val for pair in zip(srt_p, srt_m) for val in pair] unsrt = unsrt_p + unsrt_m with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(srt) value = StabilizerTable.from_labels(unsrt).sort() self.assertEqual(target, value) # Sort with - cases all first in shuffled list srt = [val for pair in zip(srt_m, srt_p) for val in pair] unsrt = unsrt_m + unsrt_p with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(srt) value = StabilizerTable.from_labels(unsrt).sort() self.assertEqual(target, value) with self.subTest(msg="2 qubit weight order"): srt_p = [ "II", "IX", "IY", "IZ", "XI", "YI", "ZI", "XX", "XY", "XZ", "YX", "YY", "YZ", "ZX", "ZY", "ZZ", ] srt_m = ["-" + i for i in srt_p] unsrt_p = srt_p.copy() np.random.shuffle(unsrt_p) unsrt_m = srt_m.copy() np.random.shuffle(unsrt_m) # Sort with + cases all first in shuffled list srt = [val for pair in zip(srt_p, srt_m) for val in pair] unsrt = unsrt_p + unsrt_m with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(srt) value = StabilizerTable.from_labels(unsrt).sort(weight=True) self.assertEqual(target, value) # Sort with - cases all first in shuffled list srt = [val for pair in zip(srt_m, srt_p) for val in pair] unsrt = unsrt_m + unsrt_p with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(srt) value = StabilizerTable.from_labels(unsrt).sort(weight=True) self.assertEqual(target, value) def test_unique(self): """Test unique method.""" with self.subTest(msg="1 qubit"): labels = ["X", "Z", "-I", "-X", "X", "I", "Y", "-I", "-X", "-Z", "Z", "X", "I"] unique = ["X", "Z", "-I", "-X", "I", "Y", "-Z"] with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(unique) value = StabilizerTable.from_labels(labels).unique() self.assertEqual(target, value) with self.subTest(msg="2 qubit"): labels = [ "XX", "IX", "-XX", "XX", "-IZ", "II", "IZ", "ZI", "YX", "YX", "ZZ", "IX", "XI", ] unique = ["XX", "IX", "-XX", "-IZ", "II", "IZ", "ZI", "YX", "ZZ", "XI"] with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(unique) value = StabilizerTable.from_labels(labels).unique() self.assertEqual(target, value) with self.subTest(msg="10 qubit"): labels = [10 * "X", "-" + 10 * "X", "-" + 10 * "X", 10 * "I", 10 * "X"] unique = [10 * "X", "-" + 10 * "X", 10 * "I"] with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(unique) value = StabilizerTable.from_labels(labels).unique() self.assertEqual(target, value) def test_delete(self): """Test delete method.""" with self.subTest(msg="single row"): for j in range(1, 6): with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels([j * "X", "-" + j * "Y"]) self.assertEqual(stab.delete(0), StabilizerTable("-" + j * "Y")) self.assertEqual(stab.delete(1), StabilizerTable(j * "X")) with self.subTest(msg="multiple rows"): for j in range(1, 6): with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels([j * "X", "-" + j * "Y", j * "Z"]) self.assertEqual(stab.delete([0, 2]), StabilizerTable("-" + j * "Y")) self.assertEqual(stab.delete([1, 2]), StabilizerTable(j * "X")) self.assertEqual(stab.delete([0, 1]), StabilizerTable(j * "Z")) with self.subTest(msg="single qubit"): with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["IIX", "IYI", "ZII"]) value = stab.delete(0, qubit=True) target = StabilizerTable.from_labels(["II", "IY", "ZI"]) self.assertEqual(value, target) value = stab.delete(1, qubit=True) target = StabilizerTable.from_labels(["IX", "II", "ZI"]) self.assertEqual(value, target) value = stab.delete(2, qubit=True) target = StabilizerTable.from_labels(["IX", "YI", "II"]) self.assertEqual(value, target) with self.subTest(msg="multiple qubits"): with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["IIX", "IYI", "ZII"]) value = stab.delete([0, 1], qubit=True) target = StabilizerTable.from_labels(["I", "I", "Z"]) self.assertEqual(value, target) value = stab.delete([1, 2], qubit=True) target = StabilizerTable.from_labels(["X", "I", "I"]) self.assertEqual(value, target) value = stab.delete([0, 2], qubit=True) target = StabilizerTable.from_labels(["I", "Y", "I"]) self.assertEqual(value, target) def test_insert(self): """Test insert method.""" # Insert single row for j in range(1, 10): l_px = j * "X" l_mi = "-" + j * "I" with self.assertWarns(DeprecationWarning): stab = StabilizerTable(l_px) target0 = StabilizerTable.from_labels([l_mi, l_px]) target1 = StabilizerTable.from_labels([l_px, l_mi]) with self.subTest(msg=f"single row from str ({j})"): with self.assertWarns(DeprecationWarning): value0 = stab.insert(0, l_mi) self.assertEqual(value0, target0) value1 = stab.insert(1, l_mi) self.assertEqual(value1, target1) with self.subTest(msg=f"single row from StabilizerTable ({j})"): with self.assertWarns(DeprecationWarning): value0 = stab.insert(0, StabilizerTable(l_mi)) self.assertEqual(value0, target0) value1 = stab.insert(1, StabilizerTable(l_mi)) self.assertEqual(value1, target1) # Insert multiple rows for j in range(1, 10): with self.assertWarns(DeprecationWarning): stab = StabilizerTable(j * "X") insert = StabilizerTable.from_labels(["-" + j * "I", j * "Y", "-" + j * "Z"]) target0 = insert + stab target1 = stab + insert with self.subTest(msg=f"multiple-rows from StabilizerTable ({j})"): with self.assertWarns(DeprecationWarning): value0 = stab.insert(0, insert) self.assertEqual(value0, target0) value1 = stab.insert(1, insert) self.assertEqual(value1, target1) # Insert single column with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["X", "Y", "Z"]) for sgn in ["+", "-"]: for i in ["I", "X", "Y", "Z"]: with self.assertWarns(DeprecationWarning): target0 = StabilizerTable.from_labels( [sgn + "X" + i, sgn + "Y" + i, sgn + "Z" + i] ) target1 = StabilizerTable.from_labels( [sgn + i + "X", sgn + i + "Y", sgn + i + "Z"] ) with self.subTest(msg=f"single-column single-val from str {sgn + i}"): with self.assertWarns(DeprecationWarning): value = stab.insert(0, sgn + i, qubit=True) self.assertEqual(value, target0) value = stab.insert(1, sgn + i, qubit=True) self.assertEqual(value, target1) with self.subTest(msg=f"single-column single-val from StabilizerTable {sgn + i}"): with self.assertWarns(DeprecationWarning): value = stab.insert(0, StabilizerTable(sgn + i), qubit=True) self.assertEqual(value, target0) value = stab.insert(1, StabilizerTable(sgn + i), qubit=True) self.assertEqual(value, target1) # Insert single column with multiple values with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["X", "Y", "Z"]) for i in [("I", "X", "Y"), ("X", "Y", "Z"), ("Y", "Z", "I")]: with self.assertWarns(DeprecationWarning): target0 = StabilizerTable.from_labels(["X" + i[0], "Y" + i[1], "Z" + i[2]]) target1 = StabilizerTable.from_labels([i[0] + "X", i[1] + "Y", i[2] + "Z"]) with self.subTest(msg="single-column multiple-vals from StabilizerTable"): with self.assertWarns(DeprecationWarning): value = stab.insert(0, StabilizerTable.from_labels(i), qubit=True) self.assertEqual(value, target0) value = stab.insert(1, StabilizerTable.from_labels(i), qubit=True) self.assertEqual(value, target1) with self.subTest(msg="single-column multiple-vals from array"): with self.assertWarns(DeprecationWarning): value = stab.insert(0, StabilizerTable.from_labels(i).array, qubit=True) self.assertEqual(value, target0) value = stab.insert(1, StabilizerTable.from_labels(i).array, qubit=True) self.assertEqual(value, target1) # Insert multiple columns from single with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["X", "Y", "Z"]) for j in range(1, 5): for i in [j * "I", j * "X", j * "Y", j * "Z"]: with self.assertWarns(DeprecationWarning): target0 = StabilizerTable.from_labels(["X" + i, "Y" + i, "Z" + i]) target1 = StabilizerTable.from_labels([i + "X", i + "Y", i + "Z"]) with self.subTest(msg="multiple-columns single-val from str"): with self.assertWarns(DeprecationWarning): value = stab.insert(0, i, qubit=True) self.assertEqual(value, target0) value = stab.insert(1, i, qubit=True) self.assertEqual(value, target1) with self.subTest(msg="multiple-columns single-val from StabilizerTable"): with self.assertWarns(DeprecationWarning): value = stab.insert(0, StabilizerTable(i), qubit=True) self.assertEqual(value, target0) value = stab.insert(1, StabilizerTable(i), qubit=True) self.assertEqual(value, target1) with self.subTest(msg="multiple-columns single-val from array"): with self.assertWarns(DeprecationWarning): value = stab.insert(0, StabilizerTable(i).array, qubit=True) self.assertEqual(value, target0) value = stab.insert(1, StabilizerTable(i).array, qubit=True) self.assertEqual(value, target1) # Insert multiple columns multiple row values with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["X", "Y", "Z"]) for j in range(1, 5): for i in [ (j * "I", j * "X", j * "Y"), (j * "X", j * "Z", j * "Y"), (j * "Y", j * "Z", j * "I"), ]: with self.assertWarns(DeprecationWarning): target0 = StabilizerTable.from_labels(["X" + i[0], "Y" + i[1], "Z" + i[2]]) target1 = StabilizerTable.from_labels([i[0] + "X", i[1] + "Y", i[2] + "Z"]) with self.subTest(msg="multiple-column multiple-vals from StabilizerTable"): with self.assertWarns(DeprecationWarning): value = stab.insert(0, StabilizerTable.from_labels(i), qubit=True) self.assertEqual(value, target0) value = stab.insert(1, StabilizerTable.from_labels(i), qubit=True) self.assertEqual(value, target1) with self.subTest(msg="multiple-column multiple-vals from array"): with self.assertWarns(DeprecationWarning): value = stab.insert(0, StabilizerTable.from_labels(i).array, qubit=True) self.assertEqual(value, target0) value = stab.insert(1, StabilizerTable.from_labels(i).array, qubit=True) self.assertEqual(value, target1) def test_iteration(self): """Test iteration methods.""" labels = ["+III", "+IXI", "-IYY", "+YIZ", "-ZIZ", "+XYZ", "-III"] with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(labels) with self.subTest(msg="enumerate"): with self.assertWarns(DeprecationWarning): for idx, i in enumerate(stab): self.assertEqual(i, StabilizerTable(labels[idx])) with self.subTest(msg="iter"): with self.assertWarns(DeprecationWarning): for idx, i in enumerate(iter(stab)): self.assertEqual(i, StabilizerTable(labels[idx])) with self.subTest(msg="zip"): with self.assertWarns(DeprecationWarning): for label, i in zip(labels, stab): self.assertEqual(i, StabilizerTable(label)) with self.subTest(msg="label_iter"): for idx, i in enumerate(stab.label_iter()): self.assertEqual(i, labels[idx]) with self.subTest(msg="matrix_iter (dense)"): for idx, i in enumerate(stab.matrix_iter()): self.assertTrue(np.all(i == stab_mat(labels[idx]))) with self.subTest(msg="matrix_iter (sparse)"): for idx, i in enumerate(stab.matrix_iter(sparse=True)): self.assertTrue(isinstance(i, csr_matrix)) self.assertTrue(np.all(i.toarray() == stab_mat(labels[idx]))) def test_tensor(self): """Test tensor method.""" labels1 = ["-XX", "YY"] labels2 = ["III", "-ZZZ"] with self.assertWarns(DeprecationWarning): stab1 = StabilizerTable.from_labels(labels1) stab2 = StabilizerTable.from_labels(labels2) target = StabilizerTable.from_labels(["-XXIII", "XXZZZ", "YYIII", "-YYZZZ"]) value = stab1.tensor(stab2) self.assertEqual(value, target) def test_expand(self): """Test expand method.""" labels1 = ["-XX", "YY"] labels2 = ["III", "-ZZZ"] with self.assertWarns(DeprecationWarning): stab1 = StabilizerTable.from_labels(labels1) stab2 = StabilizerTable.from_labels(labels2) target = StabilizerTable.from_labels(["-IIIXX", "IIIYY", "ZZZXX", "-ZZZYY"]) value = stab1.expand(stab2) self.assertEqual(value, target) def test_compose(self): """Test compose and dot methods.""" # Test single qubit Pauli dot products with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["I", "X", "Y", "Z"]) # Test single qubit Pauli dot products with self.assertWarns(DeprecationWarning): stab = StabilizerTable.from_labels(["I", "X", "Y", "Z", "-I", "-X", "-Y", "-Z"]) with self.subTest(msg="dot single I"): with self.assertWarns(DeprecationWarning): value = stab.compose("I") target = StabilizerTable.from_labels(["I", "X", "Y", "Z", "-I", "-X", "-Y", "-Z"]) self.assertEqual(target, value) with self.subTest(msg="dot single -I"): with self.assertWarns(DeprecationWarning): value = stab.compose("-I") target = StabilizerTable.from_labels(["-I", "-X", "-Y", "-Z", "I", "X", "Y", "Z"]) self.assertEqual(target, value) with self.subTest(msg="dot single I"): with self.assertWarns(DeprecationWarning): value = stab.dot("I") target = StabilizerTable.from_labels(["I", "X", "Y", "Z", "-I", "-X", "-Y", "-Z"]) self.assertEqual(target, value) with self.subTest(msg="dot single -I"): with self.assertWarns(DeprecationWarning): value = stab.dot("-I") target = StabilizerTable.from_labels(["-I", "-X", "-Y", "-Z", "I", "X", "Y", "Z"]) self.assertEqual(target, value) with self.subTest(msg="compose single X"): with self.assertWarns(DeprecationWarning): value = stab.compose("X") target = StabilizerTable.from_labels(["X", "I", "-Z", "Y", "-X", "-I", "Z", "-Y"]) self.assertEqual(target, value) with self.subTest(msg="compose single -X"): with self.assertWarns(DeprecationWarning): value = stab.compose("-X") target = StabilizerTable.from_labels(["-X", "-I", "Z", "-Y", "X", "I", "-Z", "Y"]) self.assertEqual(target, value) with self.subTest(msg="dot single X"): with self.assertWarns(DeprecationWarning): value = stab.dot("X") target = StabilizerTable.from_labels(["X", "I", "Z", "-Y", "-X", "-I", "-Z", "Y"]) self.assertEqual(target, value) with self.subTest(msg="dot single -X"): with self.assertWarns(DeprecationWarning): value = stab.dot("-X") target = StabilizerTable.from_labels(["-X", "-I", "-Z", "Y", "X", "I", "Z", "-Y"]) self.assertEqual(target, value) with self.subTest(msg="compose single Y"): with self.assertWarns(DeprecationWarning): value = stab.compose("Y") target = StabilizerTable.from_labels(["Y", "Z", "-I", "-X", "-Y", "-Z", "I", "X"]) self.assertEqual(target, value) with self.subTest(msg="compose single -Y"): with self.assertWarns(DeprecationWarning): value = stab.compose("-Y") target = StabilizerTable.from_labels(["-Y", "-Z", "I", "X", "Y", "Z", "-I", "-X"]) self.assertEqual(target, value) with self.subTest(msg="dot single Y"): with self.assertWarns(DeprecationWarning): value = stab.dot("Y") target = StabilizerTable.from_labels(["Y", "-Z", "-I", "X", "-Y", "Z", "I", "-X"]) self.assertEqual(target, value) with self.subTest(msg="dot single -Y"): with self.assertWarns(DeprecationWarning): value = stab.dot("-Y") target = StabilizerTable.from_labels(["-Y", "Z", "I", "-X", "Y", "-Z", "-I", "X"]) self.assertEqual(target, value) with self.subTest(msg="compose single Z"): with self.assertWarns(DeprecationWarning): value = stab.compose("Z") target = StabilizerTable.from_labels(["Z", "-Y", "X", "I", "-Z", "Y", "-X", "-I"]) self.assertEqual(target, value) with self.subTest(msg="compose single -Z"): with self.assertWarns(DeprecationWarning): value = stab.compose("-Z") target = StabilizerTable.from_labels(["-Z", "Y", "-X", "-I", "Z", "-Y", "X", "I"]) self.assertEqual(target, value) with self.subTest(msg="dot single Z"): with self.assertWarns(DeprecationWarning): value = stab.dot("Z") target = StabilizerTable.from_labels(["Z", "Y", "-X", "I", "-Z", "-Y", "X", "-I"]) self.assertEqual(target, value) with self.subTest(msg="dot single -Z"): with self.assertWarns(DeprecationWarning): value = stab.dot("-Z") target = StabilizerTable.from_labels(["-Z", "-Y", "X", "-I", "Z", "Y", "-X", "I"]) self.assertEqual(target, value) def test_compose_qargs(self): """Test compose and dot methods with qargs.""" # Dot product with qargs with self.assertWarns(DeprecationWarning): stab1 = StabilizerTable.from_labels(["III", "-XXX", "YYY", "-ZZZ"]) # 1-qubit qargs with self.assertWarns(DeprecationWarning): stab2 = StabilizerTable("-Z") with self.subTest(msg="dot 1-qubit qargs=[0]"): with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["-IIZ", "XXY", "YYX", "ZZI"]) value = stab1.dot(stab2, qargs=[0]) self.assertEqual(value, target) with self.subTest(msg="compose 1-qubit qargs=[0]"): with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["-IIZ", "-XXY", "-YYX", "ZZI"]) value = stab1.compose(stab2, qargs=[0]) self.assertEqual(value, target) with self.subTest(msg="dot 1-qubit qargs=[1]"): with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["-IZI", "XYX", "YXY", "ZIZ"]) value = stab1.dot(stab2, qargs=[1]) self.assertEqual(value, target) with self.subTest(msg="compose 1-qubit qargs=[1]"): with self.assertWarns(DeprecationWarning): value = stab1.compose(stab2, qargs=[1]) target = StabilizerTable.from_labels(["-IZI", "-XYX", "-YXY", "ZIZ"]) self.assertEqual(value, target) with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["ZII", "YXX"]) with self.subTest(msg="dot 1-qubit qargs=[2]"): with self.assertWarns(DeprecationWarning): value = stab1.dot(stab2, qargs=[2]) target = StabilizerTable.from_labels(["-ZII", "YXX", "XYY", "IZZ"]) self.assertEqual(value, target) with self.subTest(msg="compose 1-qubit qargs=[2]"): with self.assertWarns(DeprecationWarning): value = stab1.compose(stab2, qargs=[2]) target = StabilizerTable.from_labels(["-ZII", "-YXX", "-XYY", "IZZ"]) self.assertEqual(value, target) # 2-qubit qargs with self.assertWarns(DeprecationWarning): stab2 = StabilizerTable("-ZY") with self.subTest(msg="dot 2-qubit qargs=[0, 1]"): with self.assertWarns(DeprecationWarning): value = stab1.dot(stab2, qargs=[0, 1]) target = StabilizerTable.from_labels(["-IZY", "-XYZ", "-YXI", "ZIX"]) self.assertEqual(value, target) with self.subTest(msg="compose 2-qubit qargs=[0, 1]"): with self.assertWarns(DeprecationWarning): value = stab1.compose(stab2, qargs=[0, 1]) target = StabilizerTable.from_labels(["-IZY", "-XYZ", "YXI", "-ZIX"]) self.assertEqual(value, target) with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["YIZ", "ZXY"]) with self.subTest(msg="dot 2-qubit qargs=[2, 0]"): with self.assertWarns(DeprecationWarning): value = stab1.dot(stab2, qargs=[2, 0]) target = StabilizerTable.from_labels(["-YIZ", "-ZXY", "-IYX", "XZI"]) self.assertEqual(value, target) with self.subTest(msg="compose 2-qubit qargs=[2, 0]"): with self.assertWarns(DeprecationWarning): value = stab1.compose(stab2, qargs=[2, 0]) target = StabilizerTable.from_labels(["-YIZ", "-ZXY", "IYX", "-XZI"]) self.assertEqual(value, target) # 3-qubit qargs with self.assertWarns(DeprecationWarning): stab2 = StabilizerTable("-XYZ") with self.assertWarns(DeprecationWarning): target = StabilizerTable.from_labels(["XYZ", "IZY"]) with self.subTest(msg="dot 3-qubit qargs=None"): with self.assertWarns(DeprecationWarning): value = stab1.dot(stab2, qargs=[0, 1, 2]) target = StabilizerTable.from_labels(["-XYZ", "-IZY", "-ZIX", "-YXI"]) self.assertEqual(value, target) with self.subTest(msg="dot 3-qubit qargs=[0, 1, 2]"): with self.assertWarns(DeprecationWarning): value = stab1.dot(stab2, qargs=[0, 1, 2]) target = StabilizerTable.from_labels(["-XYZ", "-IZY", "-ZIX", "-YXI"]) self.assertEqual(value, target) with self.subTest(msg="dot 3-qubit qargs=[2, 1, 0]"): with self.assertWarns(DeprecationWarning): value = stab1.dot(stab2, qargs=[2, 1, 0]) target = StabilizerTable.from_labels(["-ZYX", "-YZI", "-XIZ", "-IXY"]) self.assertEqual(value, target) with self.subTest(msg="compose 3-qubit qargs=[2, 1, 0]"): with self.assertWarns(DeprecationWarning): value = stab1.compose(stab2, qargs=[2, 1, 0]) target = StabilizerTable.from_labels(["-ZYX", "-YZI", "-XIZ", "-IXY"]) self.assertEqual(value, target) if __name__ == "__main__": unittest.main()
https://github.com/alpine-quantum-technologies/qiskit-aqt-provider-rc
alpine-quantum-technologies
# This code is part of Qiskit. # # (C) Alpine Quantum Technologies GmbH 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. from math import pi from typing import Union import pytest from hypothesis import assume, given from hypothesis import strategies as st from qiskit import QuantumCircuit, transpile from qiskit.circuit.library import RXGate, RYGate from qiskit_aqt_provider.aqt_resource import AQTResource from qiskit_aqt_provider.test.circuits import ( assert_circuits_equal, assert_circuits_equivalent, qft_circuit, ) from qiskit_aqt_provider.test.fixtures import MockSimulator from qiskit_aqt_provider.transpiler_plugin import rewrite_rx_as_r, wrap_rxx_angle @pytest.mark.parametrize( ("input_theta", "output_theta", "output_phi"), [ (pi / 3, pi / 3, 0.0), (-pi / 3, pi / 3, pi), (7 * pi / 5, 3 * pi / 5, pi), (25 * pi, pi, pi), (22 * pi / 3, 2 * pi / 3, pi), ], ) def test_rx_rewrite_example( input_theta: float, output_theta: float, output_phi: float, ) -> None: """Snapshot test for the Rx(θ) → R(θ, φ) rule.""" result = QuantumCircuit(1) result.append(rewrite_rx_as_r(input_theta), (0,)) expected = QuantumCircuit(1) expected.r(output_theta, output_phi, 0) reference = QuantumCircuit(1) reference.rx(input_theta, 0) assert_circuits_equal(result, expected) assert_circuits_equivalent(result, reference) @given(theta=st.floats(allow_nan=False, min_value=-1000 * pi, max_value=1000 * pi)) @pytest.mark.parametrize("optimization_level", [1, 2, 3]) @pytest.mark.parametrize("test_gate", [RXGate, RYGate]) def test_rx_ry_rewrite_transpile( theta: float, optimization_level: int, test_gate: Union[RXGate, RYGate], ) -> None: """Test the rewrite rule: Rx(θ), Ry(θ) → R(θ, φ), θ ∈ [0, π], φ ∈ [0, 2π].""" assume(abs(theta) > pi / 200) # we only need the backend's transpiler target for this test backend = MockSimulator(noisy=False) qc = QuantumCircuit(1) qc.append(test_gate(theta), (0,)) trans_qc = transpile(qc, backend, optimization_level=optimization_level) assert isinstance(trans_qc, QuantumCircuit) assert_circuits_equivalent(trans_qc, qc) assert set(trans_qc.count_ops()) <= set(backend.configuration().basis_gates) num_r = trans_qc.count_ops().get("r") assume(num_r is not None) assert num_r == 1 for operation in trans_qc.data: instruction = operation[0] if instruction.name == "r": theta, phi = instruction.params assert 0 <= float(theta) <= pi assert 0 <= float(phi) <= 2 * pi break else: # pragma: no cover pytest.fail("No R gates in transpiled circuit.") def test_decompose_1q_rotations_example(offline_simulator_no_noise: AQTResource) -> None: """Snapshot test for the efficient rewrite of single-qubit rotation runs as ZXZ.""" qc = QuantumCircuit(1) qc.rx(pi / 2, 0) qc.ry(pi / 2, 0) expected = QuantumCircuit(1) expected.rz(-pi / 2, 0) expected.r(pi / 2, 0, 0) result = transpile(qc, offline_simulator_no_noise, optimization_level=3) assert isinstance(result, QuantumCircuit) # only got one circuit back assert_circuits_equal(result, expected) assert_circuits_equivalent(result, expected) def test_rxx_wrap_angle_case0() -> None: """Snapshot test for Rxx(θ) rewrite with 0 <= θ <= π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(pi / 2), (0, 1)) expected = QuantumCircuit(2) expected.rxx(pi / 2, 0, 1) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case0_negative() -> None: """Snapshot test for Rxx(θ) rewrite with -π/2 <= θ < 0.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(-pi / 2), (0, 1)) expected = QuantumCircuit(2) expected.rz(pi, 0) expected.rxx(pi / 2, 0, 1) expected.rz(pi, 0) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case1() -> None: """Snapshot test for Rxx(θ) rewrite with π/2 < θ <= 3π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(3 * pi / 2), (0, 1)) expected = QuantumCircuit(2) expected.rx(pi, 0) expected.rx(pi, 1) expected.rxx(pi / 2, 0, 1) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case1_negative() -> None: """Snapshot test for Rxx(θ) rewrite with -3π/2 <= θ < -π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(-3 * pi / 2), (0, 1)) expected = QuantumCircuit(2) expected.rxx(pi / 2, 0, 1) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case2() -> None: """Snapshot test for Rxx(θ) rewrite with θ > 3*π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(18 * pi / 10), (0, 1)) # mod 2π = 9π/5 → -π/5 expected = QuantumCircuit(2) expected.rz(pi, 0) expected.rxx(pi / 5, 0, 1) expected.rz(pi, 0) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) def test_rxx_wrap_angle_case2_negative() -> None: """Snapshot test for Rxx(θ) rewrite with θ < -3π/2.""" result = QuantumCircuit(2) result.append(wrap_rxx_angle(-18 * pi / 10), (0, 1)) # mod 2π = π/5 expected = QuantumCircuit(2) expected.rxx(pi / 5, 0, 1) assert_circuits_equal(result.decompose(), expected) assert_circuits_equivalent(result.decompose(), expected) @given( angle=st.floats( allow_nan=False, allow_infinity=False, min_value=-1000 * pi, max_value=1000 * pi, ) ) @pytest.mark.parametrize("qubits", [3]) @pytest.mark.parametrize("optimization_level", [1, 2, 3]) def test_rxx_wrap_angle_transpile(angle: float, qubits: int, optimization_level: int) -> None: """Check that Rxx angles are wrapped by the transpiler.""" assume(abs(angle) > pi / 200) qc = QuantumCircuit(qubits) qc.rxx(angle, 0, 1) # we only need the backend's transpilation target for this test backend = MockSimulator(noisy=False) trans_qc = transpile(qc, backend, optimization_level=optimization_level) assert isinstance(trans_qc, QuantumCircuit) assert_circuits_equivalent(trans_qc, qc) assert set(trans_qc.count_ops()) <= set(backend.configuration().basis_gates) num_rxx = trans_qc.count_ops().get("rxx") # in high optimization levels, the gate might be dropped assume(num_rxx is not None) assert num_rxx == 1 # check that all Rxx have angles in [0, π/2] for operation in trans_qc.data: instruction = operation[0] if instruction.name == "rxx": (theta,) = instruction.params assert 0 <= float(theta) <= pi / 2 break # there's only one Rxx gate in the circuit else: # pragma: no cover pytest.fail("Transpiled circuit contains no Rxx gate.") @pytest.mark.parametrize("qubits", [1, 5, 10]) @pytest.mark.parametrize("optimization_level", [1, 2, 3]) def test_qft_circuit_transpilation( qubits: int, optimization_level: int, offline_simulator_no_noise: AQTResource ) -> None: """Transpile a N-qubit QFT circuit for an AQT backend. Check that the angles are properly wrapped. """ qc = qft_circuit(qubits) trans_qc = transpile(qc, offline_simulator_no_noise, optimization_level=optimization_level) assert isinstance(trans_qc, QuantumCircuit) assert set(trans_qc.count_ops()) <= set(offline_simulator_no_noise.configuration().basis_gates) for operation in trans_qc.data: instruction = operation[0] if instruction.name == "rxx": (theta,) = instruction.params assert 0 <= float(theta) <= pi / 2 if instruction.name == "r": (theta, _) = instruction.params assert abs(theta) <= pi if optimization_level < 3 and qubits < 6: assert_circuits_equivalent(qc, trans_qc)
https://github.com/Qiskit/feedback
Qiskit
from qiskit import QuantumCircuit qc = QuantumCircuit(2, 1) qc.sx(0) qc.delay(100, 0) qc.cx(0, 1) qc.measure(1, 0) qc.draw() from qiskit.test.mock import FakeWashington FakeWashington().configuration().timing_constraints from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.passes import ALAPSchedule, AlignMeasures from qiskit.transpiler.instruction_durations import InstructionDurations durations = InstructionDurations([("sx", (0, ), 160), ("cx", (0, 1), 800), ("measure", (1, ), 1600)]) # this is as of Qiskit v0.19 pm = PassManager([ALAPSchedule(durations)]) pm.run(qc).draw() # this is as of Qiskit v0.19 pm = PassManager([ALAPSchedule(durations), AlignMeasures(alignment=16)]) pm.run(qc).draw() FakeWashington().configuration().conditional_latency FakeWashington().configuration().acquisition_latency from qiskit import QuantumCircuit qc = QuantumCircuit(2, 1) qc.x(0) qc.measure(0, 0) qc.x(0).c_if(0, 0) qc.measure(1, 0) qc.draw() from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.passes import ALAPSchedule from qiskit.transpiler.instruction_durations import InstructionDurations from qiskit.visualization import timeline_drawer durations = InstructionDurations([("x", None, 160), ("measure", None, 1600)]) # this is as of Qiskit v0.19 pm = PassManager([ALAPSchedule(durations)]) qc_scheduled = pm.run(qc) qc_scheduled.draw() # this is as of Qiskit v0.19 timeline_drawer(qc_scheduled) from qiskit import QuantumCircuit qc = QuantumCircuit(2, 1) qc.x(0) qc.measure(0, 0) qc.measure(1, 0) qc.draw() # this is as of Qiskit v0.19 pm = PassManager([ALAPSchedule(durations)]) qc_scheduled = pm.run(qc) qc_scheduled.draw() # this is as of Qiskit v0.19 timeline_drawer(qc_scheduled) # this is as of Qiskit v0.19 from qiskit import schedule from qiskit.test.mock import FakeBelem try: sched = schedule(qc, FakeBelem()) except Exception as ex: print(ex) from qiskit import QuantumCircuit qc = QuantumCircuit(2, 1) qc.sx(0) qc.delay(100, 0) qc.cx(0, 1) qc.measure(1, 0) qc.draw() from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.passes import ALAPSchedule, PadDelay, ConstrainedReschedule from qiskit.transpiler.instruction_durations import InstructionDurations durations = InstructionDurations([("sx", (0, ), 160), ("cx", (0, 1), 800), ("measure", (1, ), 1600)]) pm = PassManager([ALAPSchedule(durations)]) pm.run(qc).draw() for node, t in pm.property_set["node_start_time"].items(): print(f"{t :4d} dt: {node.name} ({node.qargs} {node.cargs})") pm = PassManager( [ ALAPSchedule(durations), ConstrainedReschedule(acquire_alignment=16, pulse_alignment=16), ] ) pm.run(qc).draw() for node, t in pm.property_set["node_start_time"].items(): print(f"{t :4d} dt: {node.name} ({node.qargs} {node.cargs})") pm = PassManager( [ ALAPSchedule(durations), ConstrainedReschedule(acquire_alignment=16, pulse_alignment=16), PadDelay(), ] ) pm.run(qc).draw() from qiskit import QuantumCircuit from qiskit.visualization import timeline_drawer durations = InstructionDurations([("x", None, 160), ("measure", None, 1600)]) qc = QuantumCircuit(2, 1) qc.x(0) qc.measure(0, 0) qc.x(0).c_if(0, 0) qc.measure(1, 0) pm = PassManager( [ ALAPSchedule(durations), PadDelay(), ] ) qc_scheduled = pm.run(qc) qc_scheduled.draw() timeline_drawer(qc_scheduled) pm = PassManager( [ ALAPSchedule(durations, clbit_write_latency=300, conditional_latency=200), PadDelay(), ] ) qc_scheduled = pm.run(qc) timeline_drawer(qc_scheduled) pm = PassManager( [ ALAPSchedule(durations, clbit_write_latency=1600, conditional_latency=0), PadDelay(), ] ) qc_scheduled = pm.run(qc) timeline_drawer(qc_scheduled) from qiskit.transpiler.passes import DynamicalDecoupling from qiskit.circuit.library import XGate, YGate ghz4 = QuantumCircuit(4) ghz4.h(0) ghz4.cx(0, 1) ghz4.cx(1, 2) ghz4.cx(2, 3) ghz4.draw() durations = InstructionDurations([("h", None, 160), ("x", None, 160), ("y", None, 160), ("cx", None, 800)]) dd_sequence = [XGate(), YGate(), XGate(), YGate()] pm = PassManager( [ ALAPSchedule(durations, clbit_write_latency=1600, conditional_latency=0), PadDelay(), ] ) qc_scheduled = pm.run(ghz4) timeline_drawer(qc_scheduled) pm = PassManager( [ ALAPSchedule(durations, clbit_write_latency=1600, conditional_latency=0), DynamicalDecoupling(durations, dd_sequence), ] ) qc_scheduled = pm.run(ghz4) timeline_drawer(qc_scheduled) qc_scheduled.draw() pm = PassManager( [ ALAPSchedule(durations, clbit_write_latency=1600, conditional_latency=0), DynamicalDecoupling(durations, dd_sequence, pulse_alignment=16), ] ) qc_scheduled = pm.run(ghz4) qc_scheduled.draw()
https://github.com/msramalho/Teach-Me-Quantum
msramalho
from qiskit import ClassicalRegister # Create a Classical Register with 2 bits. c = ClassicalRegister(2) from qiskit import QuantumRegister # Create a Quantum Register with 2 qubits. q = QuantumRegister(2) from qiskit import QuantumCircuit # Create a Quantum Circuit qc = QuantumCircuit(q, c) # perform a measurement of our qubits into our bits qc.measure(q, c); # ; hides the output # Jupyter command to activate matplotlib and allow the preview of our circuit %matplotlib inline from qiskit.tools.visualization import matplotlib_circuit_drawer as draw draw(qc) # visualize quantum circuit # Try both and use the one you like best from qiskit.tools.visualization import circuit_drawer as draw2 draw2(qc) # visualize quantum circuit # if you want to save it to a file from qiskit.tools.visualization import circuit_drawer diagram = circuit_drawer(qc, filename="my_first_quantum_circuit.png") diagram.show() # or even open it on an external program (no need to save first) # get the QASM representation of our circuit print(qc.qasm())
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
from qiskit import QuantumCircuit, QuantumRegister import sys import math import numpy as np class QWALK: """ Class to implement the Quantum Walk algorithm as described in Childs et al. (https://arxiv.org/abs/quant-ph/0209131) A circuit implementing the quantum walk can be generated for a given instance of a problem parameterized by N (i.e. # of vertices in a graph) by calling the gen_circuit() method. Attributes ---------- N : int number of vertices in the graph we want to perform the quantum walk on barriers : bool should barriers be included in the generated circuit regname : str optional string to name the quantum and classical registers. This allows for the easy concatenation of multiple QuantumCircuits. qr : QuantumRegister Qiskit QuantumRegister holding all of the quantum bits circ : QuantumCircuit Qiskit QuantumCircuit that represents the uccsd circuit """ def __init__(self, N, barriers=False, regname=None): # number of vertices self.N = N # set flags for circuit generation self.barriers = barriers self.k = self.gen_coloring() # NOTE: self.nq does not include the r and 0 ancilla register qubits # that are also added to the circuit. # self.nq = len(a) + len(b) # Where a and b are both 2n bitstrings as defined in Childs et al. self.nq = math.ceil(math.log2(self.N)) * 4 # create a QuantumCircuit object if regname is None: self.qr = QuantumRegister(self.nq) else: self.qr = QuantumRegister(self.nq, name=regname) self.circ = QuantumCircuit(self.qr) # Add the r and 0 ancilla registers self.ancR = QuantumRegister(1, "ancR") self.anc0 = QuantumRegister(1, "anc0") self.circ.add_register(self.ancR) self.circ.add_register(self.anc0) def gen_coloring(self): """ Generate a coloring for the graph k = poly(log(N)) """ self.k = 4 def Vc(self, c): """ Apply the Vc gate to the circuit """ def evolve_T(self, t): """ Simulate the evolution of exp(-iTt) """ def gen_circuit(self): """ Create a circuit implementing the quantum walk algorithm Returns ------- QuantumCircuit QuantumCircuit object of size nq with no ClassicalRegister and no measurements """ t = 1 for c in range(self.k): self.Vc(c) self.evolve_T(t) self.Vc(c) return self.circ
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/apcarrik/qiskit-dev
apcarrik
### Using the Matrix Product State Simulation Method import numpy as np # import qiskit from qiskit import QuantumCircuit, transpile from qiskit.providers.aer import AerSimulator # construct quantum circuit circ = QuantumCircuit(2,2) circ.h(0) circ.cx(0,1) circ.measure([0,1],[0,1]) # select the AerSimulator from the Aer provider simulator = AerSimulator(method='matrix_product_state') # run and get counts tcirc = transpile(circ, simulator) result = simulator.run(tcirc).result() counts = result.get_counts(0) print(counts) # construct quantum circuit circ = QuantumCircuit(2,2) circ.h(0) circ.cx(0,1) # define a snapshot that shows the current state vector circ.save_statevector(label='my_sv') circ.save_matrix_product_state(label='my_mps') circ.measure([0,1],[0,1]) # execute and get saved data tcirc = transpile(circ, simulator) result = simulator.run(tcirc).result() data = result.data(0) print(data) ### Testing Large EPR State Circuit num_qubits_arr = [50, 100, 500] for num_qubits in num_qubits_arr: circ = QuantumCircuit(num_qubits, num_qubits) # create EPR state circ.h(0) for i in range(0,num_qubits-1): circ.cx(i,i+1) # measure circ.measure(range(num_qubits), range(num_qubits)) tcirc = transpile(circ, simulator) result = simulator.run(tcirc).result() print("\nFor {} qubits:".format(num_qubits)) print("\tTime taken: {}s".format(result.time_taken)) print("\tCounts: ", counts)
https://github.com/arnavdas88/QuGlassyIsing
arnavdas88
from google.colab import auth # auth.authenticate_user() !curl https://sdk.cloud.google.com | bash !gcloud init !gcloud config set project "kablj-ml" # !gsutil -m cp -R gs://deepmind-research-glassy-dynamics . !gsutil -m ls -al gs://deepmind-research-glassy-dynamics !gsutil -m ls -la gs://deepmind-research-glassy-dynamics/public_dataset/ !gsutil -m ls -al gs://deepmind-research-glassy-dynamics/public_dataset/AQS/train | tail -n 1 !gsutil -m ls -al gs://deepmind-research-glassy-dynamics/public_dataset/temperature_044/train | tail -n 1 !gsutil -m ls -al gs://deepmind-research-glassy-dynamics/public_dataset/temperature_04685/train | tail -n 1 !gsutil -m ls -al gs://deepmind-research-glassy-dynamics/public_dataset/temperature_050/train | tail -n 1 !gsutil -m ls -al gs://deepmind-research-glassy-dynamics/public_dataset/temperature_056/train | tail -n 1 !gsutil -m cp -R gs://deepmind-research-glassy-dynamics/public_dataset/temperature_044/train . import pickle import os import tensorflow as tf files = os.walk("./train") base, _, lst = next(files) files = [os.path.join(base, l) for l in lst] with tf.io.gfile.GFile(files[0], 'rb') as f: data = pickle.load(f) print("Type : ", type(data)) print("Keys : ", ", \n\t".join([k for k in data])) print("Key Iterated : ") for k in data: print("\t", k, " : ", type(data[k])) print("METADATA") print(data['metadata']) with tf.io.gfile.GFile(files[0], 'rb') as f: data = pickle.load(f) time_indices = data['time_indices'] time = data ['time'] print(time_indices) for time_now in time_indices: print(time[time_now]) with tf.io.gfile.GFile(files[1], 'rb') as f: data = pickle.load(f) time_indices = data['time_indices'] time = data ['time'] print(time_indices) for time_now in time_indices: print(time[time_now]) with tf.io.gfile.GFile(files[2], 'rb') as f: data = pickle.load(f) time_indices = data['time_indices'] time = data ['time'] print(time_indices) for time_now in time_indices: print(time[time_now]) with tf.io.gfile.GFile(files[3], 'rb') as f: data = pickle.load(f) time_indices = data['time_indices'] time = data ['time'] print(time_indices) for time_now in time_indices: print(time[time_now])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.algorithms import AmplificationProblem # the state we desire to find is '11' good_state = ['11'] # specify the oracle that marks the state '11' as a good solution oracle = QuantumCircuit(2) oracle.cz(0, 1) # define Grover's algorithm problem = AmplificationProblem(oracle, is_good_state=good_state) # now we can have a look at the Grover operator that is used in running the algorithm # (Algorithm circuits are wrapped in a gate to appear in composition as a block # so we have to decompose() the op to see it expanded into its component gates.) problem.grover_operator.decompose().draw(output='mpl') from qiskit.algorithms import Grover from qiskit.primitives import Sampler grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Result type:', type(result)) print() print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) from qiskit.quantum_info import Statevector oracle = Statevector.from_label('11') problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Result type:', type(result)) print() print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) problem.grover_operator.oracle.decompose().draw(output='mpl') from qiskit.circuit.library.phase_oracle import PhaseOracle from qiskit.exceptions import MissingOptionalLibraryError # `Oracle` (`PhaseOracle`) as the `oracle` argument expression = '(a & b)' try: oracle = PhaseOracle(expression) problem = AmplificationProblem(oracle) display(problem.grover_operator.oracle.decompose().draw(output='mpl')) except MissingOptionalLibraryError as ex: print(ex) import numpy as np # Specifying `state_preparation` # to prepare a superposition of |01>, |10>, and |11> oracle = QuantumCircuit(3) oracle.ccz(0, 1, 2) theta = 2 * np.arccos(1 / np.sqrt(3)) state_preparation = QuantumCircuit(3) state_preparation.ry(theta, 0) state_preparation.ch(0,1) state_preparation.x(1) state_preparation.h(2) # we only care about the first two bits being in state 1, thus add both possibilities for the last qubit problem = AmplificationProblem(oracle, state_preparation=state_preparation, is_good_state=['110', '111']) # state_preparation print('state preparation circuit:') problem.grover_operator.state_preparation.draw(output='mpl') grover = Grover(sampler=Sampler()) result = grover.amplify(problem) print('Success!' if result.oracle_evaluation else 'Failure!') print('Top measurement:', result.top_measurement) oracle = QuantumCircuit(5) oracle.ccz(0, 1, 2) oracle.draw(output='mpl') from qiskit.circuit.library import GroverOperator grover_op = GroverOperator(oracle, insert_barriers=True) grover_op.decompose().draw(output='mpl') grover_op = GroverOperator(oracle, reflection_qubits=[0, 1, 2], insert_barriers=True) grover_op.decompose().draw(output='mpl') # a list of binary strings good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = ['11', '00'] problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # a list of integer good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = [0, 1] problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) from qiskit.quantum_info import Statevector # `Statevector` good state oracle = QuantumCircuit(2) oracle.cz(0, 1) good_state = Statevector.from_label('11') problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # Callable good state def callable_good_state(bitstr): if bitstr == "11": return True return False oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=good_state) print(problem.is_good_state('11')) # integer iteration oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=1) # list iteration oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=[1, 2, 3]) # using sample_from_iterations oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11']) grover = Grover(iterations=[1, 2, 3], sample_from_iterations=True) iterations = Grover.optimal_num_iterations(num_solutions=1, num_qubits=8) iterations def to_DIAMACS_CNF_format(bit_rep): return [index+1 if val==1 else -1 * (index + 1) for index, val in enumerate(bit_rep)] oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=['11'], post_processing=to_DIAMACS_CNF_format) problem.post_processing([1, 0, 1]) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/abbarreto/qiskit2
abbarreto
cos(-2*pi/3), sin(-2*pi/3), cos(-4*pi/3), sin(-4*pi/3), cos(-8*pi/3), sin(-8*pi/3)
https://github.com/sebasmos/QuantumVE
sebasmos
import os MODEL_METADATA = "SVM" model_name = "efficientnet_b3_embeddings_finetuning" EXPERIMENT_NAME = "efficientnet_b3_embeddings_"#"efficientnet_v2_m"#"convnext_base"#"efficientnet_b3"#"mobileNet" results_path = f"{model_name}/{MODEL_METADATA}" os.makedirs(results_path, exist_ok = True) train_path = f"{model_name}/train" val_path = f"{model_name}/val" os.makedirs(train_path, exist_ok = True) os.makedirs(val_path, exist_ok=True) import sys sys.path.insert(0,'../') # from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd import argparse import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter # import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image # import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score import torch.optim as optim import torch.nn as nn import torch import PIL import pandas as pd import torch import numpy as np import pandas as pd from tqdm import tqdm import os import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score from sklearn.metrics import precision_score, recall_score, f1_score, fbeta_score import numpy as np from torchvision import datasets, transforms from timm.data import create_transform # from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD IMAGENET_DEFAULT_MEAN = np.array([0.485, 0.456, 0.406]) IMAGENET_DEFAULT_STD = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * IMAGENET_DEFAULT_STD + IMAGENET_DEFAULT_MEAN) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def plot_multiclass_roc_curve(all_labels, all_predictions, results_path="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{results_path}/roc_curve.png') plt.show() def build_dataset(is_train, args): transform = build_transform(is_train, args) root = os.path.join(args.data_path, 'train' if is_train else 'val') dataset = datasets.ImageFolder(root, transform=transform) print(dataset) return dataset def build_transform(is_train, args): mean = IMAGENET_DEFAULT_MEAN std = IMAGENET_DEFAULT_STD # train transform if is_train: # this should always dispatch to transforms_imagenet_train transform = create_transform( input_size=args.input_size, is_training=True, color_jitter=args.color_jitter, auto_augment=args.aa, interpolation='bicubic', re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, mean=mean, std=std, ) return transform # eval transform t = [] if args.input_size <= 224: crop_pct = 224 / 256 else: crop_pct = 1.0 size = int(args.input_size / crop_pct) t.append( transforms.Resize(size, interpolation=PIL.Image.BICUBIC), # to maintain same ratio w.r.t. 224 images ) t.append(transforms.CenterCrop(args.input_size)) t.append(transforms.ToTensor()) t.append(transforms.Normalize(mean, std)) return transforms.Compose(t) # Set the seed for PyTorch torch.manual_seed(42) from sklearn.svm import SVC # Read embeddings CSV files train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv') val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv') print(f"Reading embeddings from: ", train_path) # Prepare data for training X_train = train_embeddings.iloc[:, :-1].values # Features y_train = train_embeddings.iloc[:, -1].values # Labels X_val = val_embeddings.iloc[:, :-1].values # Features y_val = val_embeddings.iloc[:, -1].values # Labels # Use los mejores parámetros encontrados best_params = {'C': 4, 'gamma': 'scale', 'kernel': 'rbf'}#{'C': 10, 'gamma': 'scale', 'kernel': 'rbf'} # Inicializa el clasificador SVM con los mejores parámetros svm_classifier = SVC(**best_params, random_state=42) svm_classifier.fit(X_train, y_train) # Predict on validation data y_pred = svm_classifier.predict(X_val) # Calculate accuracy accuracy = accuracy_score(y_val, y_pred) # Calculate precision precision = precision_score(y_val, y_pred, average='weighted') # Calculate recall recall = recall_score(y_val, y_pred, average='weighted') # Calculate F1 score f1 = f1_score(y_val, y_pred, average='weighted') # Calculate F0.75 score fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') print("Validation Accuracy:", accuracy) print("Precision:", precision) print("Recall:", recall) print("F1 Score:", f1) print("F0.75 Score:", fbeta_75) X_train.shape unique_classes = np.unique(np.concatenate(((y_pred, y_val)))) confusion_mat = confusion_matrix(y_pred, y_val, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() plot_multiclass_roc_curve(y_pred, y_val, results_path) report = classification_report(y_val,y_pred, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(results_path, f"confusion_matrix_{MODEL_METADATA}.csv")) print(df) # Calculate precision, recall, and specificity (micro-averaged) precision = precision_score(y_val, y_pred, average='micro') recall = recall_score(y_val, y_pred, average='micro') # Calculate true negatives, false positives, and specificity (micro-averaged) tn = np.sum((y_val != 1) & (y_pred != 1)) fp = np.sum((y_val != 1) & (y_pred == 1)) specificity = tn / (tn + fp) # Calculate F1 score (weighted average) f1 = f1_score(y_val, y_pred, average='weighted') fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') evaluation_metrics = { "Accuracy": accuracy, "F1 Score": f1, "F0.75 Score": fbeta_75, "Precision": precision, "Recall": recall, "Specificity": specificity } print("Evaluation Metrics:") # for metric, value in evaluation_metrics.items(): # print(f"{metric}: {value}") # Create a DataFrame from the dictionary df = pd.DataFrame(evaluation_metrics, index=[0]) # # Save the DataFrame to a CSV file df.to_csv(f'{results_path}/evaluation_metrics_for_table_{MODEL_METADATA}.csv', index=False) df from sklearn.svm import SVC # Read embeddings CSV files train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv') val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv') print(f"Reading embeddings from: ", train_path) # Prepare data for training X_train = train_embeddings.iloc[:, :-1].values # Features y_train = train_embeddings.iloc[:, -1].values # Labels X_val = val_embeddings.iloc[:, :-1].values # Features y_val = val_embeddings.iloc[:, -1].values # Labels start = 0.1 end = 100.0 step = 0.1 # Initialize variables to track best F0.75 score and its corresponding C value best_fbeta_75 = -1 best_c_val = None for c_val in np.arange(start, end + step, step): # Use los mejores parámetros encontrados best_params = {'C': c_val, 'gamma': 'scale', 'kernel': 'rbf'}#{'C': 10, 'gamma': 'scale', 'kernel': 'rbf'} # Inicializa el clasificador SVM con los mejores parámetros svm_classifier = SVC(**best_params, random_state=42) svm_classifier.fit(X_train, y_train) # Predict on validation data y_pred = svm_classifier.predict(X_val) # Calculate accuracy accuracy = accuracy_score(y_val, y_pred) # Calculate precision precision = precision_score(y_val, y_pred, average='weighted') # Calculate recall recall = recall_score(y_val, y_pred, average='weighted') # Calculate F1 score f1 = f1_score(y_val, y_pred, average='weighted') # Calculate F0.75 score fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') # Update best F0.75 score and corresponding C value if a higher score is found if fbeta_75 > best_fbeta_75: best_fbeta_75 = fbeta_75 best_c_val = c_val print(f"value of c: {c_val} ".center(60,"-")) print("Validation Accuracy:", accuracy) print("Precision:", precision) print("Recall:", recall) print("F1 Score:", f1) print("F0.75 Score:", fbeta_75) # Print the parameter C that obtains the highest F0.75 score print("Best C value:", best_c_val) print("Best F0.75 Score:", best_fbeta_75) from sklearn.model_selection import GridSearchCV from sklearn.svm import SVC # Define el rango de parámetros que deseas buscar param_grid = { 'C': [0.1,1,10,100], 'gamma': [0.1, 0.01, 0.001, 0.0001], 'kernel': ['rbf'] } # Crea un clasificador SVM svm_classifier = SVC(random_state=42) # Crea un objeto GridSearchCV grid_search = GridSearchCV(estimator=svm_classifier, param_grid=param_grid, cv=10, scoring='accuracy') # Ajusta el modelo GridSearchCV a los datos de entrenamiento grid_search.fit(X_train, y_train) # Obtiene los mejores parámetros y el mejor puntaje best_params = grid_search.best_params_ best_score = grid_search.best_score_ print("Mejores parámetros:", best_params) print("Mejor puntaje:", best_score) # Usa el mejor estimador encontrado por GridSearchCV best_svm_classifier = grid_search.best_estimator_ # Predice sobre los datos de validación usando el mejor modelo y_pred = best_svm_classifier.predict(X_val) # Calcula las métricas de evaluación accuracy = accuracy_score(y_val, y_pred) precision = precision_score(y_val, y_pred, average='weighted') recall = recall_score(y_val, y_pred, average='weighted') f1 = f1_score(y_val, y_pred, average='weighted') fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') print("Exactitud de la validación:", accuracy) print("Precisión:", precision) print("Recall:", recall) print("Puntuación F1:", f1) print("Puntuación F0.75:", fbeta_75)
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
hamburgerguy
"""Qiskit code for running Simon's algorithm on quantum hardware for 2 qubits and b = '11' """ # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle #set b equal to '11' b = '11' #1) initialize qubits n = 2 simon_circuit_2 = QuantumCircuit(n*2, n) #2) Apply Hadamard gates before querying the oracle simon_circuit_2.h(range(n)) #3) Query oracle simon_circuit_2 += simon_oracle(b) #5) Apply Hadamard gates to the input register simon_circuit_2.h(range(n)) #3) and 6) Measure qubits simon_circuit_2.measure(range(n), range(n)) # Load saved IBMQ accounts and get the least busy backend device IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Execute and monitor the job from qiskit.tools.monitor import job_monitor shots = 1024 job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval = 2) # Get results and plot counts device_counts = job.result().get_counts() plot_histogram(device_counts) #additionally, function for calculating dot product of results def bdotz(b, z): accum = 0 for i in range(len(b)): accum += int(b[i]) * int(z[i]) return (accum % 2) print('b = ' + b) for z in device_counts: print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots)) #the most significant results are those for which b dot z=0(mod 2). '''b = 11 11.00 = 0 (mod 2) (45.0%) 11.01 = 1 (mod 2) (6.2%) 11.10 = 1 (mod 2) (6.4%) 11.11 = 0 (mod 2) (42.4%)'''
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 Check Map pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.circuit.library import CXGate from qiskit.transpiler.passes import CheckMap from qiskit.transpiler import CouplingMap, Target from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestCheckMapCX(QiskitTestCase): """Tests the CheckMap pass with CX gates""" def test_trivial_nop_map(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_ = CheckMap(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_trivial_nop_map_target(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) target = Target() dag = circuit_to_dag(circuit) pass_ = CheckMap(target) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_true(self): """Mapped is easy to check qr0:--(+)-[H]-(+)- | | qr1:---.-------|-- | qr2:-----------.-- CouplingMap map: [1]--[0]--[2] """ qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.cx(qr[0], qr[2]) coupling = CouplingMap([[0, 1], [0, 2]]) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_false(self): """Needs [0]-[1] in a [0]--[2]--[1] qr0:--(+)-- | qr1:---.--- CouplingMap map: [0]--[2]--[1] """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) coupling = CouplingMap([[0, 2], [2, 1]]) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertFalse(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_false_target(self): """Needs [0]-[1] in a [0]--[2]--[1] qr0:--(+)-- | qr1:---.--- CouplingMap map: [0]--[2]--[1] """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) target = Target(num_qubits=2) target.add_instruction(CXGate(), {(0, 2): None, (2, 1): None}) dag = circuit_to_dag(circuit) pass_ = CheckMap(target) pass_.run(dag) self.assertFalse(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_cf_true(self): """Check control flow blocks are mapped.""" num_qubits = 3 coupling = CouplingMap.from_line(num_qubits) qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) true_body = QuantumCircuit(qr, cr) true_body.swap(0, 1) true_body.cx(2, 1) circuit.if_else((cr[0], 0), true_body, None, qr, cr) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_cf_false(self): """Check control flow blocks are not mapped.""" num_qubits = 3 coupling = CouplingMap.from_line(num_qubits) qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) true_body = QuantumCircuit(qr) true_body.cx(0, 2) circuit.if_else((cr[0], 0), true_body, None, qr, []) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertFalse(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_cf_layout_change_false(self): """Check control flow blocks with layout change are not mapped.""" num_qubits = 3 coupling = CouplingMap.from_line(num_qubits) qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) true_body = QuantumCircuit(qr, cr) true_body.cx(1, 2) circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], cr) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertFalse(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_cf_layout_change_true(self): """Check control flow blocks with layout change are mapped.""" num_qubits = 3 coupling = CouplingMap.from_line(num_qubits) qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) true_body = QuantumCircuit(qr) true_body.cx(0, 2) circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], []) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_swap_mapped_cf_different_bits(self): """Check control flow blocks with layout change are mapped.""" num_qubits = 3 coupling = CouplingMap.from_line(num_qubits) qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) true_body = QuantumCircuit(3, 1) true_body.cx(0, 2) circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], [cr[0]]) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_disjoint_controlflow_bits(self): """test control flow on with different registers""" num_qubits = 4 coupling = CouplingMap.from_line(num_qubits) qr1 = QuantumRegister(4, "qr") qr2 = QuantumRegister(3, "qrif") cr = ClassicalRegister(3) circuit = QuantumCircuit(qr1, cr) true_body = QuantumCircuit(qr2, [cr[0]]) true_body.cx(0, 2) circuit.if_else((cr[0], 0), true_body, None, qr1[[1, 0, 2]], [cr[0]]) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_nested_controlflow_true(self): """Test nested controlflow with true evaluation.""" num_qubits = 4 coupling = CouplingMap.from_line(num_qubits) qr1 = QuantumRegister(4, "qr") qr2 = QuantumRegister(3, "qrif") cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(1) circuit = QuantumCircuit(qr1, cr1) true_body = QuantumCircuit(qr2, cr2) for_body = QuantumCircuit(3) for_body.cx(0, 2) true_body.for_loop(range(5), body=for_body, qubits=qr2, clbits=[]) circuit.if_else((cr1[0], 0), true_body, None, qr1[[1, 0, 2]], cr1) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertTrue(pass_.property_set["is_swap_mapped"]) def test_nested_controlflow_false(self): """Test nested controlflow with true evaluation.""" num_qubits = 4 coupling = CouplingMap.from_line(num_qubits) qr1 = QuantumRegister(4, "qr") qr2 = QuantumRegister(3, "qrif") cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(1) circuit = QuantumCircuit(qr1, cr1) true_body = QuantumCircuit(qr2, cr2) for_body = QuantumCircuit(3) for_body.cx(0, 2) true_body.for_loop(range(5), body=for_body, qubits=qr2, clbits=[]) circuit.if_else((cr1[0], 0), true_body, None, qr1[[0, 1, 2]], cr1) dag = circuit_to_dag(circuit) pass_ = CheckMap(coupling) pass_.run(dag) self.assertFalse(pass_.property_set["is_swap_mapped"]) def test_nested_conditional_unusual_bit_order(self): """Test that `CheckMap` succeeds when inner conditional blocks have clbits that are involved in their own (nested conditionals), and the binding order is not the same as the bit-definition order. See gh-10394.""" qr = QuantumRegister(2, "q") cr1 = ClassicalRegister(2, "c1") cr2 = ClassicalRegister(2, "c2") # Note that the bits here are not in the same order as in the outer circuit object, but they # are the same as the binding order in the `if_test`, so everything maps `{x: x}` and it # should all be fine. This kind of thing is a staple of the control-flow builders. inner_order = [cr2[0], cr1[0], cr2[1], cr1[1]] inner = QuantumCircuit(qr, inner_order, cr1, cr2) inner.cx(0, 1).c_if(cr2, 3) outer = QuantumCircuit(qr, cr1, cr2) outer.if_test((cr1, 3), inner, outer.qubits, inner_order) pass_ = CheckMap(CouplingMap.from_line(2)) pass_(outer) self.assertTrue(pass_.property_set["is_swap_mapped"]) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.tools.visualization import circuit_drawer q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/peiyong-addwater/Hackathon-QNLP
peiyong-addwater
import collections import pickle import warnings warnings.filterwarnings("ignore") import os from random import shuffle import random from discopy.tensor import Tensor from discopy import Word from discopy.rigid import Functor from discopy import grammar import seaborn as sns import pandas as pd import matplotlib.pyplot as plt from jax import numpy as jnp import numpy as np from lambeq import AtomicType, IQPAnsatz, remove_cups, NumpyModel, spiders_reader from lambeq import BobcatParser, TreeReader, cups_reader, DepCCGParser from lambeq import Dataset from lambeq import QuantumTrainer, SPSAOptimizer from lambeq import TketModel from lambeq import Rewriter from pytket.extensions.qiskit import AerBackend import seaborn as sns import matplotlib.pyplot as plt from pytket.circuit.display import render_circuit_jupyter pd.set_option('display.width', 1000) pd.options.display.max_colwidth=80 print(os.getcwd()) warnings.filterwarnings("ignore") os.environ["TOKENIZERS_PARALLELISM"] = "false" BATCH_SIZE = 20 EPOCHS = 50 SEED = 0 TRAIN_INDEX_RATIO = 0.02 VAL_INDEX_RATIO = TRAIN_INDEX_RATIO + 0.001 TEST_INDEX_RATIO = VAL_INDEX_RATIO + 0.001 assert TEST_INDEX_RATIO <= 1 def load_pickled_dict_to_df(filename): saved_dict = pickle.load(open(filename, 'rb')) df = pd.DataFrame.from_dict(saved_dict) df = df.sample(frac=1, random_state=SEED).reset_index(drop=True) sentiment = [] for i in df['target']: if i == "Positive": sentiment.append(1) else: sentiment.append(0) df["Sentiment"] = sentiment return df cleaned_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data.pkl') cleaned_lemmatized_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data_lematize.pkl') cleaned_lemmatized_stemmed_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data_stem_lematize.pkl') #cleaned_qnlp = load_pickled_dict_to_df(cleaned_qnlp_filename) cleaned_lemmatized_qnlp = load_pickled_dict_to_df(cleaned_lemmatized_qnlp_filename) cleaned__lemmatized_stemmed_qnlp = load_pickled_dict_to_df(cleaned_lemmatized_stemmed_qnlp_filename) #cleaned_qnlp.head(10) #cleaned_qnlp.info() #sns.countplot(x = "target", data = cleaned_qnlp) cleaned_lemmatized_qnlp.head(10) cleaned_lemmatized_qnlp.info() sns.countplot(x='target', data = cleaned_lemmatized_qnlp) cleaned__lemmatized_stemmed_qnlp.head(10) cleaned__lemmatized_stemmed_qnlp.info() sns.countplot(x='target', data = cleaned__lemmatized_stemmed_qnlp) # parser = BobcatParser(verbose='text') # parser = DepCCGParser(root_cats=['S[dcl]']) # parser = spiders_reader parser = TreeReader() NUM_DATA_1 = 2578 rewriter = Rewriter(['prepositional_phrase', 'determiner', 'auxiliary', 'connector', 'coordination', 'object_rel_pronoun', 'subject_rel_pronoun', 'postadverb', 'preadverb']) def rewrite(diagram): # diagram = rewriter(diagram) return remove_cups(diagram) def create_diagrams_and_labels(total_df, NUM_DATA = 2578): total_text = total_df['data'].tolist() total_labels = total_df["Sentiment"].tolist() total_labels = [[t, 1-t] for t in total_labels] # [1, 0] for positive, [0, 1] for negative train_diagrams = parser.sentences2diagrams(total_text[:round(NUM_DATA*TRAIN_INDEX_RATIO)]) train_labels = total_labels[:round(NUM_DATA*TRAIN_INDEX_RATIO)] dev_diagrams = parser.sentences2diagrams(total_text[round(NUM_DATA*TRAIN_INDEX_RATIO):round(NUM_DATA*VAL_INDEX_RATIO)]) dev_labels = total_labels[round(NUM_DATA*TRAIN_INDEX_RATIO):round(NUM_DATA*VAL_INDEX_RATIO)] test_diagrams = parser.sentences2diagrams(total_text[round(NUM_DATA*VAL_INDEX_RATIO):round(NUM_DATA*TEST_INDEX_RATIO)]) test_labels = total_labels[round(NUM_DATA*VAL_INDEX_RATIO):round(NUM_DATA*TEST_INDEX_RATIO)] return train_diagrams, train_labels, dev_diagrams, dev_labels, test_diagrams, test_labels raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(cleaned__lemmatized_stemmed_qnlp, NUM_DATA_1) print(len(raw_train_diagrams_1)) raw_train_diagrams_1[0].draw(figsize=(12,3)) train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1] dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1] test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1] train_diagrams_1[0].draw(figsize=(6,5)) alternate_parser = BobcatParser(verbose='text') dig_0 = alternate_parser.sentence2diagram(cleaned__lemmatized_stemmed_qnlp['data'].tolist()[0]) grammar.draw(dig_0, figsize=(14,3), fontsize=12) ansatz_1 = IQPAnsatz({AtomicType.NOUN: 1, AtomicType.SENTENCE: 1, AtomicType.PREPOSITIONAL_PHRASE: 1, AtomicType.NOUN_PHRASE:1, AtomicType.CONJUNCTION:1}, n_layers=1, n_single_qubit_params=3) train_circuits_1 = [ansatz_1(diagram) for diagram in train_diagrams_1] dev_circuits_1 = [ansatz_1(diagram) for diagram in dev_diagrams_1] test_circuits_1 = [ansatz_1(diagram) for diagram in test_diagrams_1] train_circuits_1[0].draw(figsize=(9, 12)) # train_circuits_1[0].draw(figsize=(9, 12)) render_circuit_jupyter(train_circuits_1[0].to_tk()) [(s, s.size) for s in train_circuits_1[0].free_symbols] all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1 from sympy import default_sort_key vocab_1 = sorted( {sym for circ in all_circuits_1 for sym in circ.free_symbols}, key=default_sort_key ) print(len(vocab_1)) params_1 = jnp.array(np.random.rand(len(vocab_1))) from tqdm.notebook import tqdm np_circuits = [] for c in tqdm(train_circuits_1): np_circuits.append(c.lambdify(*vocab_1)(*params_1)) for c in tqdm(np_circuits): print(c.eval().array) def sigmoid(x): return 1 / (1 + jnp.exp(-x)) def loss_1(tensors): # Lambdify np_circuits = [c.lambdify(*vocab_1)(*tensors) for c in train_circuits_1] # Compute predictions predictions = sigmoid(jnp.array([[jnp.real(jnp.conjugate(c.eval().array[0])*c.eval().array[0]), jnp.real(jnp.conjugate(c.eval().array[1])*c.eval().array[1])] for c in np_circuits])) # binary cross-entropy loss cost = -jnp.sum(train_targets_1 * jnp.log2(predictions)) / len(train_targets_1) return cost from jax import jit, grad training_loss = jit(loss_1) gradient = jit(grad(loss_1)) training_losses = [] LR = 1.0 for i in range(EPOCHS): gr = gradient(params_1) params_1 = params_1 - LR*gr training_losses.append(float(training_loss(params_1))) if (i + 1) % 1 == 0: print(f"Epoch {i + 1} - loss {training_losses[-1]}")
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
import numpy as np from scipy.optimize import minimize import qiskit from qiskit import Aer, QuantumCircuit from qiskit.utils import QuantumInstance from matplotlib import pyplot as plt from qiskit_machine_learning.neural_networks import CircuitQNN # linear entangler (as in scales linearly with trash qubits) def get_entangler_map(L, num_trash, i_permut=1): result = [] nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly for i in range(L-num_trash): result.append((repeated[i_permut + i], nums_compressed[i])) return result def QAE_Ansatz(L,num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"): entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)] return qiskit.circuit.library.TwoLocal(L, parametrized_gate, entangling_gate, entanglement, reps=num_trash, insert_barriers=insert_barriers, ) QAE_Ansatz(6,2,insert_barriers=True).draw("mpl") QAE_Ansatz(5,2,insert_barriers=True).draw("mpl") QAE_Ansatz(7,2,insert_barriers=True).draw("mpl") QAE_Ansatz(6,3,insert_barriers=True).draw("mpl") # more complicated and as far as i can tell exponential def get_entangler_map_exp(L, num_trash, i_permut=0): result = [] nums = list(range(L)) nums_compressed = nums.copy()[:L-num_trash] nums_trash = nums.copy()[-num_trash:] #print(nums, nums_compressed, nums_trash) # combine all trash qubits with themselves for trash_q in nums_trash[:-1]: result.append((trash_q+1,trash_q)) # combine each of the trash qubits with every n-th permutations = list(itertools.permutations(nums_trash)) for _,trash_q in enumerate(permutations[i_permut]): for comp_q in nums_compressed[_%num_trash::num_trash]: # combine each trash_q with even or odd site result.append((trash_q, comp_q)) return result # Use Qiskit layer generator thingy because now it has everything it needs to get a gradient! # Note that it has redundant Ry rotations at the end on the compression qubits, didnt find a clever way how to get rid of them, but this shouldnt change too much # variational ansatz sub-circuit ansatz = QAE_Ansatz(6,2) # measurement circuit qreg = qiskit.QuantumRegister(L, 'q') creg = qiskit.ClassicalRegister(2, 'c') measurement_circ = qiskit.QuantumCircuit(qreg, creg) measurement_circ.measure(qreg[4], creg[0]) measurement_circ.measure(qreg[5], creg[1]) circ2 = ansatz + measurement_circ circ2.decompose() #print(circ2) #measurement_circ.draw("mpl") circ2.draw("mpl") qi_qasm = QuantumInstance(Aer.get_backend('qasm_simulator'), shots=10) qi_sv = QuantumInstance(Aer.get_backend('statevector_simulator')) qnn4 = CircuitQNN(circ2, [], circ2.parameters, sparse=False, quantum_instance=qi_qasm) input4 = np.random.rand(qnn4.num_inputs) weights4 = np.random.rand(qnn4.num_weights) qnn4.forward(input4, weights4) qnn4.backward(input4, weights4) from qiskit.algorithms.variational_algorithm import VariationalAlgorithm VariationalAlgorithm(ansatz = circ2, optimizer = None) qiskit.__version__ import qiskit import numpy as np L = 6 def create_map(L): return [(i,i+1) for i in np.arange(L-1)] map1 = create_map(L) print(map1) map_by_hand1 = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)] print(map_by_hand1) map1 == map_by_hand1 ansatz = qiskit.circuit.library.TwoLocal(L,"ry","cz",[map_by_hand1],reps=2, insert_barriers=True) ansatz.draw("mpl") ansatz = qiskit.circuit.library.TwoLocal(L,"ry","cz",[map1],reps=2, insert_barriers=True) ansatz.draw("mpl") map1 = get_entangler_map(6,2) map2 = get_entangler_map(6,2,1) print(map1) print(map2) ansatz = qiskit.circuit.library.TwoLocal(L,"ry","cz",[map1,map2],reps=2, insert_barriers=True) ansatz.draw("mpl") ansatz = qiskit.circuit.library.TwoLocal(L,"ry","cz",[map_by_hand],reps=2, insert_barriers=True) ansatz.draw("mpl")
https://github.com/iqm-finland/qiskit-on-iqm
iqm-finland
# Copyright 2022 Qiskit on IQM developers # # 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. """Testing Qiskit to IQM conversion tools. """ import pytest from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from iqm.qiskit_iqm.qiskit_to_iqm import MeasurementKey @pytest.fixture() def circuit() -> QuantumCircuit: return QuantumCircuit(3, 3) def test_measurement_key_to_str(): mk = MeasurementKey('abc', 1, 2, 3) assert str(mk) == 'abc_1_2_3' def test_measurement_key_from_clbit(): qreg = QuantumRegister(3) creg1, creg2 = ClassicalRegister(2, name='cr1'), ClassicalRegister(1, name='cr2') circuit = QuantumCircuit(qreg, creg1, creg2) mk1 = MeasurementKey.from_clbit(creg1[0], circuit) mk2 = MeasurementKey.from_clbit(creg1[1], circuit) mk3 = MeasurementKey.from_clbit(creg2[0], circuit) assert str(mk1) == 'cr1_2_0_0' assert str(mk2) == 'cr1_2_0_1' assert str(mk3) == 'cr2_1_1_0' @pytest.mark.parametrize('key_str', ['abc_4_5_6', 'a_bc_4_5_6']) def test_measurement_key_from_string(key_str): mk = MeasurementKey.from_string(key_str) assert str(mk) == key_str
https://github.com/sergiogh/qpirates-qiskit-notebooks
sergiogh
# importing Qiskit from qiskit import IBMQ, Aer from qiskit import QuantumCircuit, execute jokes = [ "I also have a wavefunction joke but I'm afraid that it will collapse", "I have a unique quantum joke because I am pretty sure it cannot be cloned.", "I have a joke about quantum physics, but nobody gets it - not even me.", "I have a quantum computing joke, but it may have decohered.", "I could tell an entanglement joke, but you already know the second half.", "I have a quantum computing joke, but it may and may not be more funny than a classical computing joke.", "I have a quantum diamond joke but it has a defect.", "I have a quantum entanglement joke, but finding a witness to it is NP-hard.", "I have a quantum computing opinion, but it's just a projection.", "All quantum computing jokes are so entangling", "I have a quantum computing joke, but it’s too nisqué.", "I have a joke about quantum computing, but I’ll tell you when it’s less noisy.", "I'll probably have a quantum computing joke about 30 years from now.", "I won't tell my joke about Quantum Computing, it's a bit cold.", "I have a joke about quantum computing, but it’s not yet error corrected.", "I have a quantum computing joke. Once built it is going to profoundly change the way we do humor.", "It has come to the University’s attention that people really like science jokes. We aim to form a committee in the next 2-3 months made up of selected candidates that will come up with our own, school-approved joke. Please be patient and be on the lookout for our correspondence.", "There’s a 50/50 chance I have a quantum joke.", "I have a quantum computing joke, but it will take you at least from 5 to 15 years to get it." ] qubits = len(bin(len(jokes))[2:]) print("Jokes: %s, Need %s Qubits" % (len(jokes), qubits)) qc = QuantumCircuit(qubits) qc.h(range(qubits)) # TODO: Interfere or remove additional states not in the length of # the solution. I.e. If 8 strings, max binary rep is 1000 qc.measure_all() qc.draw('mpl') # Clasically it will be easier to just repeat the simulation if we get an out of bounds result :) while True: backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1 ) result = job.result().get_counts() joke = int(list(result)[0],2) if (joke - 1 < len(jokes)): break print(jokes[joke-1])
https://github.com/Slimane33/QuantumClassifier
Slimane33
import numpy as np from qiskit import * from qiskit.tools.jupyter import * import matplotlib.pyplot as plt from scipy.optimize import minimize from sklearn.preprocessing import Normalizer backend = BasicAer.get_backend('qasm_simulator') def get_angles(x): beta0 = 2 * np.arcsin(np.sqrt(x[1]) ** 2 / np.sqrt(x[0] ** 2 + x[1] ** 2 + 1e-12)) beta1 = 2 * np.arcsin(np.sqrt(x[3]) ** 2 / np.sqrt(x[2] ** 2 + x[3] ** 2 + 1e-12)) beta2 = 2 * np.arcsin( np.sqrt(x[2] ** 2 + x[3] ** 2) / np.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2 + x[3] ** 2) ) return np.array([beta2, -beta1 / 2, beta1 / 2, -beta0 / 2, beta0 / 2]) data = np.loadtxt("iris_classes1and2_scaled.txt") X = data[:, 0:2] print("First X sample (original) :", X[0]) # pad the vectors to size 2^2 with constant values padding = 0.3 * np.ones((len(X), 1)) X_pad = np.c_[np.c_[X, padding], np.zeros((len(X), 1))] print("First X sample (padded) :", X_pad[0]) # normalize each input normalization = np.sqrt(np.sum(X_pad ** 2, -1)) X_norm = (X_pad.T / normalization).T print("First X sample (normalized):", X_norm[0]) # angles for state preparation are new features features = np.array([get_angles(x) for x in X_norm]) print("First features sample :", features[0]) Y = (data[:, -1] + 1) / 2 def statepreparation(a, circuit, target): a = 2*a circuit.ry(a[0], target[0]) circuit.cx(target[0], target[1]) circuit.ry(a[1], target[1]) circuit.cx(target[0], target[1]) circuit.ry(a[2], target[1]) circuit.x(target[0]) circuit.cx(target[0], target[1]) circuit.ry(a[3], target[1]) circuit.cx(target[0], target[1]) circuit.ry(a[4], target[1]) circuit.x(target[0]) return circuit x = X_norm[0] ang = get_angles(x) q = QuantumRegister(2) c = ClassicalRegister(1) circuit = QuantumCircuit(q,c) circuit = statepreparation(ang, circuit, [0,1]) circuit.draw(output='mpl') def u_gate(param, circuit, target): '''Return the quantum circuit with u3 gate applied on qubit target with param as an iterable''' circuit.u3(param[0],param[1],param[2],target) return circuit def cu_gate(param, circuit, control, target): '''Return the quantum circuit with cu3 gate applied on qubit target with param as an iterable wrt control''' circuit.cu3(param[0],param[1],param[2], control, target) return circuit def circuit_block(param, circuit, target, same_order_x=True): '''Return the block applied on qubits target from the circuit circuit - param : array parameters for the two u gate - target : array of integer the numero of qubits for the u gates to be applied - if same_order_x == True : cx(target[0], target[1]) else: cx(target[1], target[0])''' circuit = u_gate(param[0], circuit, target[0]) circuit = u_gate(param[1], circuit, target[1]) if same_order_x: circuit.cx(target[0], target[1]) else: circuit.cx(target[1], target[0]) return circuit def c_circuit_block(param, circuit, control, target, same_order_x=True): '''Return the controlled block applied on qubits target from the circuit circuit - param : array parameters for the two u gate - target : array of integer the numero of qubits for the u gates to be applied - if same_order_x == True : cx(target[0], target[1]) else: cx(target[1], target[0])''' circuit = cu_gate(param[0], circuit, control, target[0]) circuit = cu_gate(param[1], circuit, control, target[1]) if same_order_x: circuit.ccx(control, target[0], target[1]) else: circuit.ccx(control, target[1], target[0]) return circuit def create_circuit(param, circuit, target): order = True for i in range(param.shape[0]): circuit = circuit_block(param[i], circuit, target, order) order = not order return circuit def create_c_circuit(param, circuit, control, target): order = True for i in range(param.shape[0]): circuit = c_circuit_block(param[i], circuit, control, target, order) order = not order return circuit x = np.array([0.53896774, 0.79503606, 0.27826503, 0.0]) ang = get_angles(x) params = np.array([[[np.pi/3,np.pi/3,np.pi/4], [np.pi/6,np.pi/4,np.pi/6]], [[np.pi/6,np.pi/4,np.pi/4], [np.pi/3,np.pi/7,np.pi/6]], [[np.pi/3,np.pi/3,np.pi/4], [np.pi/6,np.pi/4,np.pi/6]], [[np.pi/6,np.pi/4,np.pi/4], [np.pi/3,np.pi/7,np.pi/6]]]) q = QuantumRegister(2) c = ClassicalRegister(1) circuit = QuantumCircuit(q,c) circuit = statepreparation(ang, circuit, [0,1]) circuit = create_circuit(params, circuit, [0,1]) circuit.measure(0,c) circuit.draw(output='mpl') def execute_circuit(params, angles=None, x=None, use_angles=True, bias=0, shots=1000): if not use_angles: angles = get_angles(x) q = QuantumRegister(2) c = ClassicalRegister(1) circuit = QuantumCircuit(q,c) circuit = statepreparation(angles, circuit, [0,1]) circuit = create_circuit(params, circuit, [0,1]) circuit.measure(0,c) result = execute(circuit,backend,shots=shots).result() counts = result.get_counts(circuit) result=np.zeros(2) for key in counts: result[int(key,2)]=counts[key] result/=shots return result[1] + bias execute_circuit(params, ang, bias=0.02) def predict(probas): return (probas>=0.5)*1 def binary_crossentropy(labels, predictions): loss = 0 for l, p in zip(labels, predictions): loss = loss - l * np.log(np.max([p,1e-8])) loss = loss / len(labels) return loss 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 cost(params, features, labels): predictions = [execute_circuit(params, angles=f) for f in features] return binary_crossentropy(labels, predictions) 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 real(param1, param2, angles, shots=1000): """Returns Re{<circuit(param2)|sigma_z|circuit(param1)>}""" q = QuantumRegister(3) c = ClassicalRegister(1) circuit = QuantumCircuit(q,c) circuit.h(q[0]) circuit = statepreparation(angles, circuit, [1,2]) circuit = create_c_circuit(param1, circuit, 0, [1,2]) circuit.cz(q[0], q[1]) circuit.x(q[0]) circuit = create_c_circuit(param2, circuit, 0, [1,2]) circuit.x(q[0]) circuit.h(q[0]) circuit.measure(q[0],c) result = execute(circuit,backend,shots=shots).result() counts = result.get_counts(circuit) result=np.zeros(2) for key in counts: result[int(key,2)]=counts[key] result/=shots return (2*result[0]-1) def imaginary(param1, param2, angles, shots=1000): """Returns Im{<circuit(param2)|sigma_z|circuit(param1)>}""" q = QuantumRegister(3) c = ClassicalRegister(1) circuit = QuantumCircuit(q,c) circuit.h(q[0]) circuit = statepreparation(angles, circuit, [1,2]) circuit = create_c_circuit(param1, circuit, 0, [1,2]) circuit.cz(q[0], q[1]) circuit.x(q[0]) circuit = create_c_circuit(param2, circuit, 0, [1,2]) circuit.x(q[0]) circuit.u1(np.pi/2, q[0]) circuit.h(q[0]) circuit.measure(q[0],c) result = execute(circuit,backend,shots=shots).result() counts = result.get_counts(circuit) result=np.zeros(2) for key in counts: result[int(key,2)]=counts[key] result/=shots return -(2*result[0]-1) def gradients(params, angles, label, bias=0): grads = np.zeros_like(params) imag = imaginary(params, params, angles) for i in range(params.shape[0]): for j in range(params.shape[1]): params_bis = np.copy(params) params_bis[i,j,0]+=np.pi grads[i,j,0] = -0.5 * real(params, params_bis, angles) params_bis[i,j,0]-=np.pi params_bis[i,j,1]+=np.pi grads[i,j,1] = 0.5 * (imaginary(params, params_bis, angles) - imag) params_bis[i,j,1]-=np.pi params_bis[i,j,2]+=np.pi grads[i,j,2] = 0.5 * (imaginary(params, params_bis, angles) - imag) params_bis[i,j,2]-=np.pi p = execute_circuit(params, angles, bias=bias) grad_bias = (p - label) / (p * (1 - p)) grads *= grad_bias return grads, grad_bias np.random.seed(0) num_data = len(Y) num_train = int(0.75 * num_data) index = np.random.permutation(range(num_data)) feats_train = features[index[:num_train]] Y_train = Y[index[:num_train]] feats_val = features[index[num_train:]] Y_val = Y[index[num_train:]] # We need these later for plotting X_train = X[index[:num_train]] X_val = X[index[num_train:]] layers = 6 params_init = np.random.randn(layers,2,3) * 0.01 bias_init = 0.01 batch_size = 5 learning_rate = 0.01 momentum = 0.9 var = np.copy(params_init) bias = bias_init v = np.zeros_like(var) v_bias = 0 for it in range(15): # Update the weights by one optimizer step batch_index = np.random.randint(0, num_train, (batch_size,)) feats_train_batch = feats_train[batch_index] Y_train_batch = Y_train[batch_index] grads = np.zeros_like(var) grad_bias = 0 var_corrected = var + momentum * v bias_corrected = bias + momentum * v_bias for j in range(batch_size): g, g_bias = gradients(var_corrected, feats_train_batch[j], Y_train_batch[j], bias) grads += g / batch_size grad_bias +=g_bias / batch_size v = momentum * v - learning_rate * grads v_bias = momentum * v_bias - learning_rate * grad_bias var += v bias += v_bias # Compute predictions on train and validation set probas_train = np.array([execute_circuit(var, angles=f, bias=bias) for f in feats_train]) probas_val = np.array([execute_circuit(var, angles=f, bias=bias) for f in feats_val]) predictions_train = predict(probas_train) predictions_val = predict(probas_val) # Compute accuracy on train and validation set acc_train = accuracy(Y_train, predictions_train) acc_val = accuracy(Y_val, predictions_val) print( "Iter: {:5d} | Loss: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} " "".format(it + 1, cost(var, features, Y), acc_train, acc_val) ) plt.figure() cm = plt.cm.RdBu # make data for decision regions xx, yy = np.meshgrid(np.linspace(0.0, 1.5, 20), np.linspace(0.0, 1.5, 20)) X_grid = [np.array([x, y]) for x, y in zip(xx.flatten(), yy.flatten())] # preprocess grid points like data inputs above padding = 0.3 * np.ones((len(X_grid), 1)) X_grid = np.c_[np.c_[X_grid, padding], np.zeros((len(X_grid), 1))] # pad each input normalization = np.sqrt(np.sum(X_grid ** 2, -1)) X_grid = (X_grid.T / normalization).T # normalize each input features_grid = np.array( [get_angles(x) for x in X_grid] ) # angles for state preparation are new features predictions_grid = [execute_circuit(var, angles=f, bias=bias, shots=10000) for f in features_grid] Z = np.reshape(predictions_grid, xx.shape) # plot decision regions cnt = plt.contourf(xx, yy, Z, levels=np.arange(0, 1.1, 0.1), cmap=cm, alpha=0.8, extend="both") plt.contour(xx, yy, Z, levels=[0.0], colors=("black",), linestyles=("--",), linewidths=(0.8,)) plt.colorbar(cnt, ticks=[0, 0, 1]) # plot data plt.scatter( X_train[:, 0][Y_train == 1], X_train[:, 1][Y_train == 1], c="b", marker="o", edgecolors="k", label="class 1 train", ) plt.scatter( X_val[:, 0][Y_val == 1], X_val[:, 1][Y_val == 1], c="b", marker="^", edgecolors="k", label="class 1 validation", ) plt.scatter( X_train[:, 0][Y_train == 0], X_train[:, 1][Y_train == 0], c="r", marker="o", edgecolors="k", label="class 0 train", ) plt.scatter( X_val[:, 0][Y_val == 0], X_val[:, 1][Y_val == 0], c="r", marker="^", edgecolors="k", label="class 0 validation", ) plt.legend() plt.show()
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qrx = QuantumRegister(1, 'q0') qry = QuantumRegister(1, 'q1') cr = ClassicalRegister(1, 'c') qc = QuantumCircuit(qrx, qry, cr) qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() qc.x(qry) qc.barrier() qc.h(qrx) qc.h(qry) qc.measure(qrx, cr) qc.draw("mpl") from qiskit import execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram sim = AerSimulator() job = execute(qc, backend = sim, shots = 1000) result = job.result() counts = result.get_counts(qc) print("Counts: ", counts) plot_histogram(counts) from qiskit import QuantumCircuit, IBMQ, execute from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram IBMQ.save_account('your_token') IBMQ.load_account() IBMQ.providers() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') qcomp = provider.get_backend('ibmq_manila') job = execute(qc, backend = qcomp, shots = 1000) job_monitor(job) result = job.result() counts = result.get_counts(qc) print("Total counts for qubit states are:", counts) plot_histogram(counts)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit import register, available_backends, get_backend #import Qconfig and set APIToken and API url import sys sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} #set api register(qx_config['APItoken'], qx_config['url']) import math, scipy, copy, time import numpy as np def AddDelay (script,q,num,delay): for _ in range(delay): for address in range(num): script.iden(q[address]) def AddCnot(script,q,control,target,device): # set the coupling map # b in coupling_map[a] means a CNOT with control qubit a and target qubit b can be implemented # this is essentially just copy and pasted from # https://github.com/IBM/qiskit-qx-info/tree/master/backends/ibmqx3 # https://github.com/IBM/qiskit-qx-info/tree/master/backends/ibmqx5 # but with a few stylistic changes coupling_map = {} coupling_map['ibmqx3'] = {0: [1], 1: [2], 2: [3], 3: [14], 4: [3, 5], 5: [], 6: [7, 11], 7: [10], 8: [7], 9: [10, 8], 10:[], 11: [10], 12: [5, 11, 13], 13: [4, 14], 14:[], 15: [0, 14]} coupling_map['ibmqx5'] = {0:[],1:[0,2], 2:[3], 3:[4, 14], 4:[], 5:[4], 6:[5,7,11], 7:[10], 8:[7], 9:[8, 10], 10:[], 11:[10], 12:[5, 11, 13], 13:[4, 14], 14:[], 15:[0, 2, 14]} simulator = (device not in ['ibmqx3','ibmqx5']) # if simulator, just do the CNOT if simulator: script.cx(q[control], q[target]) # same if the coupling map allows it elif target in coupling_map[device][control]: script.cx(q[control], q[target]) # if it can be done the other way round we conjugate with Hadamards elif ( control in coupling_map[device][target] ): script.h(q[control]) script.h(q[target]) script.cx(q[target], q[control]) script.h(q[control]) script.h(q[target]) else: print('Qubits ' + str(control) + ' and ' + str(target) + ' cannot be entangled.') def GetAddress (codeQubit,offset,simulator): if (simulator): address = 2*codeQubit + offset else: address = (5-2*codeQubit-offset)%16 #address = (6+2*codeQubit+offset)%16 # this can be used to go clockwise instead return address def RunRepetition(bit,d,device,delay,totalRuns): # set the number of shots to use on the backend shots = 8192 # determine whether a simulator is used simulator = (device not in ['ibmqx3','ibmqx5']) # if the simulator is used, we declare the minimum number of qubits required if (simulator): num = 2*d # for the real device there are always 16 else: num = 16 repetitionScript = [] # we create a batch job of totalRuns identical runs for run in range(totalRuns): # set up registers and program q = QuantumRegister(num) c = ClassicalRegister(num) repetitionScript.append( QuantumCircuit(q, c) ) # now we insert all the quantum gates to be applied # a barrier is inserted between each section of the code to prevent the complilation doing things we don't want it to # the stored bit is initialized by repeating it across all code qubits same state # since qubits are automatically initialized as 0, we just need to do Xs if b=1 if (bit==1): for codeQubit in range(d): repetitionScript[run].x( q[GetAddress(codeQubit,0,simulator)] ) # also do it for the single qubit on the end for comparision repetitionScript[run].x( q[GetAddress(d-1,1,simulator)] ) repetitionScript[run].barrier() # if the code is simulated add rotations for error like effects (and a barrier) AddDelay(repetitionScript[run],q,num,delay) # we then start the syndrome measurements by doing CNOTs between each code qubit and the next ancilla along the line for codeQubit in range(d-1): AddCnot(repetitionScript[run],q,GetAddress(codeQubit,0,simulator),GetAddress(codeQubit,1,simulator),device) repetitionScript[run].barrier() # if the code is simulated add rotations for error like effects (and a barrier) AddDelay(repetitionScript[run],q,num,delay) # next we perform CNOTs between each code qubit and the previous ancilla along the line for codeQubit in range(1,d): AddCnot(repetitionScript[run],q,GetAddress(codeQubit,0,simulator),GetAddress(codeQubit,-1,simulator),device) repetitionScript[run].barrier() # if the code is simulated add rotations for error like effects (and a barrier) AddDelay(repetitionScript[run],q,num,delay) # all qubits are then measured for address in range(num): repetitionScript[run].measure(q[address], c[address]) # noise is turned on if simulator is used #repetitionScript[run].noise(int(simulator)) # run the job (if the device is available) backends = available_backends() backend = get_backend(device) print('Status of '+device+':',backend.status) dataNeeded = True while dataNeeded==True: if backend.status["available"] is True: print("\nThe device is available, so the following job is being submitted.\n") print(repetitionScript[1].qasm()) shots_device = 1000 job = execute(repetitionScript, backend, shots=shots, skip_translation=True) results = [] for run in range(totalRuns): results.append( job.result().get_counts(repetitionScript[run]) ) dataNeeded = False else: print("\nThe device is not available, so we will wait for a while.") time.sleep(600) # the raw data states the number of runs for which each outcome occurred # we convert this to fractions before output. for run in range(totalRuns): for key in results[run].keys(): results[run][key] = results[run][key]/shots # return the results return results def AddProbToResults(prob,string,results): if string not in results.keys(): results[string] = 0 results[string] += prob def CalculateError(encodedBit,results,table): # total prob of error will be caculated by looping over all strings # some will end up being ignored, so we'll also need to renormalize error = 0 renorm = 1 # all strings from our sample are looped over for string in results.keys(): # we find the probability P(string|encodedBit) from the lookup table right = 0 if string in table[encodedBit].keys(): right = table[encodedBit][string] # as is the probability P(string|!encodedBit) wrong = 0 if string in table[(encodedBit+1)%2].keys(): wrong = table[(encodedBit+1)%2][string] # if this is a string for which P(string|!encodedBit)>P(string|encodedBit), the decoding fails # the probabilty for this sample is then added to the error if (wrong>right): error += results[string] # if P(string|!encodedBit)=P(string|encodedBit)=0 we have no data to decode, so we should ignore this sample # otherwise if P(string|!encodedBit)=P(string|encodedBit), the decoder randomly chooses between them # P(failure|string) is therefore 0.5 in this case elif (wrong==right): if wrong==0: renorm -= results[string] else: error += 0.5*results[string] # otherwise the decoding succeeds, and we don't care about that if renorm==0: error = 1 else: error = error/renorm return error def GetData(device,minSize,maxSize,totalRuns,delay): # loop over code sizes that will fit on the chip (d=3 to d=8) for d in range(minSize,maxSize+1): print("\n\n**d = " + str(d) + "**") # get data for each encoded bit value for bit in range(2): # run the job and put results in resultsRaw results = RunRepetition(bit,d,device,delay,totalRuns) delayString = "" if delay>0: delayString = '_delay='+str(delay) for run in range(totalRuns): f = open('Repetition_Code_Results/'+device+'/results_d=' + str(d) + delayString + '_run=' + str(run) + '_bit=' + str(bit) + '.txt', 'w') f.write( str(results[run]) ) f.close() def ProcessData(device,encodedBit,minSize,maxSize,totalRuns,delay): # determine whether a simulator is used simulator = (device not in ['ibmqx3','ibmqx5']) # initialize list used to store the calculated means and variances for results from the codes codeResults = [[[0]*4 for _ in range(j)] for j in range(minSize,maxSize+1)] singleResults = [[[0]*2 for _ in range(16)] for _ in range(minSize,maxSize+1)] # singleResults[d-minSize][j][0] is the probability of state 1 for qubit j when used in a code of distance d # singleResults[d-minSize][j][1] is the variance for the above # the results will show that the case of partial decoding requires more analysis # for this reason we will also output combinedCodeResults, which is all runs of codeResults combined # here we initialize list of combined results from the code only case combinedResultsCode = [[{} for _ in range(minSize,maxSize+1) ] for _ in range(2)] for d in range(minSize,maxSize+1): # we loop over code sizes and runs to create the required dictionaries of data: # resultsFull, resultsCode and resultsSingle (and well as the things used to make them) # the results that come fresh from the backend resultsVeryRaw = [[{} for _ in range(2)] for run in range(0,totalRuns)] resultsRaw = [[{} for _ in range(2)] for run in range(0,totalRuns)] # the results from the full code (including ancillas) # resultsFull[k] gives results for the effective distance d-k code obtained by ignoring the last k code qubits and ancillas resultsFull = [[[{} for _ in range(d)] for _ in range(2)] for run in range(0,totalRuns)] # the same but with ancilla results excluded resultsCode = [[[{} for _ in range(d)] for _ in range(2)] for run in range(0,totalRuns)] # results each single bit resultsSingle = [[[{} for _ in range(16)] for _ in range(2)] for run in range(0,totalRuns)] for run in range(0,totalRuns): # we get results for both possible encoded bits for bit in range(2): delayString = "" if delay>0: delayString = '_delay='+str(delay) # get results for this run from file f = open('Repetition_Code_Results/'+device+'/results_d=' + str(d) + delayString + '_run=' + str(run) + '_bit=' + str(bit) + '.txt') resultsVeryRaw[run][bit] = eval(f.read()) f.close() # loop over all keys in the raw results and look at the ones without strings as values # since all such entries should have a bit string as a key, we call it stringVeryRaw for stringVeryRaw in resultsVeryRaw[run][bit].keys(): if resultsVeryRaw[run][bit][stringVeryRaw] is not str: # create a new dictionary in which each key is padded to a bit string of length 16 stringRaw = stringVeryRaw.rjust(16,'0') resultsRaw[run][bit][stringRaw] = resultsVeryRaw[run][bit][stringVeryRaw] # now stringRaw only has data in the correct format # let's loop over its entries and process stuff for stringRaw in resultsRaw[run][bit].keys(): # get the prob corresponding to this string probToAdd = resultsRaw[run][bit][stringRaw] # first we deal with resultsFull and resultsCode # loop over all truncated codes relevant for this d for k in range(d): # distance of this truncated code dd = d-k # extract the bit string relevant for resultsFull # from left to right this will alternate between code and ancilla qubits in increasing order stringFull = '' for codeQubit in range(dd): # add bit value for a code qubit... stringFull += stringRaw[15-GetAddress(codeQubit,0,simulator)] if (codeQubit!=(d-1)): #...and then the ancilla next to it (if we haven't reached the end of the code) stringFull += stringRaw[15-GetAddress(codeQubit,1,simulator)] # remove ancilla bits from this to get the string for resultsCode stringCode = "" for n in range(dd): stringCode += stringFull[2*n] AddProbToResults(probToAdd,stringFull,resultsFull[run][bit][k]) AddProbToResults(probToAdd,stringCode,resultsCode[run][bit][k]) # now we'll do results single # the qubits are listed in the order they are in the code # so for each code qubit for jj in range(8): # loop over it and its neighbour for offset in range(2): stringSingle = stringRaw[15-GetAddress(jj,offset,simulator)] AddProbToResults(probToAdd,stringSingle,resultsSingle[run][bit][2*jj+offset]) # combined this run's resultsCode with the total, using the k=0 values for stringCode in resultsCode[run][bit][0].keys(): probToAdd = resultsCode[run][bit][0][stringCode]/10 AddProbToResults(probToAdd,stringCode,combinedResultsCode[bit][d-minSize]) for run in range(0,totalRuns): # initialize list used to store the calculated means and variances for results from the codes codeSample = [[0]*2 for _ in range(d)] # here # codeSample gives the results # codeSample[0] gives results for the whole code # codeSample[k][0] is the error prob when decoding uses both code and ancilla qubits # codeSample[k][1] is the error prob when decoding uses only code qubits singleSample = [0]*16 # singleSample[j] is the probability of state 1 for qubit j when the required bit value is encoded # write results in for k in range(d): # calculate look up tables by averaging over all other runs fullTable = [{} for _ in range(2)] codeTable = [{} for _ in range(2)] for b in range(2): for r in [rr for rr in range(totalRuns) if rr!=run]: for string in resultsFull[r][b][k]: AddProbToResults(resultsFull[r][b][k][string]/(totalRuns-1),string,fullTable[b]) for string in resultsCode[r][b][k]: AddProbToResults(resultsCode[r][b][k][string]/(totalRuns-1),string,codeTable[b]) # then calculate corresponding errors codeSample[k][0] = CalculateError(encodedBit,resultsFull[run][encodedBit][k],fullTable) codeSample[k][1] = CalculateError(encodedBit,resultsCode[run][encodedBit][k],codeTable) for j in range(16): if '1' in resultsSingle[run][encodedBit][j].keys(): singleSample[j] = resultsSingle[run][encodedBit][j]['1'] # add results from this run to the overall means and variances for k in range(d): for l in range(2): codeResults[d-minSize][k][2*l] += codeSample[k][l] / totalRuns # means codeResults[d-minSize][k][2*l+1] += codeSample[k][l]**2 / totalRuns # variances for j in range(16): singleResults[d-minSize][j][0] += singleSample[j] / totalRuns singleResults[d-minSize][j][1] += singleSample[j]**2 / totalRuns # finish the variances by subtracting the square of the mean for k in range(d): for l in range(1,2,4): codeResults[d-minSize][k][l] -= codeResults[d-minSize][k][l-1]**2 for j in range(16): singleResults[d-minSize][j][1] -= singleResults[d-minSize][j][0]**2 # return processed results return codeResults, singleResults, combinedResultsCode def MakeGraph(X,Y,y,axisLabel,labels=[],legendPos='upper right',verbose=False,log=False,tall=False): from matplotlib import pyplot as plt plt.rcParams.update({'font.size': 30}) markers = ["o","^","h","D","*"] # if verbose, print the numbers to screen if verbose==True: print("\nX values") print(X) for j in range(len(Y)): print("\nY values for "+labels[j]) print(Y[j]) print("\nError bars") print(y[j]) print("") # convert the variances of varY into widths of error bars for j in range(len(y)): for k in range(len(y[j])): y[j][k] = math.sqrt(y[j][k]/2) if tall: plt.figure(figsize=(20,20)) else: plt.figure(figsize=(20,10)) # add in the series for j in range(len(Y)): marker = markers[j%len(markers)] if labels==[]: plt.errorbar(X, Y[j], marker = marker, markersize=20, yerr = y[j], linewidth=5) else: plt.errorbar(X, Y[j], label=labels[j], marker = marker, markersize=20, yerr = y[j], linewidth=5) plt.legend(loc=legendPos) # label the axes plt.xlabel(axisLabel[0]) plt.ylabel(axisLabel[1]) # make sure X axis is fully labelled plt.xticks(X) # logarithms if required if log==True: plt.yscale('log') # make the graph plt.show() plt.rcParams.update(plt.rcParamsDefault) # set device to use # this also sets the maximum d. We only go up to 6 on the simulator userInput = input("Do you want results for a real device? (input Y or N) If not, results will be from a simulator. \n").upper() if (userInput=="Y"): device = 'ibmqx3' else: device = 'ibmq_qasm_simulator' # determine the delay userInput = input("What value of the delay do you want results for? \n").upper() delay = 0 try: delay = int(userInput) except: pass # determine the code sizes to be considered userInput = input("What is the minimum size code you wish to consider? (input 3, 4, 5, 6, 7 or 8) \n").upper() if userInput in ['3','4','5','6','7','8']: minSize = int(userInput) else: minSize = 3 userInput = input("What is the maximum size code you wish to consider? (input a number no less than the minimum, but no larger than 8) \n").upper() if userInput in ['3','4','5','6','7','8']: maxSize = int(userInput) else: maxSize = 8 # determine whether data needs to be taken if device=='ibmqx5': dataAlready = True else: userInput = input("Do you want to process saved data? (Y/N) If not, new data will be obtained. \n").upper() if (userInput=="Y"): dataAlready = True else: dataAlready = False # set number of runs used for stats # totalRuns is for a repetition code of length d totalRuns = 10 # if we need data, we get it if (dataAlready==False): # get the required data for the desired number of runs GetData(device,minSize,maxSize,totalRuns,delay) codeResults = [[],[]] singleResults = [[],[]] for encodedBit in range(2): try: codeResults[encodedBit], singleResults[encodedBit], combinedResultsCode = ProcessData(device,encodedBit,minSize,maxSize,totalRuns,delay) except Exception as e: print(e) # plot for single qubit data for each code distance for d in range(minSize,maxSize+1): X = range(16) Y = [] y = [] # a series for each encoded bit for encodedBit in range(2): Y.append([singleResults[encodedBit][d-minSize][j][0] for j in range(16)]) y.append([singleResults[encodedBit][d-minSize][j][1] for j in range(16)]) # make graph print("\n\n***Final state of each qubit for code of distance d = " + str(d) + "***") MakeGraph(X,Y,y,['Qubit position in code','Probability of 1']) for encodedBit in range(2): # separate plots for each encoded bit X = range(minSize,maxSize+1) Y = [] y = [] for dec in range(2): # dec=0 corresponds to full decoding, and 1 to partial Y.append([codeResults[encodedBit][d-minSize][0][2*dec+0] for d in range(minSize,maxSize+1)]) y.append([codeResults[encodedBit][d-minSize][0][2*dec+1] for d in range(minSize,maxSize+1)]) # minimum error value for the single qubit memory is found and plotted as a comparsion (with max error bars) simulator = (device not in ['ibmqx3','ibmqx5']) minSingle = min([singleResults[encodedBit][d-minSize][GetAddress(d-1,1,simulator)][0] for d in range(minSize,maxSize+1)]) maxSingle = max([singleResults[encodedBit][d-minSize][GetAddress(d-1,1,simulator)][1] for d in range(minSize,maxSize+1)]) Y.append([minSingle]*(maxSize-minSize+1)) y.append([maxSingle]*(maxSize-minSize+1)) print("\n\n***Encoded " + str(encodedBit) + "***") MakeGraph(X,Y,y,['Code distance, d','Error probability, P'], labels=['Full decoding','Partial decoding','Single qubit memory'],legendPos='lower left',log=True,verbose=True) for encodedBit in range(2): # separate plots for each encoded bit for decoding in ['full','partial']: dec = (decoding=='partial') # this is treated as 0 if full and 1 if partial X = range(1,maxSize+1) Y = [] y = [] labels = [] for d in range(minSize,maxSize+1):# series for each code size seriesY = [math.nan]*(maxSize) seriesy = [math.nan]*(maxSize) for k in range(d): seriesY[d-k-1] = codeResults[encodedBit][d-minSize][k][2*dec+0] seriesy[d-k-1] = codeResults[encodedBit][d-minSize][k][2*dec+1] Y.append(seriesY) y.append(seriesy) labels.append('d='+str(d)) print("\n\n***Encoded " + str(encodedBit) + " with " + dec*"partial" + (1-dec)*"full" + " decoding***") MakeGraph(X,Y,y,['Effective code distance','Logical error probability'], labels=labels,legendPos = 'upper right') def MakeModelTables (q,d): # outputs an array of two dictionaries for the lookup table for a simple model of a distance d code # q[0] is prob of 0->1 noise, and q[1] is prob of 1->0 # no disinction is made between strings with the same number of errors # the prob for all are assigned to a single string, all with 0s on the left and 1s on the right modelResults = [{},{}] bit = ["0","1"] for encodedBit in range(2): for errors in range(d+1): if encodedBit==0: string = "0"*(d-errors)+"1"*errors else: string = "0"*errors+"1"*(d-errors) modelResults[encodedBit][string] = scipy.special.binom(d,errors) * q[encodedBit]**errors * (1-q[encodedBit])**(d-errors) return modelResults def TotalLogical (p0,d,p1=0): # outputs total logical error prob for a single or two round code P0 = CalculateError( encodedBit, MakeModelTables([p0,p0],d)[0], MakeModelTables([p0,p0],d) ) P1 = CalculateError( encodedBit, MakeModelTables([p0,p0],d)[1], MakeModelTables([p1,p1],d) ) return P0*(1-P1) + P1*(1-P0) for encodedBit in range(2): # separate plots for each encoded bit p = [0]*2 # here is where we'll put p_0 and p_1 bar = [0]*2 for dec in [1,0]: # dec=0 corresponds to full decoding, and 1 to partial # get the results we want to fit to realResults = [codeResults[encodedBit][d-minSize][0][2*dec] for d in range(minSize,maxSize+1)] # search possible values intul we find a minimum (assumed to be global) # first we do the partial decoding to get p (which is stored in p[0]) # then the full decoding to get p[1]=p_1 minimizing = True delta = 0.001 q = delta diff =[math.inf,math.inf] while minimizing: q += delta # set new q diff[0] = diff[1] # copy diff value for last p # calculate diff for new q diff[1] = 0 for d in range(minSize,maxSize+1): if dec==1: Q = TotalLogical(q,d) else: Q = TotalLogical(p[0]-q,d,p1=q) diff[1] += ( math.log( realResults[d-minSize] ) - math.log( Q ) )**2 # see if a minimum has been found minimizing = ( diff[0]>diff[1] ) # go back a step on p to get pSum p[1-dec] = q - delta # get diff per qubit bar[1-dec] = math.exp(math.sqrt( diff[0]/(maxSize-minSize+1) )) p[0] = p[0] - p[1] # put p_0 in p[0] (instead of p) print("\n\n***Encoded " + str(encodedBit) + "***\n" ) for j in [0,1]: print(" p_"+str(j)+" = " + str(p[j]) + " with fit values typically differing by a factor of " + str(bar[j]) + "\n") plottedMinSize = max(4,minSize) # we won't print results for d=3 for clarity X = range(plottedMinSize,maxSize+1) Y = [] y = [] # original plots for dec in range(2): # dec=0 corresponds to full decoding, and 1 to partial # results from the device Y.append([codeResults[encodedBit][d-minSize][0][2*dec+0] for d in range(plottedMinSize,maxSize+1)]) y.append([codeResults[encodedBit][d-minSize][0][2*dec+1] for d in range(plottedMinSize,maxSize+1)]) # fit lines for dec in range(2): if dec==1: Y.append([TotalLogical(p[0]+p[1],d) for d in range(plottedMinSize,maxSize+1)]) else: Y.append([TotalLogical(p[0],d,p1=p[1]) for d in range(plottedMinSize,maxSize+1)]) y.append([0]*(maxSize-plottedMinSize+1)) MakeGraph(X,Y,y,['Code distance, d','Error probability, P'], labels=['Full decoding','Partial decoding','Full decoding (model)','Partial decoding (model)'],legendPos='lower left',log=True) # for each code distance and each encoded bit value, we'll create a list of the probabilities for each possible number of errors # list is initialized with zeros errorNum = [[[0]*(d+1) for d in range(minSize,maxSize+1)] for _ in range(2)] for d in range(minSize,maxSize+1): for bit in range(2): # for each code distance and each encoded bit value we look at all possible result strings for string in combinedResultsCode[bit][d-minSize]: # count the number of errors in each string num = 0 for j in range(d): num += ( int( string[j] , 2 ) + bit )%2 # add prob to corresponding number of errors errorNum[bit][d-minSize][num] += combinedResultsCode[bit][d-minSize][string] # the we make a graph for each, and print a title Y0 = [y if y>0 else math.nan for y in errorNum[0][d-minSize]] Y1 = [y if y>0 else math.nan for y in errorNum[1][d-minSize]] print("\n\n***Probability of errors on code qubits for d = " + str(d) + "***") MakeGraph(range(d+1),[Y0,Y1],[[0]*(d+1)]*2,['Number of code qubit errors','Probability (log base 10)'], labels=['Encoded 0','Encoded 1'],legendPos='upper right',log=True) # actually, we make two graphs. This one plots the number of 1s rather than errors, and so the plot for encoded 1 is inverted # Y0 in this graph is as before Y1 = Y1[::-1] # but Y1 has its order inverted print("\n\n***Probability for number of 1s in code qubit result for d = " + str(d) + "***") MakeGraph(range(d+1),[Y0,Y1],[[0]*(d+1)]*2,['Number of 1s in code qubit result','Probability (log base 10)'], labels=['Encoded 0','Encoded 1'],legendPos='center right',log=True)
https://github.com/joemoorhouse/quantum-mc
joemoorhouse
from quantum_mc.arithmetic.piecewise_linear_transform import PiecewiseLinearTransform3 import unittest import numpy as np from qiskit.circuit.library.arithmetic import weighted_adder from scipy.stats import multivariate_normal, norm from qiskit.test.base import QiskitTestCase from qiskit import execute, Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, AncillaRegister from qiskit.circuit.library import UniformDistribution, NormalDistribution, LogNormalDistribution from qiskit.quantum_info import Statevector import quantum_mc.arithmetic.multiply_add as multiply_add from qiskit.circuit.library import NormalDistribution, LogNormalDistribution, LinearAmplitudeFunction, IntegerComparator, WeightedAdder class TestArithmetic(QiskitTestCase): def test_replicate_bug(self): import numpy as np import matplotlib.pyplot as plt from qiskit import execute, Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, AncillaRegister from qiskit.aqua.algorithms import IterativeAmplitudeEstimation from qiskit.circuit.library import NormalDistribution, LogNormalDistribution, LinearAmplitudeFunction, IntegerComparator, WeightedAdder from qiskit.visualization import plot_histogram from quantum_mc.arithmetic import piecewise_linear_transform trans = PiecewiseLinearTransform3(3, 5, 5, 3, 4, 1, 7, 2) num_ancillas = trans.num_ancilla_qubits qr_input = QuantumRegister(3, 'input') qr_result = QuantumRegister(7, 'result') qr_ancilla = QuantumRegister(num_ancillas, 'ancilla') output = ClassicalRegister(7, 'output') circ = QuantumCircuit(qr_input, qr_result, qr_ancilla, output) #circ.append(normal, qr_input) # put 3 into input circ.x(qr_input[0]) circ.x(qr_input[1]) # put value 30 in result circ.x(qr_result[1]) circ.x(qr_result[2]) circ.x(qr_result[3]) circ.x(qr_result[4]) #circ.append(trans, qr_input[:] + qr_result[:] + qr_ancilla[:]) #multiply_add.classical_add_mult(circ, 3, 7, qr_input, qr_result, qr_ancilla) multiply_add.classical_mult(circ, 3, qr_input, qr_result, qr_ancilla) circ.measure(qr_result, output) counts = execute(circ, Aer.get_backend('qasm_simulator'), shots = 128).result().get_counts() np.testing.assert_equal(counts['01011'], 128) def test_adder(self): """Simple end-to-end test of the (semi-classical) multiply and add building block.""" qr_input = QuantumRegister(3, 'input') qr_result = QuantumRegister(5, 'result') qr_ancilla = QuantumRegister(5, 'ancilla') output = ClassicalRegister(5, 'output') circ = QuantumCircuit(qr_input, qr_result, qr_ancilla, output) circ.x(qr_input[0]) circ.x(qr_input[1]) circ.x(qr_input[2]) # i.e. load up 7 into register add_mult = multiply_add.classical_add_mult(circ, 2, 3, qr_input, qr_result, qr_ancilla) #circ.append(cond_add_mult, qr_input[:] + qr_result[:] + qr_ancilla[:]) for the conditional form circ.measure(qr_result, output) # 7 * 2 + 3 = 17: expect 10001 counts = execute(circ, Aer.get_backend('qasm_simulator'), shots = 128).result().get_counts() np.testing.assert_equal(counts['10001'], 128) def test_adder_subtract(self): """Simple end-to-end test of the (semi-classical) multiply and add building block.""" qr_input = QuantumRegister(3, 'input') qr_result = QuantumRegister(5, 'result') qr_ancilla = QuantumRegister(5, 'ancilla') output = ClassicalRegister(5, 'output') circ = QuantumCircuit(qr_input, qr_result, qr_ancilla, output) circ.x(qr_input[0]) circ.x(qr_input[1]) circ.x(qr_input[2]) # i.e. load up 7 into register add_mult = multiply_add.classical_add_mult(circ, 2, -3, qr_input, qr_result, qr_ancilla) #circ.append(cond_add_mult, qr_input[:] + qr_result[:] + qr_ancilla[:]) for the conditional form circ.measure(qr_result, output) # 7 * 2 - 3 = 11: expect 01011 counts = execute(circ, Aer.get_backend('qasm_simulator'), shots = 128).result().get_counts() np.testing.assert_equal(counts['01011'], 128) def test_piecewise_transform(self): import numpy as np import matplotlib.pyplot as plt from qiskit import execute, Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, AncillaRegister from qiskit.aqua.algorithms import IterativeAmplitudeEstimation from qiskit.circuit.library import NormalDistribution, LogNormalDistribution, LinearAmplitudeFunction, IntegerComparator, WeightedAdder from qiskit.visualization import plot_histogram from quantum_mc.arithmetic import piecewise_linear_transform sigma = 1 low = -3 high = 3 mu = 0 #normal = NormalDistribution(3, mu=mu, sigma=sigma**2, bounds=(low, high)) # our test piece-wise transforms: # trans0 if x <= 2, x => 6*x + 7 # trans1 if 2 < x <= 5, x => x + 17 # trans2 if x > 5, x => 3*x + 7 trans = PiecewiseLinearTransform3(2, 5, 6, 1, 3, 7, 17, 7) num_ancillas = trans.num_ancilla_qubits qr_input = QuantumRegister(3, 'input') qr_result = QuantumRegister(6, 'result') qr_ancilla = QuantumRegister(num_ancillas, 'ancilla') output = ClassicalRegister(6, 'output') circ = QuantumCircuit(qr_input, qr_result, qr_ancilla, output) #circ.append(normal, qr_input) circ.append(trans, qr_input + qr_result + qr_ancilla) circ.measure(qr_result, output) counts = execute(circ, Aer.get_backend('qasm_simulator'), shots = 128).result().get_counts() np.testing.assert_equal(counts['01011'], 128) def in_progress_test_piecewise_transform(self): """Simple end-to-end test of the (semi-classical) multiply and add building block.""" import numpy as np import matplotlib.pyplot as plt from qiskit import execute, Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, AncillaRegister from qiskit.aqua.algorithms import IterativeAmplitudeEstimation from qiskit.circuit.library import NormalDistribution, LogNormalDistribution, LinearAmplitudeFunction, IntegerComparator, WeightedAdder from qiskit.visualization import plot_histogram from quantum_mc.arithmetic import multiply_add qr_input = QuantumRegister(3, 'input') qr_result = QuantumRegister(6, 'result') qr_comp = QuantumRegister(2, 'comparisons') qr_ancilla = QuantumRegister(6, 'ancilla') qr_comp_anc = QuantumRegister(3, 'cond_ancilla') output = ClassicalRegister(6, 'output') circ = QuantumCircuit(qr_input, qr_result, qr_comp, qr_ancilla, qr_comp_anc, output) # our test piece-wise transforms: # trans0 if x <= 2, x => 6*x + 7 # trans1 if 2 < x <= 5, x => x + 17 # trans2 if x > 5, x => 3*x + 7 sigma = 1 low = -3 high = 3 mu = 0 normal = NormalDistribution(3, mu=mu, sigma=sigma**2, bounds=(low, high)) circ.append(normal, qr_input) comp0 = IntegerComparator(num_state_qubits=3, value=3, name = "comparator0") # true if i >= point comp1 = IntegerComparator(num_state_qubits=3, value=6, name = "comparator1") # true if i >= point trans0 = multiply_add.cond_classical_add_mult(6, 7, qr_input, qr_result, qr_ancilla) trans1 = multiply_add.cond_classical_add_mult(1, 17, qr_input, qr_result, qr_ancilla) trans2 = multiply_add.cond_classical_add_mult(3, 7, qr_input, qr_result, qr_ancilla) circ.append(comp0, qr_input[:] + [qr_comp[0]] + qr_ancilla[0:comp0.num_ancillas]) circ.append(comp1, qr_input[:] + [qr_comp[1]] + qr_ancilla[0:comp0.num_ancillas]) # use three additional ancillas to define the ranges circ.cx(qr_comp[0], qr_comp_anc[0]) circ.x(qr_comp_anc[0]) circ.cx(qr_comp[1], qr_comp_anc[2]) circ.x(qr_comp_anc[2]) circ.ccx(qr_comp[0], qr_comp_anc[2], qr_comp_anc[1]) circ.append(trans0, [qr_comp_anc[0]] + qr_input[:] + qr_result[:] + qr_ancilla[:]) circ.append(trans1, [qr_comp_anc[1]] + qr_input[:] + qr_result[:] + qr_ancilla[:]) circ.append(trans2, [qr_comp[1]] + qr_input[:] + qr_result[:] + qr_ancilla[:]) # can uncompute qr_comp_anc # then uncompute the comparators circ.measure(qr_result, output)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXSimple 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=IQXSimple())
https://github.com/sooodos/Quantum-Computing-Learning-Gate
sooodos
from qiskit import QuantumCircuit class SecretNUmberOracle: @classmethod def create_secret_number_oracle(cls, random_binary, eval_mode: bool) -> QuantumCircuit: n = len(random_binary) secret_number_oracle = QuantumCircuit(len(random_binary) + 1, len(random_binary)) # Use barrier as divider secret_number_oracle.barrier() # Controlled-NOT gates for qubit in range(len(random_binary)): if random_binary[qubit] == '1': secret_number_oracle.cx(qubit, n) secret_number_oracle.barrier() if not eval_mode: # Show oracle print("This is the oracle function, aka the black box. NORMALLY THIS WOULD BE HIDDEN!") print(secret_number_oracle) return secret_number_oracle
https://github.com/quantum-kittens/quantum-computing-basics
quantum-kittens
# run this cell if you're executing this notebook in your browser !pip install qiskit from IPython.display import clear_output clear_output() from qiskit import * import numpy as np n = 2 #number of qubits used for the example in this notebook from qiskit.visualization import array_to_latex target_state = [ # state vector of the target state 1/np.sqrt(n), 0, (complex(0,1))/np.sqrt(n), 0, ] array_to_latex(target_state, prefix = '|\\psi_{ts}> = ' ) # a nifty, clean latex representation target_state_mathematical = [ [1/np.sqrt(n)], [0], [(complex(0,1))/np.sqrt(n)], [0], ] array_to_latex(target_state_mathematical, prefix = 'Mathematical: |\\psi_{m}> = ' ) qr_init = QuantumRegister(n) qc_init = QuantumCircuit(qr_init) qc_init.initialize(target_state) # the initialization qc_init.draw('mpl') qr_gate = QuantumRegister(n) qc_gate = QuantumCircuit(qr_gate) qc_gate.h(qr_gate[1]) qc_gate.s(qr_gate[1]) qc_gate.draw('mpl') from qiskit.quantum_info import Statevector qc_gate_statevector = Statevector(qc_gate) # alternative: qc_gate_statevector = quantum_info.Statevector.from_instruction(qc_gate) qc_gate_statevector.draw('latex', prefix = '|\\psi_{qc-gate-statevector}> = ') backend = Aer.get_backend('statevector_simulator') #alternative: from qiskit.providers.aer import StatevectorSimulator | backend = StatevectorSimulator() job = execute(qc_gate, backend) qc_gate_state_sim = job.result().get_statevector() array_to_latex(qc_gate_state_sim, prefix = '|\\psi_{qc-gate-sim}> = ') # Note .draw() isn't used here, because .get_statevector() returns an array from qiskit.quantum_info import state_fidelity print('Target state and qc_gate_statevector: ') display(state_fidelity(target_state, qc_gate_statevector)) print('\nTarget state and qc_gate_state_sim: ') display(state_fidelity(target_state, qc_gate_state_sim)) qc_gate_statevector.draw('qsphere') from qiskit.visualization import plot_state_qsphere plot_state_qsphere(qc_gate_statevector) qc_gate_statevector.draw('bloch') from qiskit. visualization import plot_bloch_multivector plot_bloch_multivector(qc_gate_statevector) from qiskit.visualization import plot_state_paulivec plot_state_paulivec(qc_gate_statevector) from qiskit.quantum_info import DensityMatrix rho = DensityMatrix(qc_gate) #alternative: rho = quantum_info.DensityMatrix.from_instruction(qc_gate) rho.draw('latex', prefix = '\\rho = ') rho_m_matrix = np.array([[1/2,0,complex(0,-1/2),0],[0,0,0,0],[complex(0,1/2),0,1/2,0],[0,0,0,0]]) rho_m = DensityMatrix(rho_m_matrix) display(rho_m.draw('latex', prefix='\\rho = ')) ket_target_state = np.matrix(target_state).T bra_target_state = ket_target_state.conj().T display(array_to_latex(ket_target_state, prefix = '|\\psi_m> = ' )) display(array_to_latex(bra_target_state, prefix = '<\\psi_m| = ' )) target_state_matrix = np.matmul(ket_target_state, bra_target_state) rho = DensityMatrix(target_state_matrix) display(rho.draw('latex', prefix='\\rho = ')) from qiskit.visualization import plot_state_city plot_state_city(rho, color = ['teal', 'black']) # colors cuz I felt like prettying it up rho.draw('hinton') from qiskit.visualization import plot_state_hinton plot_state_hinton(rho) from qiskit.quantum_info import Statevector init_state = Statevector(qc_init) print('\n Initial state: ') display(init_state.draw('latex', prefix = '|\\psi_{ts}> =')) # create circuit with Hadamards operating on each qubit qc_hadamards = QuantumCircuit(n) qc_hadamards.h(range(n)) display(qc_hadamards.draw('mpl')) new_state = init_state.evolve(qc_hadamards) print('\n Final state: ') display(new_state.draw('latex', prefix= '|\\psi_{f}> =')) qc_combined = qc_hadamards.compose(qc_init, range(n), front = True) display(qc_combined.draw('mpl')) qc_combined_state = Statevector(qc_combined) print('\n State of circuit qc_init + qc_hadamards = ') display(qc_combined_state.draw('latex')) from qiskit.quantum_info import Operator display(rho.draw('latex', prefix='Initial State, \\rho = ')) H = Operator.from_label('H') #fetches the Hadamard display(array_to_latex(H.data, prefix ='H = ')) HH = H.expand(H) # tensor product of H with itself display(array_to_latex(HH.data, prefix ='H \\otimes H = ')) rho_HH = rho.evolve(HH) display(rho_HH.draw('latex', prefix='\\rho_f = H\\rho H^\\dagger = ')) ket_combined_state = np.matrix(qc_combined_state).T bra_combined_state = ket_combined_state.conj().T display(array_to_latex(ket_combined_state, prefix = '|\\psi_f> = ' )) display(array_to_latex(bra_combined_state, prefix = '<\\psi_f| = ' )) combined_state_matrix = np.matmul(ket_combined_state, bra_combined_state) rho_comb = DensityMatrix(combined_state_matrix) display(rho_comb.draw('latex', prefix='\\rho_f = '))
https://github.com/Qiskit/feedback
Qiskit
import numpy as np from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import GradientDescent from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import Z, I, Gradient, AerPauliExpectation from qiskit.providers.aer import AerSimulator hamiltonian = (Z ^ Z ^ I) + (Z ^ I ^ I) ansatz = EfficientSU2(3, reps=1, entanglement="linear") ansatz.decompose().draw("mpl", style="iqx") gradient = Gradient(method="param_shift") backend = AerSimulator() energies = [] def store_energy(*args): energies.append(args[2]) vqe = VQE(ansatz, optimizer=GradientDescent(maxiter=300, learning_rate=0.01, callback=store_energy), gradient=gradient, expectation=AerPauliExpectation(), initial_point=np.arange(ansatz.num_parameters), quantum_instance=backend) result = vqe.compute_minimum_eigenvalue(hamiltonian) import matplotlib.pyplot as plt plt.figure(figsize=(10, 6)) plt.plot(energies, color="royalblue", label="VQE") plt.axhline(y=-2, ls="--", color="crimson", label="target") plt.xlabel("iteration") plt.ylabel("energy"); from time import time from qiskit.opflow import CircuitSampler, StateFn num_qubits = 5 gradient = Gradient(method="param_shift") sampler = CircuitSampler(backend) hamiltonian = Z ^ 5 timings = [] for reps in range(10): circuit = EfficientSU2(num_qubits, reps=reps, entanglement="pairwise") value_dict = dict(zip(circuit.parameters, np.arange(circuit.num_parameters))) expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit) start = time() _ = sampler.convert(gradient.convert(expectation), params=value_dict).eval() timings.append(time() - start) plt.figure(figsize=(10, 6)) plt.plot(10 * (1 + np.arange(10)), timings) plt.xlabel("number of parameters") plt.ylabel("time $s$"); from surfer.gradient import ForwardGradient # classical O(d^2) method from surfer.gradient import ReverseGradient # classical O(d) method! reverse = ReverseGradient() hamiltonian = (Z ^ Z ^ I) + (Z ^ I ^ I) circuit = EfficientSU2(3, reps=1, entanglement="linear") values = np.random.random(ansatz.num_parameters) grad = reverse.compute(hamiltonian, circuit, values) print(grad) from surfer.gradient import ForwardGradient reverse_timings = [] forward_timings = [] forward = ForwardGradient() hamiltonian = Z ^ 5 for reps in range(10): circuit = EfficientSU2(num_qubits, reps=reps, entanglement="pairwise") values = np.arange(circuit.num_parameters) start = time() _ = reverse.compute(hamiltonian, circuit, values) reverse_timings.append(time() - start) circuit = circuit.decompose() start = time() _ = forward.compute(hamiltonian, circuit, values) forward_timings.append(time() - start) plt.figure(figsize=(10, 6)) plt.plot(10 * (1 + np.arange(10)), timings, label="Qiskit") plt.plot(10 * (1 + np.arange(10)), reverse_timings, label="Reverse gradients") plt.plot(10 * (1 + np.arange(10)), forward_timings, label="Forward gradients") plt.xlabel("number of parameters") plt.ylabel("time $s$") plt.legend(); from surfer.qfi import ReverseQFI reverse_qfi = ReverseQFI() circuit = EfficientSU2(3, reps=1, entanglement="linear") values = np.random.random(ansatz.num_parameters) qfi = reverse_qfi.compute(circuit, values) from qiskit.opflow import QFI num_qubits = 5 qfi = QFI() qfi_timings = [] sampler = CircuitSampler(backend) for reps in [0, 1, 2, 3, 4, 8]: circuit = EfficientSU2(num_qubits, reps=reps, entanglement="pairwise") value_dict = dict(zip(circuit.parameters, np.arange(circuit.num_parameters))) start = time() _ = sampler.convert(qfi.convert(StateFn(circuit)), params=value_dict).eval() qfi_timings.append(time() - start) num_qubits = 5 reverse_qfi_timings = [] for reps in 2 ** np.arange(6): circuit = EfficientSU2(num_qubits, reps=reps, entanglement="pairwise") values = np.arange(circuit.num_parameters) start = time() _ = reverse_qfi.compute(circuit, values) reverse_qfi_timings.append(time() - start) plt.figure(figsize=(10, 6)) plt.plot(10 * (1 + np.array([0, 1, 2, 3, 4, 8])), qfi_timings, label="Qiskit") plt.plot(10 * (1 + 2 ** np.arange(6)), reverse_qfi_timings, label="Classically efficient QFI") plt.xlabel("number of parameters") plt.ylabel("time $s$") plt.legend();
https://github.com/JavaFXpert/quantum-pong
JavaFXpert
#measurement.py from qiskit import QuantumCircuit, transpile, assemble from qiskit.visualization import plot_histogram def measurement(qc,n_l,n_b,CU,backend,shots): t = transpile(qc, backend) qobj = assemble(t, shots=shots) results = backend.run(qobj).result() answer = results.get_counts() plot_histogram(answer, title="Output Histogram").savefig('./outputs/output_histogram.png',facecolor='#eeeeee') return answer
https://github.com/BOBO1997/osp_solutions
BOBO1997
import re import itertools import numpy as np import random random.seed(42) import mitiq from qiskit import QuantumCircuit, QuantumRegister from qiskit.ignis.mitigation import expectation_value # Pauli Twirling def pauli_twirling(circ: QuantumCircuit) -> QuantumCircuit: """ [internal function] This function takes a quantum circuit and return a new quantum circuit with Pauli Twirling around the CNOT gates. Args: circ: QuantumCircuit Returns: QuantumCircuit """ def apply_pauli(num: int, qb: int) -> str: if (num == 0): return f'' elif (num == 1): return f'x q[{qb}];\n' elif (num == 2): return f'y q[{qb}];\n' else: return f'z q[{qb}];\n' paulis = [(i,j) for i in range(0,4) for j in range(0,4)] paulis.remove((0,0)) paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)] new_circ = '' ops = circ.qasm().splitlines(True) #! split the quantum circuit into qasm operators for op in ops: if (op[:2] == 'cx'): # add Pauli Twirling around the CNOT gate num = random.randrange(len(paulis)) qbs = re.findall('q\[(.)\]', op) new_circ += apply_pauli(paulis[num][0], qbs[0]) new_circ += apply_pauli(paulis[num][1], qbs[1]) new_circ += op new_circ += apply_pauli(paulis_map[num][0], qbs[0]) new_circ += apply_pauli(paulis_map[num][1], qbs[1]) else: new_circ += op return QuantumCircuit.from_qasm_str(new_circ) def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0], pt = False): """ This function outputs the circuit list for zero-noise extrapolation. Args: qcs: List[QuantumCircuit], the input quantum circuits. scale_factors: List[float], to what extent the noise scales are investigated. pt: bool, whether add Pauli Twirling or not. Returns: folded_qcs: List[QuantumCircuit] """ folded_qcs = [] #! ZNE用の回路 for qc in qcs: folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用 folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化 if pt: folded_qcs = [pauli_twirling(circ) for circ in folded_qcs] return folded_qcs def make_stf_basis(n, basis_elements = ["X","Y","Z"]): """ [internal function] This function outputs all the combinations of length n string for given basis_elements. When basis_elements is X, Y, and Z (default), the output becomes the n-qubit Pauli basis. Args: n: int basis_elements: List[str] Returns: basis: List[str] """ if n == 1: return basis_elements basis = [] for i in basis_elements: sub_basis = make_stf_basis(n - 1, basis_elements) basis += [i + j for j in sub_basis] return basis def reduce_hist(hist, poses): """ [internal function] This function returns the reduced histogram to the designated positions. Args: hist: Dict[str, float] poses: List[int] Returns: ret_hist: Dict[str, float] """ n = len(poses) ret_hist = {format(i, "0" + str(n) + "b"): 0 for i in range(1 << n)} for k, v in hist.items(): pos = "" for i in range(n): pos += k[poses[i]] ret_hist[pos] += v return ret_hist def make_stf_expvals(n, stf_hists): """ [internal function] This function create the expectations under expanded basis, which are used to reconstruct the density matrix. Args: n: int, the size of classical register in the measurement results. stf_hists: List[Dict[str, float]], the input State Tomography Fitter histograms. Returns: st_expvals: List[float], the output State Tomography expectation values. """ assert len(stf_hists) == 3 ** n stf_basis = make_stf_basis(n, basis_elements=["X","Y","Z"]) st_basis = make_stf_basis(n, basis_elements=["I","X","Y","Z"]) stf_hists_dict = {basis: hist for basis, hist in zip(stf_basis, stf_hists)} st_hists_dict = {basis: stf_hists_dict.get(basis, None) for basis in st_basis} # remaining for basis in sorted(set(st_basis) - set(stf_basis)): if basis == "I" * n: continue reduction_poses = [] reduction_basis = "" for i, b in enumerate(basis): if b != "I": reduction_poses.append(n - 1 - i) # big endian reduction_basis += b # こっちはそのまま(なぜならラベルはlittle endianだから) else: reduction_basis += "Z" st_hists_dict[basis] = reduce_hist(stf_hists_dict[reduction_basis], reduction_poses) st_expvals = dict() for basis, hist in st_hists_dict.items(): if basis == "I" * n: st_expvals[basis] = 1.0 continue st_expvals[basis], _ = expectation_value(hist) return st_expvals def zne_decoder(n, result, scale_factors=[1.0, 2.0, 3.0], fac_type="lin"): """ This function applies the zero-noise extrapolation to the measured results and output the mitigated zero-noise expectation values. Args: n: int, the size of classical register in the measurement results. result: Result, the returned results from job. scale_factors: List[float], this should be the same as the zne_wrapper. fac_type: str, "lin" or "exp", whether to use LinFactory option or ExpFactory option in mitiq, to extrapolate the expectation values. Returns: zne_expvals: List[float], the mitigated zero-noise expectation values. """ hists = result.get_counts() num_scale_factors = len(scale_factors) assert len(hists) % num_scale_factors == 0 scale_wise_expvals = [] # num_scale_factors * 64 for i in range(num_scale_factors): scale_wise_hists = [hists[3 * j + i] for j in range(len(hists) // num_scale_factors)] st_expvals = make_stf_expvals(n, scale_wise_hists) scale_wise_expvals.append( list(st_expvals.values()) ) scale_wise_expvals = np.array(scale_wise_expvals) linfac = mitiq.zne.inference.LinearFactory(scale_factors) expfac = mitiq.zne.ExpFactory(scale_factors) zne_expvals = [] for i in range(4 ** n): if fac_type == "lin": zne_expvals.append( linfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) else: zne_expvals.append( expfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) return zne_expvals
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
import warnings warnings.filterwarnings("ignore") from matplotlib import pyplot as plt import numpy as np from qiskit.circuit.library import TwoLocal from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter import sys sys.path.append("../../") from entanglement_forging import EntanglementForgedGroundStateSolver from entanglement_forging import EntanglementForgedConfig # We start by setting up the chemical problem. 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, basis="sto3g") problem = ElectronicStructureProblem(driver) problem.second_q_ops() converter = QubitConverter(JordanWignerMapper()) # Prepare the bitstrings and the ansatz bitstrings = [[1, 0], [0, 1]] ansatz = TwoLocal(2, [], "cry", [[0, 1], [1, 0]], reps=1) from qiskit import Aer backend = Aer.get_backend("qasm_simulator") config = EntanglementForgedConfig(backend=backend, copysample_job_size=100) calc = EntanglementForgedGroundStateSolver( qubit_converter=converter, ansatz=ansatz, bitstrings_u=bitstrings, config=config ) res = calc.solve(problem) res print("Energies (from only one paramset in each iteration):") plt.plot([e[0] for e in res.get_energies_history()]) plt.show() print("Schmidts (from only one paramset in each iteration):") plt.plot([s[0] for s in res.get_schmidts_history()]) plt.show() print("Parameters (from only one paramset in each iteration):") plt.plot([p[0] for p in res.get_parameters_history()]) plt.show() res import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # 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. # pylint: disable=bad-docstring-quotes,invalid-name """Quantum circuit object.""" from __future__ import annotations import collections.abc import copy import itertools import multiprocessing as mp import string import re import warnings import typing from collections import OrderedDict, defaultdict, namedtuple from typing import ( Union, Optional, Tuple, Type, TypeVar, Sequence, Callable, Mapping, Iterable, Any, DefaultDict, Literal, overload, ) import numpy as np from qiskit.exceptions import QiskitError from qiskit.utils.multiprocessing import is_main_process from qiskit.circuit.instruction import Instruction from qiskit.circuit.gate import Gate from qiskit.circuit.parameter import Parameter from qiskit.circuit.exceptions import CircuitError from qiskit.utils import optionals as _optionals from . import _classical_resource_map from ._utils import sort_parameters from .classical import expr from .parameterexpression import ParameterExpression, ParameterValueType from .quantumregister import QuantumRegister, Qubit, AncillaRegister, AncillaQubit from .classicalregister import ClassicalRegister, Clbit from .parametertable import ParameterReferences, ParameterTable, ParameterView from .parametervector import ParameterVector from .instructionset import InstructionSet from .operation import Operation from .register import Register from .bit import Bit from .quantumcircuitdata import QuantumCircuitData, CircuitInstruction from .delay import Delay from .measure import Measure from .reset import Reset from .tools import pi_check if typing.TYPE_CHECKING: import qiskit # pylint: disable=cyclic-import from qiskit.transpiler.layout import TranspileLayout # pylint: disable=cyclic-import BitLocations = namedtuple("BitLocations", ("index", "registers")) # The following types are not marked private to avoid leaking this "private/public" abstraction out # into the documentation. They are not imported by circuit.__init__, nor are they meant to be. # Arbitrary type variables for marking up generics. S = TypeVar("S") T = TypeVar("T") # Types that can be coerced to a valid Qubit specifier in a circuit. QubitSpecifier = Union[ Qubit, QuantumRegister, int, slice, Sequence[Union[Qubit, int]], ] # Types that can be coerced to a valid Clbit specifier in a circuit. ClbitSpecifier = Union[ Clbit, ClassicalRegister, int, slice, Sequence[Union[Clbit, int]], ] # Generic type which is either :obj:`~Qubit` or :obj:`~Clbit`, used to specify types of functions # which operate on either type of bit, but not both at the same time. BitType = TypeVar("BitType", Qubit, Clbit) # Regex pattern to match valid OpenQASM identifiers VALID_QASM2_IDENTIFIER = re.compile("[a-z][a-zA-Z_0-9]*") QASM2_RESERVED = { "OPENQASM", "qreg", "creg", "include", "gate", "opaque", "U", "CX", "measure", "reset", "if", "barrier", } class QuantumCircuit: """Create a new circuit. A circuit is a list of instructions bound to some registers. Args: regs (list(:class:`~.Register`) or list(``int``) or list(list(:class:`~.Bit`))): The registers to be included in the circuit. * If a list of :class:`~.Register` objects, represents the :class:`.QuantumRegister` and/or :class:`.ClassicalRegister` objects to include in the circuit. For example: * ``QuantumCircuit(QuantumRegister(4))`` * ``QuantumCircuit(QuantumRegister(4), ClassicalRegister(3))`` * ``QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(2, 'qr1'))`` * If a list of ``int``, the amount of qubits and/or classical bits to include in the circuit. It can either be a single int for just the number of quantum bits, or 2 ints for the number of quantum bits and classical bits, respectively. For example: * ``QuantumCircuit(4) # A QuantumCircuit with 4 qubits`` * ``QuantumCircuit(4, 3) # A QuantumCircuit with 4 qubits and 3 classical bits`` * If a list of python lists containing :class:`.Bit` objects, a collection of :class:`.Bit` s to be added to the circuit. name (str): the name of the quantum circuit. If not set, an automatically generated string will be assigned. global_phase (float or ParameterExpression): The global phase of the circuit in radians. metadata (dict): Arbitrary key value metadata to associate with the circuit. This gets stored as free-form data in a dict in the :attr:`~qiskit.circuit.QuantumCircuit.metadata` attribute. It will not be directly used in the circuit. Raises: CircuitError: if the circuit name, if given, is not valid. Examples: Construct a simple Bell state circuit. .. plot:: :include-source: from qiskit import QuantumCircuit qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) qc.draw('mpl') Construct a 5-qubit GHZ circuit. .. code-block:: from qiskit import QuantumCircuit qc = QuantumCircuit(5) qc.h(0) qc.cx(0, range(1, 5)) qc.measure_all() Construct a 4-qubit Bernstein-Vazirani circuit using registers. .. plot:: :include-source: 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') """ instances = 0 prefix = "circuit" # Class variable OPENQASM header header = "OPENQASM 2.0;" extension_lib = 'include "qelib1.inc";' def __init__( self, *regs: Register | int | Sequence[Bit], name: str | None = None, global_phase: ParameterValueType = 0, metadata: dict | None = None, ): if any(not isinstance(reg, (list, QuantumRegister, ClassicalRegister)) for reg in regs): # check if inputs are integers, but also allow e.g. 2.0 try: valid_reg_size = all(reg == int(reg) for reg in regs) except (ValueError, TypeError): valid_reg_size = False if not valid_reg_size: raise CircuitError( "Circuit args must be Registers or integers. (%s '%s' was " "provided)" % ([type(reg).__name__ for reg in regs], regs) ) regs = tuple(int(reg) for reg in regs) # cast to int self._base_name = None if name is None: self._base_name = self.cls_prefix() self._name_update() elif not isinstance(name, str): raise CircuitError( "The circuit name should be a string (or None to auto-generate a name)." ) else: self._base_name = name self.name = name self._increment_instances() # Data contains a list of instructions and their contexts, # in the order they were applied. self._data: list[CircuitInstruction] = [] self._op_start_times = None # A stack to hold the instruction sets that are being built up during for-, if- and # while-block construction. These are stored as a stripped down sequence of instructions, # and sets of qubits and clbits, rather than a full QuantumCircuit instance because the # builder interfaces need to wait until they are completed before they can fill in things # like `break` and `continue`. This is because these instructions need to "operate" on the # full width of bits, but the builder interface won't know what bits are used until the end. self._control_flow_scopes: list[ "qiskit.circuit.controlflow.builder.ControlFlowBuilderBlock" ] = [] self.qregs: list[QuantumRegister] = [] self.cregs: list[ClassicalRegister] = [] self._qubits: list[Qubit] = [] self._clbits: list[Clbit] = [] # Dict mapping Qubit or Clbit instances to tuple comprised of 0) the # corresponding index in circuit.{qubits,clbits} and 1) a list of # Register-int pairs for each Register containing the Bit and its index # within that register. self._qubit_indices: dict[Qubit, BitLocations] = {} self._clbit_indices: dict[Clbit, BitLocations] = {} self._ancillas: list[AncillaQubit] = [] self._calibrations: DefaultDict[str, dict[tuple, Any]] = defaultdict(dict) self.add_register(*regs) # Parameter table tracks instructions with variable parameters. self._parameter_table = ParameterTable() # Cache to avoid re-sorting parameters self._parameters = None self._layout = None self._global_phase: ParameterValueType = 0 self.global_phase = global_phase self.duration = None self.unit = "dt" self.metadata = {} if metadata is None else metadata @staticmethod def from_instructions( instructions: Iterable[ CircuitInstruction | tuple[qiskit.circuit.Instruction] | tuple[qiskit.circuit.Instruction, Iterable[Qubit]] | tuple[qiskit.circuit.Instruction, Iterable[Qubit], Iterable[Clbit]] ], *, qubits: Iterable[Qubit] = (), clbits: Iterable[Clbit] = (), name: str | None = None, global_phase: ParameterValueType = 0, metadata: dict | None = None, ) -> "QuantumCircuit": """Construct a circuit from an iterable of CircuitInstructions. Args: instructions: The instructions to add to the circuit. qubits: Any qubits to add to the circuit. This argument can be used, for example, to enforce a particular ordering of qubits. clbits: Any classical bits to add to the circuit. This argument can be used, for example, to enforce a particular ordering of classical bits. name: The name of the circuit. global_phase: The global phase of the circuit in radians. metadata: Arbitrary key value metadata to associate with the circuit. Returns: The quantum circuit. """ circuit = QuantumCircuit(name=name, global_phase=global_phase, metadata=metadata) added_qubits = set() added_clbits = set() if qubits: qubits = list(qubits) circuit.add_bits(qubits) added_qubits.update(qubits) if clbits: clbits = list(clbits) circuit.add_bits(clbits) added_clbits.update(clbits) for instruction in instructions: if not isinstance(instruction, CircuitInstruction): instruction = CircuitInstruction(*instruction) qubits = [qubit for qubit in instruction.qubits if qubit not in added_qubits] clbits = [clbit for clbit in instruction.clbits if clbit not in added_clbits] circuit.add_bits(qubits) circuit.add_bits(clbits) added_qubits.update(qubits) added_clbits.update(clbits) circuit._append(instruction) return circuit @property def layout(self) -> Optional[TranspileLayout]: r"""Return any associated layout information about the circuit This attribute contains an optional :class:`~.TranspileLayout` object. This is typically set on the output from :func:`~.transpile` or :meth:`.PassManager.run` to retain information about the permutations caused on the input circuit by transpilation. There are two types of permutations caused by the :func:`~.transpile` function, an initial layout which permutes the qubits based on the selected physical qubits on the :class:`~.Target`, and a final layout which is an output permutation caused by :class:`~.SwapGate`\s inserted during routing. """ return self._layout @property def data(self) -> QuantumCircuitData: """Return the circuit data (instructions and context). Returns: QuantumCircuitData: a list-like object containing the :class:`.CircuitInstruction`\\ s for each instruction. """ return QuantumCircuitData(self) @data.setter def data(self, data_input: Iterable): """Sets the circuit data from a list of instructions and context. Args: data_input (Iterable): A sequence of instructions with their execution contexts. The elements must either be instances of :class:`.CircuitInstruction` (preferred), or a 3-tuple of ``(instruction, qargs, cargs)`` (legacy). In the legacy format, ``instruction`` must be an :class:`~.circuit.Instruction`, while ``qargs`` and ``cargs`` must be iterables of :class:`.Qubit` or :class:`.Clbit` specifiers (similar to the allowed forms in calls to :meth:`append`). """ # If data_input is QuantumCircuitData(self), clearing self._data # below will also empty data_input, so make a shallow copy first. data_input = list(data_input) self._data = [] self._parameter_table = ParameterTable() if not data_input: return if isinstance(data_input[0], CircuitInstruction): for instruction in data_input: self.append(instruction) else: for instruction, qargs, cargs in data_input: self.append(instruction, qargs, cargs) @property def op_start_times(self) -> list[int]: """Return a list of operation start times. This attribute is enabled once one of scheduling analysis passes runs on the quantum circuit. Returns: List of integers representing instruction start times. The index corresponds to the index of instruction in :attr:`QuantumCircuit.data`. Raises: AttributeError: When circuit is not scheduled. """ if self._op_start_times is None: raise AttributeError( "This circuit is not scheduled. " "To schedule it run the circuit through one of the transpiler scheduling passes." ) return self._op_start_times @property def calibrations(self) -> dict: """Return calibration dictionary. The custom pulse definition of a given gate is of the form ``{'gate_name': {(qubits, params): schedule}}`` """ return dict(self._calibrations) @calibrations.setter def calibrations(self, calibrations: dict): """Set the circuit calibration data from a dictionary of calibration definition. Args: calibrations (dict): A dictionary of input in the format ``{'gate_name': {(qubits, gate_params): schedule}}`` """ self._calibrations = defaultdict(dict, calibrations) def has_calibration_for(self, instruction: CircuitInstruction | tuple): """Return True if the circuit has a calibration defined for the instruction context. In this case, the operation does not need to be translated to the device basis. """ if isinstance(instruction, CircuitInstruction): operation = instruction.operation qubits = instruction.qubits else: operation, qubits, _ = instruction if not self.calibrations or operation.name not in self.calibrations: return False qubits = tuple(self.qubits.index(qubit) for qubit in qubits) params = [] for p in operation.params: if isinstance(p, ParameterExpression) and not p.parameters: params.append(float(p)) else: params.append(p) params = tuple(params) return (qubits, params) in self.calibrations[operation.name] @property def metadata(self) -> dict: """The user provided metadata associated with the circuit. The metadata for the circuit is a user provided ``dict`` of metadata for the circuit. It will not be used to influence the execution or operation of the circuit, but it is expected to be passed between all transforms of the circuit (ie transpilation) and that providers will associate any circuit metadata with the results it returns from execution of that circuit. """ return self._metadata @metadata.setter def metadata(self, metadata: dict | None): """Update the circuit metadata""" if metadata is None: metadata = {} warnings.warn( "Setting metadata to None was deprecated in Terra 0.24.0 and this ability will be " "removed in a future release. Instead, set metadata to an empty dictionary.", DeprecationWarning, stacklevel=2, ) elif not isinstance(metadata, dict): raise TypeError("Only a dictionary is accepted for circuit metadata") self._metadata = metadata def __str__(self) -> str: return str(self.draw(output="text")) def __eq__(self, other) -> bool: if not isinstance(other, QuantumCircuit): return False # TODO: remove the DAG from this function from qiskit.converters import circuit_to_dag return circuit_to_dag(self, copy_operations=False) == circuit_to_dag( other, copy_operations=False ) @classmethod def _increment_instances(cls): cls.instances += 1 @classmethod def cls_instances(cls) -> int: """Return the current number of instances of this class, useful for auto naming.""" return cls.instances @classmethod def cls_prefix(cls) -> str: """Return the prefix to use for auto naming.""" return cls.prefix def _name_update(self) -> None: """update name of instance using instance number""" if not is_main_process(): pid_name = f"-{mp.current_process().pid}" else: pid_name = "" self.name = f"{self._base_name}-{self.cls_instances()}{pid_name}" def has_register(self, register: Register) -> bool: """ Test if this circuit has the register r. Args: register (Register): a quantum or classical register. Returns: bool: True if the register is contained in this circuit. """ has_reg = False if isinstance(register, QuantumRegister) and register in self.qregs: has_reg = True elif isinstance(register, ClassicalRegister) and register in self.cregs: has_reg = True return has_reg def reverse_ops(self) -> "QuantumCircuit": """Reverse the circuit by reversing the order of instructions. This is done by recursively reversing all instructions. It does not invert (adjoint) any gate. Returns: QuantumCircuit: the reversed circuit. Examples: input: .. parsed-literal:: ┌───┐ q_0: ┤ H ├─────■────── └───┘┌────┴─────┐ q_1: ─────┤ RX(1.57) ├ └──────────┘ output: .. parsed-literal:: ┌───┐ q_0: ─────■──────┤ H ├ ┌────┴─────┐└───┘ q_1: ┤ RX(1.57) ├───── └──────────┘ """ reverse_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + "_reverse" ) for instruction in reversed(self.data): reverse_circ._append(instruction.replace(operation=instruction.operation.reverse_ops())) reverse_circ.duration = self.duration reverse_circ.unit = self.unit return reverse_circ def reverse_bits(self) -> "QuantumCircuit": """Return a circuit with the opposite order of wires. The circuit is "vertically" flipped. If a circuit is defined over multiple registers, the resulting circuit will have the same registers but with their order flipped. This method is useful for converting a circuit written in little-endian convention to the big-endian equivalent, and vice versa. Returns: QuantumCircuit: the circuit with reversed bit order. Examples: input: .. parsed-literal:: ┌───┐ a_0: ┤ H ├──■───────────────── └───┘┌─┴─┐ a_1: ─────┤ X ├──■──────────── └───┘┌─┴─┐ a_2: ──────────┤ X ├──■─────── └───┘┌─┴─┐ b_0: ───────────────┤ X ├──■── └───┘┌─┴─┐ b_1: ────────────────────┤ X ├ └───┘ output: .. parsed-literal:: ┌───┐ b_0: ────────────────────┤ X ├ ┌───┐└─┬─┘ b_1: ───────────────┤ X ├──■── ┌───┐└─┬─┘ a_0: ──────────┤ X ├──■─────── ┌───┐└─┬─┘ a_1: ─────┤ X ├──■──────────── ┌───┐└─┬─┘ a_2: ┤ H ├──■───────────────── └───┘ """ circ = QuantumCircuit( list(reversed(self.qubits)), list(reversed(self.clbits)), name=self.name, global_phase=self.global_phase, ) new_qubit_map = circ.qubits[::-1] new_clbit_map = circ.clbits[::-1] for reg in reversed(self.qregs): bits = [new_qubit_map[self.find_bit(qubit).index] for qubit in reversed(reg)] circ.add_register(QuantumRegister(bits=bits, name=reg.name)) for reg in reversed(self.cregs): bits = [new_clbit_map[self.find_bit(clbit).index] for clbit in reversed(reg)] circ.add_register(ClassicalRegister(bits=bits, name=reg.name)) for instruction in self.data: qubits = [new_qubit_map[self.find_bit(qubit).index] for qubit in instruction.qubits] clbits = [new_clbit_map[self.find_bit(clbit).index] for clbit in instruction.clbits] circ._append(instruction.replace(qubits=qubits, clbits=clbits)) return circ def inverse(self) -> "QuantumCircuit": """Invert (take adjoint of) this circuit. This is done by recursively inverting all gates. Returns: QuantumCircuit: the inverted circuit Raises: CircuitError: if the circuit cannot be inverted. Examples: input: .. parsed-literal:: ┌───┐ q_0: ┤ H ├─────■────── └───┘┌────┴─────┐ q_1: ─────┤ RX(1.57) ├ └──────────┘ output: .. parsed-literal:: ┌───┐ q_0: ──────■──────┤ H ├ ┌─────┴─────┐└───┘ q_1: ┤ RX(-1.57) ├───── └───────────┘ """ inverse_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + "_dg", global_phase=-self.global_phase, ) for instruction in reversed(self._data): inverse_circ._append(instruction.replace(operation=instruction.operation.inverse())) return inverse_circ def repeat(self, reps: int) -> "QuantumCircuit": """Repeat this circuit ``reps`` times. Args: reps (int): How often this circuit should be repeated. Returns: QuantumCircuit: A circuit containing ``reps`` repetitions of this circuit. """ repeated_circ = QuantumCircuit( self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + f"**{reps}" ) # benefit of appending instructions: decomposing shows the subparts, i.e. the power # is actually `reps` times this circuit, and it is currently much faster than `compose`. if reps > 0: try: # try to append as gate if possible to not disallow to_gate inst: Instruction = self.to_gate() except QiskitError: inst = self.to_instruction() for _ in range(reps): repeated_circ._append(inst, self.qubits, self.clbits) return repeated_circ def power(self, power: float, matrix_power: bool = False) -> "QuantumCircuit": """Raise this circuit to the power of ``power``. If ``power`` is a positive integer and ``matrix_power`` is ``False``, this implementation defaults to calling ``repeat``. Otherwise, if the circuit is unitary, the matrix is computed to calculate the matrix power. Args: power (float): The power to raise this circuit to. matrix_power (bool): If True, the circuit is converted to a matrix and then the matrix power is computed. If False, and ``power`` is a positive integer, the implementation defaults to ``repeat``. Raises: CircuitError: If the circuit needs to be converted to a gate but it is not unitary. Returns: QuantumCircuit: A circuit implementing this circuit raised to the power of ``power``. """ if power >= 0 and isinstance(power, (int, np.integer)) and not matrix_power: return self.repeat(power) # attempt conversion to gate if self.num_parameters > 0: raise CircuitError( "Cannot raise a parameterized circuit to a non-positive power " "or matrix-power, please bind the free parameters: " "{}".format(self.parameters) ) try: gate = self.to_gate() except QiskitError as ex: raise CircuitError( "The circuit contains non-unitary operations and cannot be " "controlled. Note that no qiskit.circuit.Instruction objects may " "be in the circuit for this operation." ) from ex power_circuit = QuantumCircuit(self.qubits, self.clbits, *self.qregs, *self.cregs) power_circuit.append(gate.power(power), list(range(gate.num_qubits))) return power_circuit def control( self, num_ctrl_qubits: int = 1, label: str | None = None, ctrl_state: str | int | None = None, ) -> "QuantumCircuit": """Control this circuit on ``num_ctrl_qubits`` qubits. Args: num_ctrl_qubits (int): The number of control qubits. label (str): An optional label to give the controlled operation for visualization. ctrl_state (str or int): The control state in decimal or as a bitstring (e.g. '111'). If None, use ``2**num_ctrl_qubits - 1``. Returns: QuantumCircuit: The controlled version of this circuit. Raises: CircuitError: If the circuit contains a non-unitary operation and cannot be controlled. """ try: gate = self.to_gate() except QiskitError as ex: raise CircuitError( "The circuit contains non-unitary operations and cannot be " "controlled. Note that no qiskit.circuit.Instruction objects may " "be in the circuit for this operation." ) from ex controlled_gate = gate.control(num_ctrl_qubits, label, ctrl_state) control_qreg = QuantumRegister(num_ctrl_qubits) controlled_circ = QuantumCircuit( control_qreg, self.qubits, *self.qregs, name=f"c_{self.name}" ) controlled_circ.append(controlled_gate, controlled_circ.qubits) return controlled_circ def compose( self, other: Union["QuantumCircuit", Instruction], qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, clbits: ClbitSpecifier | Sequence[ClbitSpecifier] | None = None, front: bool = False, inplace: bool = False, wrap: bool = False, ) -> Optional["QuantumCircuit"]: """Compose circuit with ``other`` circuit or instruction, optionally permuting wires. ``other`` can be narrower or of equal width to ``self``. Args: other (qiskit.circuit.Instruction or QuantumCircuit): (sub)circuit or instruction to compose onto self. If not a :obj:`.QuantumCircuit`, this can be anything that :obj:`.append` will accept. qubits (list[Qubit|int]): qubits of self to compose onto. clbits (list[Clbit|int]): clbits of self to compose onto. front (bool): If True, front composition will be performed. This is not possible within control-flow builder context managers. inplace (bool): If True, modify the object. Otherwise return composed circuit. wrap (bool): If True, wraps the other circuit into a gate (or instruction, depending on whether it contains only unitary instructions) before composing it onto self. Returns: QuantumCircuit: the composed circuit (returns None if inplace==True). Raises: CircuitError: if no correct wire mapping can be made between the two circuits, such as if ``other`` is wider than ``self``. CircuitError: if trying to emit a new circuit while ``self`` has a partially built control-flow context active, such as the context-manager forms of :meth:`if_test`, :meth:`for_loop` and :meth:`while_loop`. CircuitError: if trying to compose to the front of a circuit when a control-flow builder block is active; there is no clear meaning to this action. Examples: .. code-block:: python >>> lhs.compose(rhs, qubits=[3, 2], inplace=True) .. parsed-literal:: ┌───┐ ┌─────┐ ┌───┐ lqr_1_0: ───┤ H ├─── rqr_0: ──■──┤ Tdg ├ lqr_1_0: ───┤ H ├─────────────── ├───┤ ┌─┴─┐└─────┘ ├───┤ lqr_1_1: ───┤ X ├─── rqr_1: ┤ X ├─────── lqr_1_1: ───┤ X ├─────────────── ┌──┴───┴──┐ └───┘ ┌──┴───┴──┐┌───┐ lqr_1_2: ┤ U1(0.1) ├ + = lqr_1_2: ┤ U1(0.1) ├┤ X ├─────── └─────────┘ └─────────┘└─┬─┘┌─────┐ lqr_2_0: ─────■───── lqr_2_0: ─────■───────■──┤ Tdg ├ ┌─┴─┐ ┌─┴─┐ └─────┘ lqr_2_1: ───┤ X ├─── lqr_2_1: ───┤ X ├─────────────── └───┘ └───┘ lcr_0: 0 ═══════════ lcr_0: 0 ═══════════════════════ lcr_1: 0 ═══════════ lcr_1: 0 ═══════════════════════ """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.switch_case import SwitchCaseOp if inplace and front and self._control_flow_scopes: # If we're composing onto ourselves while in a stateful control-flow builder context, # there's no clear meaning to composition to the "front" of the circuit. raise CircuitError( "Cannot compose to the front of a circuit while a control-flow context is active." ) if not inplace and self._control_flow_scopes: # If we're inside a stateful control-flow builder scope, even if we successfully cloned # the partial builder scope (not simple), the scope wouldn't be controlled by an active # `with` statement, so the output circuit would be permanently broken. raise CircuitError( "Cannot emit a new composed circuit while a control-flow context is active." ) dest = self if inplace else self.copy() # As a special case, allow composing some clbits onto no clbits - normally the destination # has to be strictly larger. This allows composing final measurements onto unitary circuits. if isinstance(other, QuantumCircuit): if not self.clbits and other.clbits: dest.add_bits(other.clbits) for reg in other.cregs: dest.add_register(reg) if wrap and isinstance(other, QuantumCircuit): other = ( other.to_gate() if all(isinstance(ins.operation, Gate) for ins in other.data) else other.to_instruction() ) if not isinstance(other, QuantumCircuit): if qubits is None: qubits = self.qubits[: other.num_qubits] if clbits is None: clbits = self.clbits[: other.num_clbits] if front: # Need to keep a reference to the data for use after we've emptied it. old_data = list(dest.data) dest.clear() dest.append(other, qubits, clbits) for instruction in old_data: dest._append(instruction) else: dest.append(other, qargs=qubits, cargs=clbits) if inplace: return None return dest if other.num_qubits > dest.num_qubits or other.num_clbits > dest.num_clbits: raise CircuitError( "Trying to compose with another QuantumCircuit which has more 'in' edges." ) # number of qubits and clbits must match number in circuit or None edge_map: dict[Qubit | Clbit, Qubit | Clbit] = {} if qubits is None: edge_map.update(zip(other.qubits, dest.qubits)) else: mapped_qubits = dest.qbit_argument_conversion(qubits) if len(mapped_qubits) != len(other.qubits): raise CircuitError( f"Number of items in qubits parameter ({len(mapped_qubits)}) does not" f" match number of qubits in the circuit ({len(other.qubits)})." ) edge_map.update(zip(other.qubits, mapped_qubits)) if clbits is None: edge_map.update(zip(other.clbits, dest.clbits)) else: mapped_clbits = dest.cbit_argument_conversion(clbits) if len(mapped_clbits) != len(other.clbits): raise CircuitError( f"Number of items in clbits parameter ({len(mapped_clbits)}) does not" f" match number of clbits in the circuit ({len(other.clbits)})." ) edge_map.update(zip(other.clbits, dest.cbit_argument_conversion(clbits))) variable_mapper = _classical_resource_map.VariableMapper( dest.cregs, edge_map, dest.add_register ) mapped_instrs: list[CircuitInstruction] = [] for instr in other.data: n_qargs: list[Qubit] = [edge_map[qarg] for qarg in instr.qubits] n_cargs: list[Clbit] = [edge_map[carg] for carg in instr.clbits] n_op = instr.operation.copy() if (condition := getattr(n_op, "condition", None)) is not None: n_op.condition = variable_mapper.map_condition(condition) if isinstance(n_op, SwitchCaseOp): n_op.target = variable_mapper.map_target(n_op.target) mapped_instrs.append(CircuitInstruction(n_op, n_qargs, n_cargs)) if front: # adjust new instrs before original ones and update all parameters mapped_instrs += dest.data dest.clear() append = dest._control_flow_scopes[-1].append if dest._control_flow_scopes else dest._append for instr in mapped_instrs: append(instr) for gate, cals in other.calibrations.items(): dest._calibrations[gate].update(cals) dest.global_phase += other.global_phase if inplace: return None return dest def tensor(self, other: "QuantumCircuit", inplace: bool = False) -> Optional["QuantumCircuit"]: """Tensor ``self`` with ``other``. Remember that in the little-endian convention the leftmost operation will be at the bottom of the circuit. See also `the docs <qiskit.org/documentation/tutorials/circuits/3_summary_of_quantum_operations.html>`__ for more information. .. parsed-literal:: ┌────────┐ ┌─────┐ ┌─────┐ q_0: ┤ bottom ├ ⊗ q_0: ┤ top ├ = q_0: ─┤ top ├── └────────┘ └─────┘ ┌┴─────┴─┐ q_1: ┤ bottom ├ └────────┘ Args: other (QuantumCircuit): The other circuit to tensor this circuit with. inplace (bool): If True, modify the object. Otherwise return composed circuit. Examples: .. plot:: :include-source: from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl') Returns: QuantumCircuit: The tensored circuit (returns None if inplace==True). """ num_qubits = self.num_qubits + other.num_qubits num_clbits = self.num_clbits + other.num_clbits # If a user defined both circuits with via register sizes and not with named registers # (e.g. QuantumCircuit(2, 2)) then we have a naming collision, as the registers are by # default called "q" resp. "c". To still allow tensoring we define new registers of the # correct sizes. if ( len(self.qregs) == len(other.qregs) == 1 and self.qregs[0].name == other.qregs[0].name == "q" ): # check if classical registers are in the circuit if num_clbits > 0: dest = QuantumCircuit(num_qubits, num_clbits) else: dest = QuantumCircuit(num_qubits) # handle case if ``measure_all`` was called on both circuits, in which case the # registers are both named "meas" elif ( len(self.cregs) == len(other.cregs) == 1 and self.cregs[0].name == other.cregs[0].name == "meas" ): cr = ClassicalRegister(self.num_clbits + other.num_clbits, "meas") dest = QuantumCircuit(*other.qregs, *self.qregs, cr) # Now we don't have to handle any more cases arising from special implicit naming else: dest = QuantumCircuit( other.qubits, self.qubits, other.clbits, self.clbits, *other.qregs, *self.qregs, *other.cregs, *self.cregs, ) # compose self onto the output, and then other dest.compose(other, range(other.num_qubits), range(other.num_clbits), inplace=True) dest.compose( self, range(other.num_qubits, num_qubits), range(other.num_clbits, num_clbits), inplace=True, ) # Replace information from tensored circuit into self when inplace = True if inplace: self.__dict__.update(dest.__dict__) return None return dest @property def qubits(self) -> list[Qubit]: """ Returns a list of quantum bits in the order that the registers were added. """ return self._qubits @property def clbits(self) -> list[Clbit]: """ Returns a list of classical bits in the order that the registers were added. """ return self._clbits @property def ancillas(self) -> list[AncillaQubit]: """ Returns a list of ancilla bits in the order that the registers were added. """ return self._ancillas def __and__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Overload & to implement self.compose.""" return self.compose(rhs) def __iand__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Overload &= to implement self.compose in place.""" self.compose(rhs, inplace=True) return self def __xor__(self, top: "QuantumCircuit") -> "QuantumCircuit": """Overload ^ to implement self.tensor.""" return self.tensor(top) def __ixor__(self, top: "QuantumCircuit") -> "QuantumCircuit": """Overload ^= to implement self.tensor in place.""" self.tensor(top, inplace=True) return self def __len__(self) -> int: """Return number of operations in circuit.""" return len(self._data) @typing.overload def __getitem__(self, item: int) -> CircuitInstruction: ... @typing.overload def __getitem__(self, item: slice) -> list[CircuitInstruction]: ... def __getitem__(self, item): """Return indexed operation.""" return self._data[item] @staticmethod def cast(value: S, type_: Callable[..., T]) -> Union[S, T]: """Best effort to cast value to type. Otherwise, returns the value.""" try: return type_(value) except (ValueError, TypeError): return value def qbit_argument_conversion(self, qubit_representation: QubitSpecifier) -> list[Qubit]: """ Converts several qubit representations (such as indexes, range, etc.) into a list of qubits. Args: qubit_representation (Object): representation to expand Returns: List(Qubit): the resolved instances of the qubits. """ return _bit_argument_conversion( qubit_representation, self.qubits, self._qubit_indices, Qubit ) def cbit_argument_conversion(self, clbit_representation: ClbitSpecifier) -> list[Clbit]: """ Converts several classical bit representations (such as indexes, range, etc.) into a list of classical bits. Args: clbit_representation (Object): representation to expand Returns: List(tuple): Where each tuple is a classical bit. """ return _bit_argument_conversion( clbit_representation, self.clbits, self._clbit_indices, Clbit ) def _resolve_classical_resource(self, specifier): """Resolve a single classical resource specifier into a concrete resource, raising an error if the specifier is invalid. This is slightly different to :meth:`.cbit_argument_conversion`, because it should not unwrap :obj:`.ClassicalRegister` instances into lists, and in general it should not allow iterables or broadcasting. It is expected to be used as a callback for things like :meth:`.InstructionSet.c_if` to check the validity of their arguments. Args: specifier (Union[Clbit, ClassicalRegister, int]): a specifier of a classical resource present in this circuit. An ``int`` will be resolved into a :obj:`.Clbit` using the same conventions as measurement operations on this circuit use. Returns: Union[Clbit, ClassicalRegister]: the resolved resource. Raises: CircuitError: if the resource is not present in this circuit, or if the integer index passed is out-of-bounds. """ if isinstance(specifier, Clbit): if specifier not in self._clbit_indices: raise CircuitError(f"Clbit {specifier} is not present in this circuit.") return specifier if isinstance(specifier, ClassicalRegister): # This is linear complexity for something that should be constant, but QuantumCircuit # does not currently keep a hashmap of registers, and requires non-trivial changes to # how it exposes its registers publically before such a map can be safely stored so it # doesn't miss updates. (Jake, 2021-11-10). if specifier not in self.cregs: raise CircuitError(f"Register {specifier} is not present in this circuit.") return specifier if isinstance(specifier, int): try: return self._clbits[specifier] except IndexError: raise CircuitError(f"Classical bit index {specifier} is out-of-range.") from None raise CircuitError(f"Unknown classical resource specifier: '{specifier}'.") def _validate_expr(self, node: expr.Expr) -> expr.Expr: for var in expr.iter_vars(node): if isinstance(var.var, Clbit): if var.var not in self._clbit_indices: raise CircuitError(f"Clbit {var.var} is not present in this circuit.") elif isinstance(var.var, ClassicalRegister): if var.var not in self.cregs: raise CircuitError(f"Register {var.var} is not present in this circuit.") return node def append( self, instruction: Operation | CircuitInstruction, qargs: Sequence[QubitSpecifier] | None = None, cargs: Sequence[ClbitSpecifier] | None = None, ) -> InstructionSet: """Append one or more instructions to the end of the circuit, modifying the circuit in place. The ``qargs`` and ``cargs`` will be expanded and broadcast according to the rules of the given :class:`~.circuit.Instruction`, and any non-:class:`.Bit` specifiers (such as integer indices) will be resolved into the relevant instances. If a :class:`.CircuitInstruction` is given, it will be unwrapped, verified in the context of this circuit, and a new object will be appended to the circuit. In this case, you may not pass ``qargs`` or ``cargs`` separately. Args: instruction: :class:`~.circuit.Instruction` instance to append, or a :class:`.CircuitInstruction` with all its context. qargs: specifiers of the :class:`.Qubit`\\ s to attach instruction to. cargs: specifiers of the :class:`.Clbit`\\ s to attach instruction to. Returns: qiskit.circuit.InstructionSet: a handle to the :class:`.CircuitInstruction`\\ s that were actually added to the circuit. Raises: CircuitError: if the operation passed is not an instance of :class:`~.circuit.Instruction` . """ if isinstance(instruction, CircuitInstruction): operation = instruction.operation qargs = instruction.qubits cargs = instruction.clbits else: operation = instruction # Convert input to instruction if not isinstance(operation, Operation): if hasattr(operation, "to_instruction"): operation = operation.to_instruction() if not isinstance(operation, Operation): raise CircuitError("operation.to_instruction() is not an Operation.") else: if issubclass(operation, Operation): raise CircuitError( "Object is a subclass of Operation, please add () to " "pass an instance of this object." ) raise CircuitError( "Object to append must be an Operation or have a to_instruction() method." ) # Make copy of parameterized gate instances if hasattr(operation, "params"): is_parameter = any(isinstance(param, Parameter) for param in operation.params) if is_parameter: operation = copy.deepcopy(operation) expanded_qargs = [self.qbit_argument_conversion(qarg) for qarg in qargs or []] expanded_cargs = [self.cbit_argument_conversion(carg) for carg in cargs or []] if self._control_flow_scopes: appender = self._control_flow_scopes[-1].append requester = self._control_flow_scopes[-1].request_classical_resource else: appender = self._append requester = self._resolve_classical_resource instructions = InstructionSet(resource_requester=requester) if isinstance(operation, Instruction): for qarg, carg in operation.broadcast_arguments(expanded_qargs, expanded_cargs): self._check_dups(qarg) instruction = CircuitInstruction(operation, qarg, carg) appender(instruction) instructions.add(instruction) else: # For Operations that are non-Instructions, we use the Instruction's default method for qarg, carg in Instruction.broadcast_arguments( operation, expanded_qargs, expanded_cargs ): self._check_dups(qarg) instruction = CircuitInstruction(operation, qarg, carg) appender(instruction) instructions.add(instruction) return instructions # Preferred new style. @typing.overload def _append( self, instruction: CircuitInstruction, _qargs: None = None, _cargs: None = None ) -> CircuitInstruction: ... # To-be-deprecated old style. @typing.overload def _append( self, operation: Operation, qargs: Sequence[Qubit], cargs: Sequence[Clbit], ) -> Operation: ... def _append( self, instruction: CircuitInstruction | Instruction, qargs: Sequence[Qubit] | None = None, cargs: Sequence[Clbit] | None = None, ): """Append an instruction to the end of the circuit, modifying the circuit in place. .. warning:: This is an internal fast-path function, and it is the responsibility of the caller to ensure that all the arguments are valid; there is no error checking here. In particular, all the qubits and clbits must already exist in the circuit and there can be no duplicates in the list. .. note:: This function may be used by callers other than :obj:`.QuantumCircuit` when the caller is sure that all error-checking, broadcasting and scoping has already been performed, and the only reference to the circuit the instructions are being appended to is within that same function. In particular, it is not safe to call :meth:`QuantumCircuit._append` on a circuit that is received by a function argument. This is because :meth:`.QuantumCircuit._append` will not recognise the scoping constructs of the control-flow builder interface. Args: instruction: Operation instance to append qargs: Qubits to attach the instruction to. cargs: Clbits to attach the instruction to. Returns: Operation: a handle to the instruction that was just added :meta public: """ old_style = not isinstance(instruction, CircuitInstruction) if old_style: instruction = CircuitInstruction(instruction, qargs, cargs) self._data.append(instruction) if isinstance(instruction.operation, Instruction): self._update_parameter_table(instruction) # mark as normal circuit if a new instruction is added self.duration = None self.unit = "dt" return instruction.operation if old_style else instruction def _update_parameter_table(self, instruction: CircuitInstruction): for param_index, param in enumerate(instruction.operation.params): if isinstance(param, (ParameterExpression, QuantumCircuit)): # Scoped constructs like the control-flow ops use QuantumCircuit as a parameter. atomic_parameters = set(param.parameters) else: atomic_parameters = set() for parameter in atomic_parameters: if parameter in self._parameter_table: self._parameter_table[parameter].add((instruction.operation, param_index)) else: if parameter.name in self._parameter_table.get_names(): raise CircuitError(f"Name conflict on adding parameter: {parameter.name}") self._parameter_table[parameter] = ParameterReferences( ((instruction.operation, param_index),) ) # clear cache if new parameter is added self._parameters = None def add_register(self, *regs: Register | int | Sequence[Bit]) -> None: """Add registers.""" if not regs: return if any(isinstance(reg, int) for reg in regs): # QuantumCircuit defined without registers if len(regs) == 1 and isinstance(regs[0], int): # QuantumCircuit with anonymous quantum wires e.g. QuantumCircuit(2) if regs[0] == 0: regs = () else: regs = (QuantumRegister(regs[0], "q"),) elif len(regs) == 2 and all(isinstance(reg, int) for reg in regs): # QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3) if regs[0] == 0: qregs: tuple[QuantumRegister, ...] = () else: qregs = (QuantumRegister(regs[0], "q"),) if regs[1] == 0: cregs: tuple[ClassicalRegister, ...] = () else: cregs = (ClassicalRegister(regs[1], "c"),) regs = qregs + cregs else: raise CircuitError( "QuantumCircuit parameters can be Registers or Integers." " If Integers, up to 2 arguments. QuantumCircuit was called" " with %s." % (regs,) ) for register in regs: if isinstance(register, Register) and any( register.name == reg.name for reg in self.qregs + self.cregs ): raise CircuitError('register name "%s" already exists' % register.name) if isinstance(register, AncillaRegister): for bit in register: if bit not in self._qubit_indices: self._ancillas.append(bit) if isinstance(register, QuantumRegister): self.qregs.append(register) for idx, bit in enumerate(register): if bit in self._qubit_indices: self._qubit_indices[bit].registers.append((register, idx)) else: self._qubits.append(bit) self._qubit_indices[bit] = BitLocations( len(self._qubits) - 1, [(register, idx)] ) elif isinstance(register, ClassicalRegister): self.cregs.append(register) for idx, bit in enumerate(register): if bit in self._clbit_indices: self._clbit_indices[bit].registers.append((register, idx)) else: self._clbits.append(bit) self._clbit_indices[bit] = BitLocations( len(self._clbits) - 1, [(register, idx)] ) elif isinstance(register, list): self.add_bits(register) else: raise CircuitError("expected a register") def add_bits(self, bits: Iterable[Bit]) -> None: """Add Bits to the circuit.""" duplicate_bits = set(self._qubit_indices).union(self._clbit_indices).intersection(bits) if duplicate_bits: raise CircuitError(f"Attempted to add bits found already in circuit: {duplicate_bits}") for bit in bits: if isinstance(bit, AncillaQubit): self._ancillas.append(bit) if isinstance(bit, Qubit): self._qubits.append(bit) self._qubit_indices[bit] = BitLocations(len(self._qubits) - 1, []) elif isinstance(bit, Clbit): self._clbits.append(bit) self._clbit_indices[bit] = BitLocations(len(self._clbits) - 1, []) else: raise CircuitError( "Expected an instance of Qubit, Clbit, or " "AncillaQubit, but was passed {}".format(bit) ) def find_bit(self, bit: Bit) -> BitLocations: """Find locations in the circuit which can be used to reference a given :obj:`~Bit`. Args: bit (Bit): The bit to locate. Returns: namedtuple(int, List[Tuple(Register, int)]): A 2-tuple. The first element (``index``) contains the index at which the ``Bit`` can be found (in either :obj:`~QuantumCircuit.qubits`, :obj:`~QuantumCircuit.clbits`, depending on its type). The second element (``registers``) is a list of ``(register, index)`` pairs with an entry for each :obj:`~Register` in the circuit which contains the :obj:`~Bit` (and the index in the :obj:`~Register` at which it can be found). Notes: The circuit index of an :obj:`~AncillaQubit` will be its index in :obj:`~QuantumCircuit.qubits`, not :obj:`~QuantumCircuit.ancillas`. Raises: CircuitError: If the supplied :obj:`~Bit` was of an unknown type. CircuitError: If the supplied :obj:`~Bit` could not be found on the circuit. """ try: if isinstance(bit, Qubit): return self._qubit_indices[bit] elif isinstance(bit, Clbit): return self._clbit_indices[bit] else: raise CircuitError(f"Could not locate bit of unknown type: {type(bit)}") except KeyError as err: raise CircuitError( f"Could not locate provided bit: {bit}. Has it been added to the QuantumCircuit?" ) from err def _check_dups(self, qubits: Sequence[Qubit]) -> None: """Raise exception if list of qubits contains duplicates.""" squbits = set(qubits) if len(squbits) != len(qubits): raise CircuitError("duplicate qubit arguments") def to_instruction( self, parameter_map: dict[Parameter, ParameterValueType] | None = None, label: str | None = None, ) -> Instruction: """Create an Instruction out of this circuit. Args: parameter_map(dict): For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the instruction. If None, existing circuit parameters will also parameterize the instruction. label (str): Optional gate label. Returns: qiskit.circuit.Instruction: a composite instruction encapsulating this circuit (can be decomposed back) """ from qiskit.converters.circuit_to_instruction import circuit_to_instruction return circuit_to_instruction(self, parameter_map, label=label) def to_gate( self, parameter_map: dict[Parameter, ParameterValueType] | None = None, label: str | None = None, ) -> Gate: """Create a Gate out of this circuit. Args: parameter_map(dict): For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the gate. If None, existing circuit parameters will also parameterize the gate. label (str): Optional gate label. Returns: Gate: a composite gate encapsulating this circuit (can be decomposed back) """ from qiskit.converters.circuit_to_gate import circuit_to_gate return circuit_to_gate(self, parameter_map, label=label) def decompose( self, gates_to_decompose: Type[Gate] | Sequence[Type[Gate]] | Sequence[str] | str | None = None, reps: int = 1, ) -> "QuantumCircuit": """Call a decomposition pass on this circuit, to decompose one level (shallow decompose). Args: gates_to_decompose (type or str or list(type, str)): Optional subset of gates to decompose. Can be a gate type, such as ``HGate``, or a gate name, such as 'h', or a gate label, such as 'My H Gate', or a list of any combination of these. If a gate name is entered, it will decompose all gates with that name, whether the gates have labels or not. Defaults to all gates in circuit. reps (int): Optional number of times the circuit should be decomposed. For instance, ``reps=2`` equals calling ``circuit.decompose().decompose()``. can decompose specific gates specific time Returns: QuantumCircuit: a circuit one level decomposed """ # pylint: disable=cyclic-import from qiskit.transpiler.passes.basis.decompose import Decompose from qiskit.transpiler.passes.synthesis import HighLevelSynthesis from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_circuit import dag_to_circuit dag = circuit_to_dag(self) dag = HighLevelSynthesis().run(dag) pass_ = Decompose(gates_to_decompose) for _ in range(reps): dag = pass_.run(dag) return dag_to_circuit(dag) def qasm( self, formatted: bool = False, filename: str | None = None, encoding: str | None = None, ) -> str | None: """Return OpenQASM string. Args: formatted (bool): Return formatted Qasm string. filename (str): Save Qasm to file with name 'filename'. encoding (str): Optionally specify the encoding to use for the output file if ``filename`` is specified. By default this is set to the system's default encoding (ie whatever ``locale.getpreferredencoding()`` returns) and can be set to any valid codec or alias from stdlib's `codec module <https://docs.python.org/3/library/codecs.html#standard-encodings>`__ Returns: str: If formatted=False. Raises: MissingOptionalLibraryError: If pygments is not installed and ``formatted`` is ``True``. QASM2ExportError: If circuit has free parameters. QASM2ExportError: If an operation that has no OpenQASM 2 representation is encountered. """ from qiskit.qasm2 import QASM2ExportError # pylint: disable=cyclic-import if self.num_parameters > 0: raise QASM2ExportError( "Cannot represent circuits with unbound parameters in OpenQASM 2." ) existing_gate_names = { "barrier", "measure", "reset", "u3", "u2", "u1", "cx", "id", "u0", "u", "p", "x", "y", "z", "h", "s", "sdg", "t", "tdg", "rx", "ry", "rz", "sx", "sxdg", "cz", "cy", "swap", "ch", "ccx", "cswap", "crx", "cry", "crz", "cu1", "cp", "cu3", "csx", "cu", "rxx", "rzz", "rccx", "rc3x", "c3x", "c3sx", # This is the Qiskit gate name, but the qelib1.inc name is 'c3sqrtx'. "c4x", } # Mapping of instruction name to a pair of the source for a definition, and an OQ2 string # that includes the `gate` or `opaque` statement that defines the gate. gates_to_define: OrderedDict[str, tuple[Instruction, str]] = OrderedDict() regless_qubits = [bit for bit in self.qubits if not self.find_bit(bit).registers] regless_clbits = [bit for bit in self.clbits if not self.find_bit(bit).registers] dummy_registers: list[QuantumRegister | ClassicalRegister] = [] if regless_qubits: dummy_registers.append(QuantumRegister(name="qregless", bits=regless_qubits)) if regless_clbits: dummy_registers.append(ClassicalRegister(name="cregless", bits=regless_clbits)) register_escaped_names: dict[str, QuantumRegister | ClassicalRegister] = {} for regs in (self.qregs, self.cregs, dummy_registers): for reg in regs: register_escaped_names[ _make_unique(_qasm_escape_name(reg.name, "reg_"), register_escaped_names) ] = reg bit_labels: dict[Qubit | Clbit, str] = { bit: "%s[%d]" % (name, idx) for name, register in register_escaped_names.items() for (idx, bit) in enumerate(register) } register_definitions_qasm = "".join( f"{'qreg' if isinstance(reg, QuantumRegister) else 'creg'} {name}[{reg.size}];\n" for name, reg in register_escaped_names.items() ) instruction_calls = [] for instruction in self._data: operation = instruction.operation if operation.name == "measure": qubit = instruction.qubits[0] clbit = instruction.clbits[0] instruction_qasm = f"measure {bit_labels[qubit]} -> {bit_labels[clbit]};" elif operation.name == "reset": instruction_qasm = f"reset {bit_labels[instruction.qubits[0]]};" elif operation.name == "barrier": if not instruction.qubits: # Barriers with no operands are invalid in (strict) OQ2, and the statement # would have no meaning anyway. continue qargs = ",".join(bit_labels[q] for q in instruction.qubits) instruction_qasm = "barrier;" if not qargs else f"barrier {qargs};" else: instruction_qasm = _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, bit_labels ) instruction_calls.append(instruction_qasm) instructions_qasm = "".join(f"{call}\n" for call in instruction_calls) gate_definitions_qasm = "".join(f"{qasm}\n" for _, qasm in gates_to_define.values()) out = "".join( ( self.header, "\n", self.extension_lib, "\n", gate_definitions_qasm, register_definitions_qasm, instructions_qasm, ) ) if filename: with open(filename, "w+", encoding=encoding) as file: file.write(out) if formatted: _optionals.HAS_PYGMENTS.require_now("formatted OpenQASM 2 output") import pygments from pygments.formatters import ( # pylint: disable=no-name-in-module Terminal256Formatter, ) from qiskit.qasm.pygments import OpenQASMLexer from qiskit.qasm.pygments import QasmTerminalStyle code = pygments.highlight( out, OpenQASMLexer(), Terminal256Formatter(style=QasmTerminalStyle) ) print(code) return None return out def draw( self, output: str | None = None, scale: float | None = None, filename: str | None = None, style: dict | str | None = None, interactive: bool = False, plot_barriers: bool = True, reverse_bits: bool = None, justify: str | None = None, vertical_compression: str | None = "medium", idle_wires: bool = True, with_layout: bool = True, fold: int | None = None, # The type of ax is matplotlib.axes.Axes, but this is not a fixed dependency, so cannot be # safely forward-referenced. ax: Any | None = None, initial_state: bool = False, cregbundle: bool = None, wire_order: list = None, ): """Draw the quantum circuit. Use the output parameter to choose the drawing format: **text**: ASCII art TextDrawing that can be printed in the console. **mpl**: images with color rendered purely in Python using matplotlib. **latex**: high-quality images compiled via latex. **latex_source**: raw uncompiled latex output. .. warning:: Support for :class:`~.expr.Expr` nodes in conditions and :attr:`.SwitchCaseOp.target` fields is preliminary and incomplete. The ``text`` and ``mpl`` drawers will make a best-effort attempt to show data dependencies, but the LaTeX-based drawers will skip these completely. Args: output (str): select the output method to use for drawing the circuit. Valid choices are ``text``, ``mpl``, ``latex``, ``latex_source``. By default the `text` drawer is used unless the user config file (usually ``~/.qiskit/settings.conf``) has an alternative backend set as the default. For example, ``circuit_drawer = latex``. If the output kwarg is set, that backend will always be used over the default in the user config file. scale (float): scale of image to draw (shrink if < 1.0). Only used by the `mpl`, `latex` and `latex_source` outputs. Defaults to 1.0. filename (str): file path to save image to. Defaults to None. style (dict or str): dictionary of style or file name of style json file. This option is only used by the `mpl` or `latex` output type. If `style` is a str, it is used as the path to a json file which contains a style dict. The file will be opened, parsed, and then any style elements in the dict will replace the default values in the input dict. A file to be loaded must end in ``.json``, but the name entered here can omit ``.json``. For example, ``style='iqx.json'`` or ``style='iqx'``. If `style` is a dict and the ``'name'`` key is set, that name will be used to load a json file, followed by loading the other items in the style dict. For example, ``style={'name': 'iqx'}``. If `style` is not a str and `name` is not a key in the style dict, then the default value from the user config file (usually ``~/.qiskit/settings.conf``) will be used, for example, ``circuit_mpl_style = iqx``. If none of these are set, the `default` style will be used. The search path for style json files can be specified in the user config, for example, ``circuit_mpl_style_path = /home/user/styles:/home/user``. See: :class:`~qiskit.visualization.qcstyle.DefaultStyle` for more information on the contents. interactive (bool): when set to true, show the circuit in a new window (for `mpl` this depends on the matplotlib backend being used supporting this). Note when used with either the `text` or the `latex_source` output type this has no effect and will be silently ignored. Defaults to False. reverse_bits (bool): when set to True, reverse the bit order inside registers for the output visualization. Defaults to False unless the user config file (usually ``~/.qiskit/settings.conf``) has an alternative value set. For example, ``circuit_reverse_bits = True``. plot_barriers (bool): enable/disable drawing barriers in the output circuit. Defaults to True. justify (string): options are ``left``, ``right`` or ``none``. If anything else is supplied, it defaults to left justified. It refers to where gates should be placed in the output circuit if there is an option. ``none`` results in each gate being placed in its own column. vertical_compression (string): ``high``, ``medium`` or ``low``. It merges the lines generated by the `text` output so the drawing will take less vertical room. Default is ``medium``. Only used by the `text` output, will be silently ignored otherwise. idle_wires (bool): include idle wires (wires with no circuit elements) in output visualization. Default is True. with_layout (bool): include layout information, with labels on the physical layout. Default is True. fold (int): sets pagination. It can be disabled using -1. In `text`, sets the length of the lines. This is useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using ``shutil.get_terminal_size()``. However, if running in jupyter, the default line length is set to 80 characters. In `mpl`, it is the number of (visual) layers before folding. Default is 25. ax (matplotlib.axes.Axes): Only used by the `mpl` backend. An optional Axes object to be used for the visualization output. If none is specified, a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. initial_state (bool): Optional. Adds ``|0>`` in the beginning of the wire. Default is False. cregbundle (bool): Optional. If set True, bundle classical registers. Default is True, except for when ``output`` is set to ``"text"``. wire_order (list): Optional. A list of integers used to reorder the display of the bits. The list must have an entry for every bit with the bits in the range 0 to (``num_qubits`` + ``num_clbits``). Returns: :class:`.TextDrawing` or :class:`matplotlib.figure` or :class:`PIL.Image` or :class:`str`: * `TextDrawing` (output='text') A drawing that can be printed as ascii art. * `matplotlib.figure.Figure` (output='mpl') A matplotlib figure object for the circuit diagram. * `PIL.Image` (output='latex') An in-memory representation of the image of the circuit diagram. * `str` (output='latex_source') The LaTeX source code for visualizing the circuit diagram. Raises: VisualizationError: when an invalid output method is selected ImportError: when the output methods requires non-installed libraries. Example: .. plot:: :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'}) """ # pylint: disable=cyclic-import from qiskit.visualization import circuit_drawer return circuit_drawer( self, scale=scale, filename=filename, style=style, output=output, interactive=interactive, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify, vertical_compression=vertical_compression, idle_wires=idle_wires, with_layout=with_layout, fold=fold, ax=ax, initial_state=initial_state, cregbundle=cregbundle, wire_order=wire_order, ) def size( self, filter_function: Callable[..., int] = lambda x: not getattr( x.operation, "_directive", False ), ) -> int: """Returns total number of instructions in circuit. Args: filter_function (callable): a function to filter out some instructions. Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)). By default filters out "directives", such as barrier or snapshot. Returns: int: Total number of gate operations. """ return sum(map(filter_function, self._data)) def depth( self, filter_function: Callable[..., int] = lambda x: not getattr( x.operation, "_directive", False ), ) -> int: """Return circuit depth (i.e., length of critical path). Args: filter_function (callable): A function to filter instructions. Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)). Instructions for which the function returns False are ignored in the computation of the circuit depth. By default filters out "directives", such as barrier or snapshot. Returns: int: Depth of circuit. Notes: The circuit depth and the DAG depth need not be the same. """ # Assign each bit in the circuit a unique integer # to index into op_stack. bit_indices: dict[Qubit | Clbit, int] = { bit: idx for idx, bit in enumerate(self.qubits + self.clbits) } # If no bits, return 0 if not bit_indices: return 0 # A list that holds the height of each qubit # and classical bit. op_stack = [0] * len(bit_indices) # Here we are playing a modified version of # Tetris where we stack gates, but multi-qubit # gates, or measurements have a block for each # qubit or cbit that are connected by a virtual # line so that they all stacked at the same depth. # Conditional gates act on all cbits in the register # they are conditioned on. # The max stack height is the circuit depth. for instruction in self._data: levels = [] reg_ints = [] for ind, reg in enumerate(instruction.qubits + instruction.clbits): # Add to the stacks of the qubits and # cbits used in the gate. reg_ints.append(bit_indices[reg]) if filter_function(instruction): levels.append(op_stack[reg_ints[ind]] + 1) else: levels.append(op_stack[reg_ints[ind]]) # Assuming here that there is no conditional # snapshots or barriers ever. if getattr(instruction.operation, "condition", None): # Controls operate over all bits of a classical register # or over a single bit if isinstance(instruction.operation.condition[0], Clbit): condition_bits = [instruction.operation.condition[0]] else: condition_bits = instruction.operation.condition[0] for cbit in condition_bits: idx = bit_indices[cbit] if idx not in reg_ints: reg_ints.append(idx) levels.append(op_stack[idx] + 1) max_level = max(levels) for ind in reg_ints: op_stack[ind] = max_level return max(op_stack) def width(self) -> int: """Return number of qubits plus clbits in circuit. Returns: int: Width of circuit. """ return len(self.qubits) + len(self.clbits) @property def num_qubits(self) -> int: """Return number of qubits.""" return len(self.qubits) @property def num_ancillas(self) -> int: """Return the number of ancilla qubits.""" return len(self.ancillas) @property def num_clbits(self) -> int: """Return number of classical bits.""" return len(self.clbits) # The stringified return type is because OrderedDict can't be subscripted before Python 3.9, and # typing.OrderedDict wasn't added until 3.7.2. It can be turned into a proper type once 3.6 # support is dropped. def count_ops(self) -> "OrderedDict[Instruction, int]": """Count each operation kind in the circuit. Returns: OrderedDict: a breakdown of how many operations of each kind, sorted by amount. """ count_ops: dict[Instruction, int] = {} for instruction in self._data: count_ops[instruction.operation.name] = count_ops.get(instruction.operation.name, 0) + 1 return OrderedDict(sorted(count_ops.items(), key=lambda kv: kv[1], reverse=True)) def num_nonlocal_gates(self) -> int: """Return number of non-local gates (i.e. involving 2+ qubits). Conditional nonlocal gates are also included. """ multi_qubit_gates = 0 for instruction in self._data: if instruction.operation.num_qubits > 1 and not getattr( instruction.operation, "_directive", False ): multi_qubit_gates += 1 return multi_qubit_gates def get_instructions(self, name: str) -> list[CircuitInstruction]: """Get instructions matching name. Args: name (str): The name of instruction to. Returns: list(tuple): list of (instruction, qargs, cargs). """ return [match for match in self._data if match.operation.name == name] def num_connected_components(self, unitary_only: bool = False) -> int: """How many non-entangled subcircuits can the circuit be factored to. Args: unitary_only (bool): Compute only unitary part of graph. Returns: int: Number of connected components in circuit. """ # Convert registers to ints (as done in depth). bits = self.qubits if unitary_only else (self.qubits + self.clbits) bit_indices: dict[Qubit | Clbit, int] = {bit: idx for idx, bit in enumerate(bits)} # Start with each qubit or cbit being its own subgraph. sub_graphs = [[bit] for bit in range(len(bit_indices))] num_sub_graphs = len(sub_graphs) # Here we are traversing the gates and looking to see # which of the sub_graphs the gate joins together. for instruction in self._data: if unitary_only: args = instruction.qubits num_qargs = len(args) else: args = instruction.qubits + instruction.clbits num_qargs = len(args) + ( 1 if getattr(instruction.operation, "condition", None) else 0 ) if num_qargs >= 2 and not getattr(instruction.operation, "_directive", False): graphs_touched = [] num_touched = 0 # Controls necessarily join all the cbits in the # register that they use. if not unitary_only: for bit in instruction.operation.condition_bits: idx = bit_indices[bit] for k in range(num_sub_graphs): if idx in sub_graphs[k]: graphs_touched.append(k) break for item in args: reg_int = bit_indices[item] for k in range(num_sub_graphs): if reg_int in sub_graphs[k]: if k not in graphs_touched: graphs_touched.append(k) break graphs_touched = list(set(graphs_touched)) num_touched = len(graphs_touched) # If the gate touches more than one subgraph # join those graphs together and return # reduced number of subgraphs if num_touched > 1: connections = [] for idx in graphs_touched: connections.extend(sub_graphs[idx]) _sub_graphs = [] for idx in range(num_sub_graphs): if idx not in graphs_touched: _sub_graphs.append(sub_graphs[idx]) _sub_graphs.append(connections) sub_graphs = _sub_graphs num_sub_graphs -= num_touched - 1 # Cannot go lower than one so break if num_sub_graphs == 1: break return num_sub_graphs def num_unitary_factors(self) -> int: """Computes the number of tensor factors in the unitary (quantum) part of the circuit only. """ return self.num_connected_components(unitary_only=True) def num_tensor_factors(self) -> int: """Computes the number of tensor factors in the unitary (quantum) part of the circuit only. Notes: This is here for backwards compatibility, and will be removed in a future release of Qiskit. You should call `num_unitary_factors` instead. """ return self.num_unitary_factors() def copy(self, name: str | None = None) -> "QuantumCircuit": """Copy the circuit. Args: name (str): name to be given to the copied circuit. If None, then the name stays the same. Returns: QuantumCircuit: a deepcopy of the current circuit, with the specified name """ cpy = self.copy_empty_like(name) operation_copies = { id(instruction.operation): instruction.operation.copy() for instruction in self._data } cpy._parameter_table = ParameterTable( { param: ParameterReferences( (operation_copies[id(operation)], param_index) for operation, param_index in self._parameter_table[param] ) for param in self._parameter_table } ) cpy._data = [ instruction.replace(operation=operation_copies[id(instruction.operation)]) for instruction in self._data ] return cpy def copy_empty_like(self, name: str | None = None) -> "QuantumCircuit": """Return a copy of self with the same structure but empty. That structure includes: * name, calibrations and other metadata * global phase * all the qubits and clbits, including the registers Args: name (str): Name for the copied circuit. If None, then the name stays the same. Returns: QuantumCircuit: An empty copy of self. """ if not (name is None or isinstance(name, str)): raise TypeError( f"invalid name for a circuit: '{name}'. The name must be a string or 'None'." ) cpy = copy.copy(self) # copy registers correctly, in copy.copy they are only copied via reference cpy.qregs = self.qregs.copy() cpy.cregs = self.cregs.copy() cpy._qubits = self._qubits.copy() cpy._ancillas = self._ancillas.copy() cpy._clbits = self._clbits.copy() cpy._qubit_indices = self._qubit_indices.copy() cpy._clbit_indices = self._clbit_indices.copy() cpy._parameter_table = ParameterTable() cpy._data = [] cpy._calibrations = copy.deepcopy(self._calibrations) cpy._metadata = copy.deepcopy(self._metadata) if name: cpy.name = name return cpy def clear(self) -> None: """Clear all instructions in self. Clearing the circuits will keep the metadata and calibrations. """ self._data.clear() self._parameter_table.clear() def _create_creg(self, length: int, name: str) -> ClassicalRegister: """Creates a creg, checking if ClassicalRegister with same name exists""" if name in [creg.name for creg in self.cregs]: save_prefix = ClassicalRegister.prefix ClassicalRegister.prefix = name new_creg = ClassicalRegister(length) ClassicalRegister.prefix = save_prefix else: new_creg = ClassicalRegister(length, name) return new_creg def _create_qreg(self, length: int, name: str) -> QuantumRegister: """Creates a qreg, checking if QuantumRegister with same name exists""" if name in [qreg.name for qreg in self.qregs]: save_prefix = QuantumRegister.prefix QuantumRegister.prefix = name new_qreg = QuantumRegister(length) QuantumRegister.prefix = save_prefix else: new_qreg = QuantumRegister(length, name) return new_qreg def reset(self, qubit: QubitSpecifier) -> InstructionSet: """Reset the quantum bit(s) to their default state. Args: qubit: qubit(s) to reset. Returns: qiskit.circuit.InstructionSet: handle to the added instruction. """ return self.append(Reset(), [qubit], []) def measure(self, qubit: QubitSpecifier, cbit: ClbitSpecifier) -> InstructionSet: r"""Measure a quantum bit (``qubit``) in the Z basis into a classical bit (``cbit``). When a quantum state is measured, a qubit is projected in the computational (Pauli Z) basis to either :math:`\lvert 0 \rangle` or :math:`\lvert 1 \rangle`. The classical bit ``cbit`` indicates the result of that projection as a ``0`` or a ``1`` respectively. This operation is non-reversible. Args: qubit: qubit(s) to measure. cbit: classical bit(s) to place the measurement result(s) in. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. Raises: CircuitError: if arguments have bad format. Examples: In this example, a qubit is measured and the result of that measurement is stored in the classical bit (usually expressed in diagrams as a double line): .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(1, 1) circuit.h(0) circuit.measure(0, 0) circuit.draw() .. parsed-literal:: ┌───┐┌─┐ q: ┤ H ├┤M├ └───┘└╥┘ c: 1/══════╩═ 0 It is possible to call ``measure`` with lists of ``qubits`` and ``cbits`` as a shortcut for one-to-one measurement. These two forms produce identical results: .. code-block:: circuit = QuantumCircuit(2, 2) circuit.measure([0,1], [0,1]) .. code-block:: circuit = QuantumCircuit(2, 2) circuit.measure(0, 0) circuit.measure(1, 1) Instead of lists, you can use :class:`~qiskit.circuit.QuantumRegister` and :class:`~qiskit.circuit.ClassicalRegister` under the same logic. .. code-block:: from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qreg = QuantumRegister(2, "qreg") creg = ClassicalRegister(2, "creg") circuit = QuantumCircuit(qreg, creg) circuit.measure(qreg, creg) This is equivalent to: .. code-block:: circuit = QuantumCircuit(qreg, creg) circuit.measure(qreg[0], creg[0]) circuit.measure(qreg[1], creg[1]) """ return self.append(Measure(), [qubit], [cbit]) def measure_active(self, inplace: bool = True) -> Optional["QuantumCircuit"]: """Adds measurement to all non-idle qubits. Creates a new ClassicalRegister with a size equal to the number of non-idle qubits being measured. Returns a new circuit with measurements if `inplace=False`. Args: inplace (bool): All measurements inplace or return new circuit. Returns: QuantumCircuit: Returns circuit with measurements when `inplace = False`. """ from qiskit.converters.circuit_to_dag import circuit_to_dag if inplace: circ = self else: circ = self.copy() dag = circuit_to_dag(circ) qubits_to_measure = [qubit for qubit in circ.qubits if qubit not in dag.idle_wires()] new_creg = circ._create_creg(len(qubits_to_measure), "measure") circ.add_register(new_creg) circ.barrier() circ.measure(qubits_to_measure, new_creg) if not inplace: return circ else: return None def measure_all( self, inplace: bool = True, add_bits: bool = True ) -> Optional["QuantumCircuit"]: """Adds measurement to all qubits. By default, adds new classical bits in a :obj:`.ClassicalRegister` to store these measurements. If ``add_bits=False``, the results of the measurements will instead be stored in the already existing classical bits, with qubit ``n`` being measured into classical bit ``n``. Returns a new circuit with measurements if ``inplace=False``. Args: inplace (bool): All measurements inplace or return new circuit. add_bits (bool): Whether to add new bits to store the results. Returns: QuantumCircuit: Returns circuit with measurements when ``inplace=False``. Raises: CircuitError: if ``add_bits=False`` but there are not enough classical bits. """ if inplace: circ = self else: circ = self.copy() if add_bits: new_creg = circ._create_creg(len(circ.qubits), "meas") circ.add_register(new_creg) circ.barrier() circ.measure(circ.qubits, new_creg) else: if len(circ.clbits) < len(circ.qubits): raise CircuitError( "The number of classical bits must be equal or greater than " "the number of qubits." ) circ.barrier() circ.measure(circ.qubits, circ.clbits[0 : len(circ.qubits)]) if not inplace: return circ else: return None def remove_final_measurements(self, inplace: bool = True) -> Optional["QuantumCircuit"]: """Removes final measurements and barriers on all qubits if they are present. Deletes the classical registers that were used to store the values from these measurements that become idle as a result of this operation, and deletes classical bits that are referenced only by removed registers, or that aren't referenced at all but have become idle as a result of this operation. Measurements and barriers are considered final if they are followed by no other operations (aside from other measurements or barriers.) Args: inplace (bool): All measurements removed inplace or return new circuit. Returns: QuantumCircuit: Returns the resulting circuit when ``inplace=False``, else None. """ # pylint: disable=cyclic-import from qiskit.transpiler.passes import RemoveFinalMeasurements from qiskit.converters import circuit_to_dag if inplace: circ = self else: circ = self.copy() dag = circuit_to_dag(circ) remove_final_meas = RemoveFinalMeasurements() new_dag = remove_final_meas.run(dag) kept_cregs = set(new_dag.cregs.values()) kept_clbits = set(new_dag.clbits) # Filter only cregs/clbits still in new DAG, preserving original circuit order cregs_to_add = [creg for creg in circ.cregs if creg in kept_cregs] clbits_to_add = [clbit for clbit in circ._clbits if clbit in kept_clbits] # Clear cregs and clbits circ.cregs = [] circ._clbits = [] circ._clbit_indices = {} # We must add the clbits first to preserve the original circuit # order. This way, add_register never adds clbits and just # creates registers that point to them. circ.add_bits(clbits_to_add) for creg in cregs_to_add: circ.add_register(creg) # Clear instruction info circ.data.clear() circ._parameter_table.clear() # Set circ instructions to match the new DAG for node in new_dag.topological_op_nodes(): # Get arguments for classical condition (if any) inst = node.op.copy() circ.append(inst, node.qargs, node.cargs) if not inplace: return circ else: return None @staticmethod def from_qasm_file(path: str) -> "QuantumCircuit": """Take in a QASM file and generate a QuantumCircuit object. Args: path (str): Path to the file for a QASM program Return: QuantumCircuit: The QuantumCircuit object for the input QASM See also: :func:`.qasm2.load`: the complete interface to the OpenQASM 2 importer. """ # pylint: disable=cyclic-import from qiskit import qasm2 return qasm2.load( path, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) @staticmethod def from_qasm_str(qasm_str: str) -> "QuantumCircuit": """Take in a QASM string and generate a QuantumCircuit object. Args: qasm_str (str): A QASM program string Return: QuantumCircuit: The QuantumCircuit object for the input QASM See also: :func:`.qasm2.loads`: the complete interface to the OpenQASM 2 importer. """ # pylint: disable=cyclic-import from qiskit import qasm2 return qasm2.loads( qasm_str, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) @property def global_phase(self) -> ParameterValueType: """Return the global phase of the circuit in radians.""" return self._global_phase @global_phase.setter def global_phase(self, angle: ParameterValueType): """Set the phase of the circuit. Args: angle (float, ParameterExpression): radians """ if isinstance(angle, ParameterExpression) and angle.parameters: self._global_phase = angle else: # Set the phase to the [0, 2π) interval angle = float(angle) if not angle: self._global_phase = 0 else: self._global_phase = angle % (2 * np.pi) @property def parameters(self) -> ParameterView: """The parameters defined in the circuit. This attribute returns the :class:`.Parameter` objects in the circuit sorted alphabetically. Note that parameters instantiated with a :class:`.ParameterVector` are still sorted numerically. Examples: The snippet below shows that insertion order of parameters does not matter. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter >>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant") >>> circuit = QuantumCircuit(1) >>> circuit.rx(b, 0) >>> circuit.rz(elephant, 0) >>> circuit.ry(a, 0) >>> circuit.parameters # sorted alphabetically! ParameterView([Parameter(a), Parameter(b), Parameter(elephant)]) Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers. The literal "10" comes before "2" in strict alphabetical sorting. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter >>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")] >>> circuit = QuantumCircuit(1) >>> circuit.u(*angles, 0) >>> circuit.draw() ┌─────────────────────────────┐ q: ┤ U(angle_1,angle_2,angle_10) ├ └─────────────────────────────┘ >>> circuit.parameters ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)]) To respect numerical sorting, a :class:`.ParameterVector` can be used. .. code-block:: python >>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector >>> x = ParameterVector("x", 12) >>> circuit = QuantumCircuit(1) >>> for x_i in x: ... circuit.rx(x_i, 0) >>> circuit.parameters ParameterView([ ParameterVectorElement(x[0]), ParameterVectorElement(x[1]), ParameterVectorElement(x[2]), ParameterVectorElement(x[3]), ..., ParameterVectorElement(x[11]) ]) Returns: The sorted :class:`.Parameter` objects in the circuit. """ # parameters from gates if self._parameters is None: self._parameters = sort_parameters(self._unsorted_parameters()) # return as parameter view, which implements the set and list interface return ParameterView(self._parameters) @property def num_parameters(self) -> int: """The number of parameter objects in the circuit.""" return len(self._unsorted_parameters()) def _unsorted_parameters(self) -> set[Parameter]: """Efficiently get all parameters in the circuit, without any sorting overhead.""" parameters = set(self._parameter_table) if isinstance(self.global_phase, ParameterExpression): parameters.update(self.global_phase.parameters) return parameters @overload def assign_parameters( self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: Literal[False] = ..., *, flat_input: bool = ..., strict: bool = ..., ) -> "QuantumCircuit": ... @overload def assign_parameters( self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: Literal[True] = ..., *, flat_input: bool = ..., strict: bool = ..., ) -> None: ... def assign_parameters( # pylint: disable=missing-raises-doc self, parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]], inplace: bool = False, *, flat_input: bool = False, strict: bool = True, ) -> Optional["QuantumCircuit"]: """Assign parameters to new parameters or values. If ``parameters`` is passed as a dictionary, the keys must be :class:`.Parameter` instances in the current circuit. The values of the dictionary can either be numeric values or new parameter objects. If ``parameters`` is passed as a list or array, the elements are assigned to the current parameters in the order of :attr:`parameters` which is sorted alphabetically (while respecting the ordering in :class:`.ParameterVector` objects). The values can be assigned to the current circuit object or to a copy of it. Args: parameters: Either a dictionary or iterable specifying the new parameter values. inplace: If False, a copy of the circuit with the bound parameters is returned. If True the circuit instance itself is modified. flat_input: If ``True`` and ``parameters`` is a mapping type, it is assumed to be exactly a mapping of ``{parameter: value}``. By default (``False``), the mapping may also contain :class:`.ParameterVector` keys that point to a corresponding sequence of values, and these will be unrolled during the mapping. strict: If ``False``, any parameters given in the mapping that are not used in the circuit will be ignored. If ``True`` (the default), an error will be raised indicating a logic error. Raises: CircuitError: If parameters is a dict and contains parameters not present in the circuit. ValueError: If parameters is a list/array and the length mismatches the number of free parameters in the circuit. Returns: A copy of the circuit with bound parameters if ``inplace`` is False, otherwise None. Examples: Create a parameterized circuit and assign the parameters in-place. .. plot:: :include-source: from qiskit.circuit import QuantumCircuit, Parameter circuit = QuantumCircuit(2) params = [Parameter('A'), Parameter('B'), Parameter('C')] circuit.ry(params[0], 0) circuit.crx(params[1], 0, 1) circuit.draw('mpl') circuit.assign_parameters({params[0]: params[2]}, inplace=True) circuit.draw('mpl') Bind the values out-of-place by list and get a copy of the original circuit. .. plot:: :include-source: from qiskit.circuit import QuantumCircuit, ParameterVector circuit = QuantumCircuit(2) params = ParameterVector('P', 2) circuit.ry(params[0], 0) circuit.crx(params[1], 0, 1) bound_circuit = circuit.assign_parameters([1, 2]) bound_circuit.draw('mpl') circuit.draw('mpl') """ if inplace: target = self else: target = self.copy() target._increment_instances() target._name_update() # Normalise the inputs into simple abstract interfaces, so we've dispatched the "iteration" # logic in one place at the start of the function. This lets us do things like calculate # and cache expensive properties for (e.g.) the sequence format only if they're used; for # many large, close-to-hardware circuits, we won't need the extra handling for # `global_phase` or recursive definition binding. # # During normalisation, be sure to reference 'parameters' and related things from 'self' not # 'target' so we can take advantage of any caching we might be doing. if isinstance(parameters, dict): raw_mapping = parameters if flat_input else self._unroll_param_dict(parameters) our_parameters = self._unsorted_parameters() if strict and (extras := raw_mapping.keys() - our_parameters): raise CircuitError( f"Cannot bind parameters ({', '.join(str(x) for x in extras)}) not present in" " the circuit." ) parameter_binds = _ParameterBindsDict(raw_mapping, our_parameters) else: our_parameters = self.parameters if len(parameters) != len(our_parameters): raise ValueError( "Mismatching number of values and parameters. For partial binding " "please pass a dictionary of {parameter: value} pairs." ) parameter_binds = _ParameterBindsSequence(our_parameters, parameters) # Clear out the parameter table for the relevant entries, since we'll be binding those. # Any new references to parameters are reinserted as part of the bind. target._parameters = None # This is deliberately eager, because we want the side effect of clearing the table. all_references = [ (parameter, value, target._parameter_table.pop(parameter, ())) for parameter, value in parameter_binds.items() ] seen_operations = {} # The meat of the actual binding for regular operations. for to_bind, bound_value, references in all_references: update_parameters = ( tuple(bound_value.parameters) if isinstance(bound_value, ParameterExpression) else () ) for operation, index in references: seen_operations[id(operation)] = operation assignee = operation.params[index] if isinstance(assignee, ParameterExpression): new_parameter = assignee.assign(to_bind, bound_value) for parameter in update_parameters: if parameter not in target._parameter_table: target._parameter_table[parameter] = ParameterReferences(()) target._parameter_table[parameter].add((operation, index)) if not new_parameter.parameters: if new_parameter.is_real(): new_parameter = ( int(new_parameter) if new_parameter._symbol_expr.is_integer else float(new_parameter) ) else: new_parameter = complex(new_parameter) new_parameter = operation.validate_parameter(new_parameter) elif isinstance(assignee, QuantumCircuit): new_parameter = assignee.assign_parameters( {to_bind: bound_value}, inplace=False, flat_input=True ) else: raise RuntimeError( # pragma: no cover f"Saw an unknown type during symbolic binding: {assignee}." " This may indicate an internal logic error in symbol tracking." ) operation.params[index] = new_parameter # After we've been through everything at the top level, make a single visit to each # operation we've seen, rebinding its definition if necessary. for operation in seen_operations.values(): if ( definition := getattr(operation, "_definition", None) ) is not None and definition.num_parameters: definition.assign_parameters( parameter_binds.mapping, inplace=True, flat_input=True, strict=False ) if isinstance(target.global_phase, ParameterExpression): new_phase = target.global_phase for parameter in new_phase.parameters & parameter_binds.mapping.keys(): new_phase = new_phase.assign(parameter, parameter_binds.mapping[parameter]) target.global_phase = new_phase # Finally, assign the parameters inside any of the calibrations. We don't track these in # the `ParameterTable`, so we manually reconstruct things. def map_calibration(qubits, parameters, schedule): modified = False new_parameters = list(parameters) for i, parameter in enumerate(new_parameters): if not isinstance(parameter, ParameterExpression): continue if not (contained := parameter.parameters & parameter_binds.mapping.keys()): continue for to_bind in contained: parameter = parameter.assign(to_bind, parameter_binds.mapping[to_bind]) if not parameter.parameters: parameter = ( int(parameter) if parameter._symbol_expr.is_integer else float(parameter) ) new_parameters[i] = parameter modified = True if modified: schedule.assign_parameters(parameter_binds.mapping) return (qubits, tuple(new_parameters)), schedule target._calibrations = defaultdict( dict, ( ( gate, dict( map_calibration(qubits, parameters, schedule) for (qubits, parameters), schedule in calibrations.items() ), ) for gate, calibrations in target._calibrations.items() ), ) return None if inplace else target @staticmethod def _unroll_param_dict( parameter_binds: Mapping[Parameter, ParameterValueType] ) -> Mapping[Parameter, ParameterValueType]: out = {} for parameter, value in parameter_binds.items(): if isinstance(parameter, ParameterVector): if len(parameter) != len(value): raise CircuitError( f"Parameter vector '{parameter.name}' has length {len(parameter)}," f" but was assigned to {len(value)} values." ) out.update(zip(parameter, value)) else: out[parameter] = value return out def bind_parameters( self, values: Union[Mapping[Parameter, float], Sequence[float]] ) -> "QuantumCircuit": """Assign numeric parameters to values yielding a new circuit. If the values are given as list or array they are bound to the circuit in the order of :attr:`parameters` (see the docstring for more details). To assign new Parameter objects or bind the values in-place, without yielding a new circuit, use the :meth:`assign_parameters` method. Args: values: ``{parameter: value, ...}`` or ``[value1, value2, ...]`` Raises: CircuitError: If values is a dict and contains parameters not present in the circuit. TypeError: If values contains a ParameterExpression. Returns: Copy of self with assignment substitution. """ if isinstance(values, dict): if any(isinstance(value, ParameterExpression) for value in values.values()): raise TypeError( "Found ParameterExpression in values; use assign_parameters() instead." ) return self.assign_parameters(values) else: if any(isinstance(value, ParameterExpression) for value in values): raise TypeError( "Found ParameterExpression in values; use assign_parameters() instead." ) return self.assign_parameters(values) def barrier(self, *qargs: QubitSpecifier, label=None) -> InstructionSet: """Apply :class:`~.library.Barrier`. If ``qargs`` is empty, applies to all qubits in the circuit. Args: qargs (QubitSpecifier): Specification for one or more qubit arguments. label (str): The string label of the barrier. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. """ from .barrier import Barrier qubits: list[QubitSpecifier] = [] if not qargs: # None qubits.extend(self.qubits) for qarg in qargs: if isinstance(qarg, QuantumRegister): qubits.extend([qarg[j] for j in range(qarg.size)]) elif isinstance(qarg, list): qubits.extend(qarg) elif isinstance(qarg, range): qubits.extend(list(qarg)) elif isinstance(qarg, slice): qubits.extend(self.qubits[qarg]) else: qubits.append(qarg) return self.append(Barrier(len(qubits), label=label), qubits, []) def delay( self, duration: ParameterValueType, qarg: QubitSpecifier | None = None, unit: str = "dt", ) -> InstructionSet: """Apply :class:`~.circuit.Delay`. If qarg is ``None``, applies to all qubits. When applying to multiple qubits, delays with the same duration will be created. Args: duration (int or float or ParameterExpression): duration of the delay. qarg (Object): qubit argument to apply this delay. unit (str): unit of the duration. Supported units: ``'s'``, ``'ms'``, ``'us'``, ``'ns'``, ``'ps'``, and ``'dt'``. Default is ``'dt'``, i.e. integer time unit depending on the target backend. Returns: qiskit.circuit.InstructionSet: handle to the added instructions. Raises: CircuitError: if arguments have bad format. """ qubits: list[QubitSpecifier] = [] if qarg is None: # -> apply delays to all qubits for q in self.qubits: qubits.append(q) else: if isinstance(qarg, QuantumRegister): qubits.extend([qarg[j] for j in range(qarg.size)]) elif isinstance(qarg, list): qubits.extend(qarg) elif isinstance(qarg, (range, tuple)): qubits.extend(list(qarg)) elif isinstance(qarg, slice): qubits.extend(self.qubits[qarg]) else: qubits.append(qarg) instructions = InstructionSet(resource_requester=self._resolve_classical_resource) for q in qubits: inst: tuple[ Instruction, Sequence[QubitSpecifier] | None, Sequence[ClbitSpecifier] | None ] = (Delay(duration, unit), [q], []) self.append(*inst) instructions.add(*inst) return instructions def h(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.HGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.h import HGate return self.append(HGate(), [qubit], []) def ch( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CHGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.h import CHGate return self.append( CHGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def i(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.IGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.i import IGate return self.append(IGate(), [qubit], []) def id(self, qubit: QubitSpecifier) -> InstructionSet: # pylint: disable=invalid-name """Apply :class:`~qiskit.circuit.library.IGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. See Also: QuantumCircuit.i: the same function. """ return self.i(qubit) def ms(self, theta: ParameterValueType, qubits: Sequence[QubitSpecifier]) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MSGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. qubits: The qubits to apply the gate to. Returns: A handle to the instructions created. """ # pylint: disable=cyclic-import from .library.generalized_gates.gms import MSGate return self.append(MSGate(len(qubits), theta), qubits) def p(self, theta: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.PhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: THe angle of the rotation. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.p import PhaseGate return self.append(PhaseGate(theta), [qubit], []) def cp( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CPhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.p import CPhaseGate return self.append( CPhaseGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def mcp( self, lam: ParameterValueType, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCPhaseGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: lam: The angle of the rotation. control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.p import MCPhaseGate num_ctrl_qubits = len(control_qubits) return self.append( MCPhaseGate(lam, num_ctrl_qubits), control_qubits[:] + [target_qubit], [] ) def r( self, theta: ParameterValueType, phi: ParameterValueType, qubit: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. phi: The angle of the axis of rotation in the x-y plane. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.r import RGate return self.append(RGate(theta, phi), [qubit], []) def rv( self, vx: ParameterValueType, vy: ParameterValueType, vz: ParameterValueType, qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RVGate`. For the full matrix form of this gate, see the underlying gate documentation. Rotation around an arbitrary rotation axis :math:`v`, where :math:`|v|` is the angle of rotation in radians. Args: vx: x-component of the rotation axis. vy: y-component of the rotation axis. vz: z-component of the rotation axis. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.generalized_gates.rv import RVGate return self.append(RVGate(vx, vy, vz), [qubit], []) def rccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RCCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.x import RCCXGate return self.append(RCCXGate(), [control_qubit1, control_qubit2, target_qubit], []) def rcccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, control_qubit3: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RC3XGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. control_qubit3: The qubit(s) used as the third control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. """ from .library.standard_gates.x import RC3XGate return self.append( RC3XGate(), [control_qubit1, control_qubit2, control_qubit3, target_qubit], [] ) def rx( self, theta: ParameterValueType, qubit: QubitSpecifier, label: str | None = None ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.rx import RXGate return self.append(RXGate(theta, label=label), [qubit], []) def crx( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.rx import CRXGate return self.append( CRXGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def rxx( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RXXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rxx import RXXGate return self.append(RXXGate(theta), [qubit1, qubit2], []) def ry( self, theta: ParameterValueType, qubit: QubitSpecifier, label: str | None = None ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.ry import RYGate return self.append(RYGate(theta, label=label), [qubit], []) def cry( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.ry import CRYGate return self.append( CRYGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def ryy( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RYYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.ryy import RYYGate return self.append(RYYGate(theta), [qubit1, qubit2], []) def rz(self, phi: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: phi: The rotation angle of the gate. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rz import RZGate return self.append(RZGate(phi), [qubit], []) def crz( self, theta: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CRZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The angle of the rotation. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.rz import CRZGate return self.append( CRZGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def rzx( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rzx import RZXGate return self.append(RZXGate(theta), [qubit1, qubit2], []) def rzz( self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.RZZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The rotation angle of the gate. qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.rzz import RZZGate return self.append(RZZGate(theta), [qubit1, qubit2], []) def ecr(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.ECRGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.ecr import ECRGate return self.append(ECRGate(), [qubit1, qubit2], []) def s(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.s import SGate return self.append(SGate(), [qubit], []) def sdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.s import SdgGate return self.append(SdgGate(), [qubit], []) def cs( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.s import CSGate return self.append( CSGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def csdg( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.s import CSdgGate return self.append( CSdgGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def swap(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.swap import SwapGate return self.append(SwapGate(), [qubit1, qubit2], []) def iswap(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.iSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1, qubit2: The qubits to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.iswap import iSwapGate return self.append(iSwapGate(), [qubit1, qubit2], []) def cswap( self, control_qubit: QubitSpecifier, target_qubit1: QubitSpecifier, target_qubit2: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit1: The qubit(s) targeted by the gate. target_qubit2: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. ``'1'``). Defaults to controlling on the ``'1'`` state. Returns: A handle to the instructions created. """ from .library.standard_gates.swap import CSwapGate return self.append( CSwapGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit1, target_qubit2], [], ) def fredkin( self, control_qubit: QubitSpecifier, target_qubit1: QubitSpecifier, target_qubit2: QubitSpecifier, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSwapGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit1: The qubit(s) targeted by the gate. target_qubit2: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. See Also: QuantumCircuit.cswap: the same function with a different name. """ return self.cswap(control_qubit, target_qubit1, target_qubit2) def sx(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import SXGate return self.append(SXGate(), [qubit], []) def sxdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SXdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import SXdgGate return self.append(SXdgGate(), [qubit], []) def csx( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.CSXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.sx import CSXGate return self.append( CSXGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def t(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.TGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.t import TGate return self.append(TGate(), [qubit], []) def tdg(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.TdgGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.t import TdgGate return self.append(TdgGate(), [qubit], []) def u( self, theta: ParameterValueType, phi: ParameterValueType, lam: ParameterValueType, qubit: QubitSpecifier, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.UGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The :math:`\theta` rotation angle of the gate. phi: The :math:`\phi` rotation angle of the gate. lam: The :math:`\lambda` rotation angle of the gate. qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.u import UGate return self.append(UGate(theta, phi, lam), [qubit], []) def cu( self, theta: ParameterValueType, phi: ParameterValueType, lam: ParameterValueType, gamma: ParameterValueType, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CUGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: theta: The :math:`\theta` rotation angle of the gate. phi: The :math:`\phi` rotation angle of the gate. lam: The :math:`\lambda` rotation angle of the gate. gamma: The global phase applied of the U gate, if applied. control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.u import CUGate return self.append( CUGate(theta, phi, lam, gamma, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [], ) def x(self, qubit: QubitSpecifier, label: str | None = None) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.XGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. label: The string label of the gate in the circuit. Returns: A handle to the instructions created. """ from .library.standard_gates.x import XGate return self.append(XGate(label=label), [qubit], []) def cx( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.x import CXGate return self.append( CXGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def cnot( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. See Also: QuantumCircuit.cx: the same function with a different name. """ return self.cx(control_qubit, target_qubit, label, ctrl_state) def dcx(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.DCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit1: The qubit(s) to apply the gate to. qubit2: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.dcx import DCXGate return self.append(DCXGate(), [qubit1, qubit2], []) def ccx( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.x import CCXGate return self.append( CCXGate(ctrl_state=ctrl_state), [control_qubit1, control_qubit2, target_qubit], [], ) def toffoli( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCXGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. Returns: A handle to the instructions created. See Also: QuantumCircuit.ccx: the same gate with a different name. """ return self.ccx(control_qubit1, control_qubit2, target_qubit) def mcx( self, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ancilla_qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, mode: str = "noancilla", ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCXGate`. The multi-cX gate can be implemented using different techniques, which use different numbers of ancilla qubits and have varying circuit depth. These modes are: - ``'noancilla'``: Requires 0 ancilla qubits. - ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0. - ``'v-chain'``: Requires 2 less ancillas than the number of control qubits. - ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer). For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. ancilla_qubits: The qubits used as the ancillae, if the mode requires them. mode: The choice of mode, explained further above. Returns: A handle to the instructions created. Raises: ValueError: if the given mode is not known, or if too few ancilla qubits are passed. AttributeError: if no ancilla qubits are passed, but some are needed. """ from .library.standard_gates.x import MCXGrayCode, MCXRecursive, MCXVChain num_ctrl_qubits = len(control_qubits) available_implementations = { "noancilla": MCXGrayCode(num_ctrl_qubits), "recursion": MCXRecursive(num_ctrl_qubits), "v-chain": MCXVChain(num_ctrl_qubits, False), "v-chain-dirty": MCXVChain(num_ctrl_qubits, dirty_ancillas=True), # outdated, previous names "advanced": MCXRecursive(num_ctrl_qubits), "basic": MCXVChain(num_ctrl_qubits, dirty_ancillas=False), "basic-dirty-ancilla": MCXVChain(num_ctrl_qubits, dirty_ancillas=True), } # check ancilla input if ancilla_qubits: _ = self.qbit_argument_conversion(ancilla_qubits) try: gate = available_implementations[mode] except KeyError as ex: all_modes = list(available_implementations.keys()) raise ValueError( f"Unsupported mode ({mode}) selected, choose one of {all_modes}" ) from ex if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0: required = gate.num_ancilla_qubits if ancilla_qubits is None: raise AttributeError(f"No ancillas provided, but {required} are needed!") # convert ancilla qubits to a list if they were passed as int or qubit if not hasattr(ancilla_qubits, "__len__"): ancilla_qubits = [ancilla_qubits] if len(ancilla_qubits) < required: actually = len(ancilla_qubits) raise ValueError(f"At least {required} ancillas required, but {actually} given.") # size down if too many ancillas were provided ancilla_qubits = ancilla_qubits[:required] else: ancilla_qubits = [] return self.append(gate, control_qubits[:] + [target_qubit] + ancilla_qubits[:], []) def mct( self, control_qubits: Sequence[QubitSpecifier], target_qubit: QubitSpecifier, ancilla_qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, mode: str = "noancilla", ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.MCXGate`. The multi-cX gate can be implemented using different techniques, which use different numbers of ancilla qubits and have varying circuit depth. These modes are: - ``'noancilla'``: Requires 0 ancilla qubits. - ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0. - ``'v-chain'``: Requires 2 less ancillas than the number of control qubits. - ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer). For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubits: The qubits used as the controls. target_qubit: The qubit(s) targeted by the gate. ancilla_qubits: The qubits used as the ancillae, if the mode requires them. mode: The choice of mode, explained further above. Returns: A handle to the instructions created. Raises: ValueError: if the given mode is not known, or if too few ancilla qubits are passed. AttributeError: if no ancilla qubits are passed, but some are needed. See Also: QuantumCircuit.mcx: the same gate with a different name. """ return self.mcx(control_qubits, target_qubit, ancilla_qubits, mode) def y(self, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.YGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.y import YGate return self.append(YGate(), [qubit], []) def cy( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CYGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the controls. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.y import CYGate return self.append( CYGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def z(self, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.ZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: qubit: The qubit(s) to apply the gate to. Returns: A handle to the instructions created. """ from .library.standard_gates.z import ZGate return self.append(ZGate(), [qubit], []) def cz( self, control_qubit: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit: The qubit(s) used as the controls. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling on the '1' state. Returns: A handle to the instructions created. """ from .library.standard_gates.z import CZGate return self.append( CZGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) def ccz( self, control_qubit1: QubitSpecifier, control_qubit2: QubitSpecifier, target_qubit: QubitSpecifier, label: str | None = None, ctrl_state: str | int | None = None, ) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.CCZGate`. For the full matrix form of this gate, see the underlying gate documentation. Args: control_qubit1: The qubit(s) used as the first control. control_qubit2: The qubit(s) used as the second control. target_qubit: The qubit(s) targeted by the gate. label: The string label of the gate in the circuit. ctrl_state: The control state in decimal, or as a bitstring (e.g. '10'). Defaults to controlling on the '11' state. Returns: A handle to the instructions created. """ from .library.standard_gates.z import CCZGate return self.append( CCZGate(label=label, ctrl_state=ctrl_state), [control_qubit1, control_qubit2, target_qubit], [], ) def pauli( self, pauli_string: str, qubits: Sequence[QubitSpecifier], ) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.PauliGate`. Args: pauli_string: A string representing the Pauli operator to apply, e.g. 'XX'. qubits: The qubits to apply this gate to. Returns: A handle to the instructions created. """ from qiskit.circuit.library.generalized_gates.pauli import PauliGate return self.append(PauliGate(pauli_string), qubits, []) def _push_scope( self, qubits: Iterable[Qubit] = (), clbits: Iterable[Clbit] = (), registers: Iterable[Register] = (), allow_jumps: bool = True, forbidden_message: Optional[str] = None, ): """Add a scope for collecting instructions into this circuit. This should only be done by the control-flow context managers, which will handle cleaning up after themselves at the end as well. Args: qubits: Any qubits that this scope should automatically use. clbits: Any clbits that this scope should automatically use. allow_jumps: Whether this scope allows jumps to be used within it. forbidden_message: If given, all attempts to add instructions to this scope will raise a :exc:`.CircuitError` with this message. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.builder import ControlFlowBuilderBlock # Chain resource requests so things like registers added to inner scopes via conditions are # requested in the outer scope as well. if self._control_flow_scopes: resource_requester = self._control_flow_scopes[-1].request_classical_resource else: resource_requester = self._resolve_classical_resource self._control_flow_scopes.append( ControlFlowBuilderBlock( qubits, clbits, resource_requester=resource_requester, registers=registers, allow_jumps=allow_jumps, forbidden_message=forbidden_message, ) ) def _pop_scope(self) -> "qiskit.circuit.controlflow.builder.ControlFlowBuilderBlock": """Finish a scope used in the control-flow builder interface, and return it to the caller. This should only be done by the control-flow context managers, since they naturally synchronise the creation and deletion of stack elements.""" return self._control_flow_scopes.pop() def _peek_previous_instruction_in_scope(self) -> CircuitInstruction: """Return the instruction 3-tuple of the most recent instruction in the current scope, even if that scope is currently under construction. This function is only intended for use by the control-flow ``if``-statement builders, which may need to modify a previous instruction.""" if self._control_flow_scopes: return self._control_flow_scopes[-1].peek() if not self._data: raise CircuitError("This circuit contains no instructions.") return self._data[-1] def _pop_previous_instruction_in_scope(self) -> CircuitInstruction: """Return the instruction 3-tuple of the most recent instruction in the current scope, even if that scope is currently under construction, and remove it from that scope. This function is only intended for use by the control-flow ``if``-statement builders, which may need to replace a previous instruction with another. """ if self._control_flow_scopes: return self._control_flow_scopes[-1].pop() if not self._data: raise CircuitError("This circuit contains no instructions.") instruction = self._data.pop() if isinstance(instruction.operation, Instruction): self._update_parameter_table_on_instruction_removal(instruction) return instruction def _update_parameter_table_on_instruction_removal(self, instruction: CircuitInstruction): """Update the :obj:`.ParameterTable` of this circuit given that an instance of the given ``instruction`` has just been removed from the circuit. .. note:: This does not account for the possibility for the same instruction instance being added more than once to the circuit. At the time of writing (2021-11-17, main commit 271a82f) there is a defensive ``deepcopy`` of parameterised instructions inside :meth:`.QuantumCircuit.append`, so this should be safe. Trying to account for it would involve adding a potentially quadratic-scaling loop to check each entry in ``data``. """ atomic_parameters: list[tuple[Parameter, int]] = [] for index, parameter in enumerate(instruction.operation.params): if isinstance(parameter, (ParameterExpression, QuantumCircuit)): atomic_parameters.extend((p, index) for p in parameter.parameters) for atomic_parameter, index in atomic_parameters: new_entries = self._parameter_table[atomic_parameter].copy() new_entries.discard((instruction.operation, index)) if not new_entries: del self._parameter_table[atomic_parameter] # Invalidate cache. self._parameters = None else: self._parameter_table[atomic_parameter] = new_entries @typing.overload def while_loop( self, condition: tuple[ClassicalRegister | Clbit, int] | expr.Expr, body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.while_loop.WhileLoopContext": ... @typing.overload def while_loop( self, condition: tuple[ClassicalRegister | Clbit, int] | expr.Expr, body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None, ) -> InstructionSet: ... def while_loop(self, condition, body=None, qubits=None, clbits=None, *, label=None): """Create a ``while`` loop on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :obj:`~qiskit.circuit.controlflow.WhileLoopOp` with the given ``body``. If ``body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which will automatically build a :obj:`~qiskit.circuit.controlflow.WhileLoopOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. Example usage:: from qiskit.circuit import QuantumCircuit, Clbit, Qubit bits = [Qubit(), Qubit(), Clbit()] qc = QuantumCircuit(bits) with qc.while_loop((bits[2], 0)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) Args: condition (Tuple[Union[ClassicalRegister, Clbit], int]): An equality condition to be checked prior to executing ``body``. The left-hand side of the condition must be a :obj:`~ClassicalRegister` or a :obj:`~Clbit`, and the right-hand side must be an integer or boolean. body (Optional[QuantumCircuit]): The loop body to be repeatedly executed. Omit this to use the context-manager mode. qubits (Optional[Sequence[Qubit]]): The circuit qubits over which the loop body should be run. Omit this to use the context-manager mode. clbits (Optional[Sequence[Clbit]]): The circuit clbits over which the loop body should be run. Omit this to use the context-manager mode. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or WhileLoopContext: If used in context-manager mode, then this should be used as a ``with`` resource, which will infer the block content and operands on exit. If the full form is used, then this returns a handle to the instructions created. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.while_loop import WhileLoopOp, WhileLoopContext if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) if body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'while_loop' as a context manager," " you cannot pass qubits or clbits." ) return WhileLoopContext(self, condition, label=label) elif qubits is None or clbits is None: raise CircuitError( "When using 'while_loop' with a body, you must pass qubits and clbits." ) return self.append(WhileLoopOp(condition, body, label), qubits, clbits) @typing.overload def for_loop( self, indexset: Iterable[int], loop_parameter: Parameter | None, body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.for_loop.ForLoopContext": ... @typing.overload def for_loop( self, indexset: Iterable[int], loop_parameter: Union[Parameter, None], body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None, ) -> InstructionSet: ... def for_loop( self, indexset, loop_parameter=None, body=None, qubits=None, clbits=None, *, label=None ): """Create a ``for`` loop on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :class:`~qiskit.circuit.ForLoopOp` with the given ``body``. If ``body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which, when entered, provides a loop variable (unless one is given, in which case it will be reused) and will automatically build a :class:`~qiskit.circuit.ForLoopOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. For example:: from qiskit import QuantumCircuit qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)) as i: qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) Args: indexset (Iterable[int]): A collection of integers to loop over. Always necessary. loop_parameter (Optional[Parameter]): The parameter used within ``body`` to which the values from ``indexset`` will be assigned. In the context-manager form, if this argument is not supplied, then a loop parameter will be allocated for you and returned as the value of the ``with`` statement. This will only be bound into the circuit if it is used within the body. If this argument is ``None`` in the manual form of this method, ``body`` will be repeated once for each of the items in ``indexset`` but their values will be ignored. body (Optional[QuantumCircuit]): The loop body to be repeatedly executed. Omit this to use the context-manager mode. qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the loop body should be run. Omit this to use the context-manager mode. clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the loop body should be run. Omit this to use the context-manager mode. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or ForLoopContext: depending on the call signature, either a context manager for creating the for loop (it will automatically be added to the circuit at the end of the block), or an :obj:`~InstructionSet` handle to the appended loop operation. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.for_loop import ForLoopOp, ForLoopContext if body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'for_loop' as a context manager, you cannot pass qubits or clbits." ) return ForLoopContext(self, indexset, loop_parameter, label=label) elif qubits is None or clbits is None: raise CircuitError( "When using 'for_loop' with a body, you must pass qubits and clbits." ) return self.append(ForLoopOp(indexset, loop_parameter, body, label), qubits, clbits) @typing.overload def if_test( self, condition: tuple[ClassicalRegister | Clbit, int], true_body: None, qubits: None, clbits: None, *, label: str | None, ) -> "qiskit.circuit.controlflow.if_else.IfContext": ... @typing.overload def if_test( self, condition: tuple[ClassicalRegister | Clbit, int], true_body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: str | None = None, ) -> InstructionSet: ... def if_test( self, condition, true_body=None, qubits=None, clbits=None, *, label=None, ): """Create an ``if`` statement on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :obj:`~qiskit.circuit.IfElseOp` with the given ``true_body``, and there will be no branch for the ``false`` condition (see also the :meth:`.if_else` method). However, if ``true_body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which can be used to build ``if`` statements. The return value of the ``with`` statement is a chainable context manager, which can be used to create subsequent ``else`` blocks. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. For example:: from qiskit.circuit import QuantumCircuit, Qubit, Clbit bits = [Qubit(), Qubit(), Qubit(), Clbit(), Clbit()] qc = QuantumCircuit(bits) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.h(0) qc.cx(0, 1) qc.measure(0, 1) with qc.if_test((bits[3], 0)) as else_: qc.x(2) with else_: qc.h(2) qc.z(2) Args: condition (Tuple[Union[ClassicalRegister, Clbit], int]): A condition to be evaluated at circuit runtime which, if true, will trigger the evaluation of ``true_body``. Can be specified as either a tuple of a ``ClassicalRegister`` to be tested for equality with a given ``int``, or as a tuple of a ``Clbit`` to be compared to either a ``bool`` or an ``int``. true_body (Optional[QuantumCircuit]): The circuit body to be run if ``condition`` is true. qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the if/else should be run. clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the if/else should be run. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or IfContext: depending on the call signature, either a context manager for creating the ``if`` block (it will automatically be added to the circuit at the end of the block), or an :obj:`~InstructionSet` handle to the appended conditional operation. Raises: CircuitError: If the provided condition references Clbits outside the enclosing circuit. CircuitError: if an incorrect calling convention is used. Returns: A handle to the instruction created. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.if_else import IfElseOp, IfContext if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) if true_body is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'if_test' as a context manager, you cannot pass qubits or clbits." ) # We can only allow jumps if we're in a loop block, but the default path (no scopes) # also allows adding jumps to support the more verbose internal mode. in_loop = bool(self._control_flow_scopes and self._control_flow_scopes[-1].allow_jumps) return IfContext(self, condition, in_loop=in_loop, label=label) elif qubits is None or clbits is None: raise CircuitError("When using 'if_test' with a body, you must pass qubits and clbits.") return self.append(IfElseOp(condition, true_body, None, label), qubits, clbits) def if_else( self, condition: tuple[ClassicalRegister, int] | tuple[Clbit, int] | tuple[Clbit, bool], true_body: "QuantumCircuit", false_body: "QuantumCircuit", qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], label: str | None = None, ) -> InstructionSet: """Apply :class:`~qiskit.circuit.IfElseOp`. .. note:: This method does not have an associated context-manager form, because it is already handled by the :meth:`.if_test` method. You can use the ``else`` part of that with something such as:: from qiskit.circuit import QuantumCircuit, Qubit, Clbit bits = [Qubit(), Qubit(), Clbit()] qc = QuantumCircuit(bits) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) with qc.if_test((bits[2], 0)) as else_: qc.h(0) with else_: qc.x(0) Args: condition: A condition to be evaluated at circuit runtime which, if true, will trigger the evaluation of ``true_body``. Can be specified as either a tuple of a ``ClassicalRegister`` to be tested for equality with a given ``int``, or as a tuple of a ``Clbit`` to be compared to either a ``bool`` or an ``int``. true_body: The circuit body to be run if ``condition`` is true. false_body: The circuit to be run if ``condition`` is false. qubits: The circuit qubits over which the if/else should be run. clbits: The circuit clbits over which the if/else should be run. label: The string label of the instruction in the circuit. Raises: CircuitError: If the provided condition references Clbits outside the enclosing circuit. Returns: A handle to the instruction created. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.if_else import IfElseOp if isinstance(condition, expr.Expr): condition = self._validate_expr(condition) else: condition = (self._resolve_classical_resource(condition[0]), condition[1]) return self.append(IfElseOp(condition, true_body, false_body, label), qubits, clbits) @typing.overload def switch( self, target: Union[ClbitSpecifier, ClassicalRegister], cases: None, qubits: None, clbits: None, *, label: Optional[str], ) -> "qiskit.circuit.controlflow.switch_case.SwitchContext": ... @typing.overload def switch( self, target: Union[ClbitSpecifier, ClassicalRegister], cases: Iterable[Tuple[typing.Any, QuantumCircuit]], qubits: Sequence[QubitSpecifier], clbits: Sequence[ClbitSpecifier], *, label: Optional[str], ) -> InstructionSet: ... def switch(self, target, cases=None, qubits=None, clbits=None, *, label=None): """Create a ``switch``/``case`` structure on this circuit. There are two forms for calling this function. If called with all its arguments (with the possible exception of ``label``), it will create a :class:`.SwitchCaseOp` with the given case structure. If ``cases`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which will automatically build a :class:`.SwitchCaseOp` when the scope finishes. In this form, you do not need to keep track of the qubits or clbits you are using, because the scope will handle it for you. Example usage:: from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister qreg = QuantumRegister(3) creg = ClassicalRegister(3) qc = QuantumCircuit(qreg, creg) qc.h([0, 1, 2]) qc.measure([0, 1, 2], [0, 1, 2]) with qc.switch(creg) as case: with case(0): qc.x(0) with case(1, 2): qc.z(1) with case(case.DEFAULT): qc.cx(0, 1) Args: target (Union[ClassicalRegister, Clbit]): The classical value to switch one. This must be integer-like. cases (Iterable[Tuple[typing.Any, QuantumCircuit]]): A sequence of case specifiers. Each tuple defines one case body (the second item). The first item of the tuple can be either a single integer value, the special value :data:`.CASE_DEFAULT`, or a tuple of several integer values. Each of the integer values will be tried in turn; control will then pass to the body corresponding to the first match. :data:`.CASE_DEFAULT` matches all possible values. Omit in context-manager form. qubits (Sequence[Qubit]): The circuit qubits over which all case bodies execute. Omit in context-manager form. clbits (Sequence[Clbit]): The circuit clbits over which all case bodies execute. Omit in context-manager form. label (Optional[str]): The string label of the instruction in the circuit. Returns: InstructionSet or SwitchCaseContext: If used in context-manager mode, then this should be used as a ``with`` resource, which will return an object that can be repeatedly entered to produce cases for the switch statement. If the full form is used, then this returns a handle to the instructions created. Raises: CircuitError: if an incorrect calling convention is used. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.switch_case import SwitchCaseOp, SwitchContext if isinstance(target, expr.Expr): target = self._validate_expr(target) else: target = self._resolve_classical_resource(target) if cases is None: if qubits is not None or clbits is not None: raise CircuitError( "When using 'switch' as a context manager, you cannot pass qubits or clbits." ) in_loop = bool(self._control_flow_scopes and self._control_flow_scopes[-1].allow_jumps) return SwitchContext(self, target, in_loop=in_loop, label=label) if qubits is None or clbits is None: raise CircuitError("When using 'switch' with cases, you must pass qubits and clbits.") return self.append(SwitchCaseOp(target, cases, label=label), qubits, clbits) def break_loop(self) -> InstructionSet: """Apply :class:`~qiskit.circuit.BreakLoopOp`. .. warning:: If you are using the context-manager "builder" forms of :meth:`.if_test`, :meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are within a loop context, because otherwise the "resource width" of the operation cannot be determined. This would quickly lead to invalid circuits, and so if you are trying to construct a reusable loop body (without the context managers), you must also use the non-context-manager form of :meth:`.if_test` and :meth:`.if_else`. Take care that the :obj:`.BreakLoopOp` instruction must span all the resources of its containing loop, not just the immediate scope. Returns: A handle to the instruction created. Raises: CircuitError: if this method was called within a builder context, but not contained within a loop. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.break_loop import BreakLoopOp, BreakLoopPlaceholder if self._control_flow_scopes: operation = BreakLoopPlaceholder() resources = operation.placeholder_resources() return self.append(operation, resources.qubits, resources.clbits) return self.append(BreakLoopOp(self.num_qubits, self.num_clbits), self.qubits, self.clbits) def continue_loop(self) -> InstructionSet: """Apply :class:`~qiskit.circuit.ContinueLoopOp`. .. warning:: If you are using the context-manager "builder" forms of :meth:`.if_test`, :meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are within a loop context, because otherwise the "resource width" of the operation cannot be determined. This would quickly lead to invalid circuits, and so if you are trying to construct a reusable loop body (without the context managers), you must also use the non-context-manager form of :meth:`.if_test` and :meth:`.if_else`. Take care that the :class:`~qiskit.circuit.ContinueLoopOp` instruction must span all the resources of its containing loop, not just the immediate scope. Returns: A handle to the instruction created. Raises: CircuitError: if this method was called within a builder context, but not contained within a loop. """ # pylint: disable=cyclic-import from qiskit.circuit.controlflow.continue_loop import ContinueLoopOp, ContinueLoopPlaceholder if self._control_flow_scopes: operation = ContinueLoopPlaceholder() resources = operation.placeholder_resources() return self.append(operation, resources.qubits, resources.clbits) return self.append( ContinueLoopOp(self.num_qubits, self.num_clbits), self.qubits, self.clbits ) def add_calibration( self, gate: Union[Gate, str], qubits: Sequence[int], # Schedule has the type `qiskit.pulse.Schedule`, but `qiskit.pulse` cannot be imported # while this module is, and so Sphinx will not accept a forward reference to it. Sphinx # needs the types available at runtime, whereas mypy will accept it, because it handles the # type checking by static analysis. schedule, params: Sequence[ParameterValueType] | None = None, ) -> None: """Register a low-level, custom pulse definition for the given gate. Args: gate (Union[Gate, str]): Gate information. qubits (Union[int, Tuple[int]]): List of qubits to be measured. schedule (Schedule): Schedule information. params (Optional[List[Union[float, Parameter]]]): A list of parameters. Raises: Exception: if the gate is of type string and params is None. """ def _format(operand): try: # Using float/complex value as a dict key is not good idea. # This makes the mapping quite sensitive to the rounding error. # However, the mechanism is already tied to the execution model (i.e. pulse gate) # and we cannot easily update this rule. # The same logic exists in DAGCircuit.add_calibration. evaluated = complex(operand) if np.isreal(evaluated): evaluated = float(evaluated.real) if evaluated.is_integer(): evaluated = int(evaluated) return evaluated except TypeError: # Unassigned parameter return operand if isinstance(gate, Gate): params = gate.params gate = gate.name if params is not None: params = tuple(map(_format, params)) else: params = () self._calibrations[gate][(tuple(qubits), params)] = schedule # Functions only for scheduled circuits def qubit_duration(self, *qubits: Union[Qubit, int]) -> float: """Return the duration between the start and stop time of the first and last instructions, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Args: *qubits: Qubits within ``self`` to include. Returns: Return the duration between the first start and last stop time of non-delay instructions """ return self.qubit_stop_time(*qubits) - self.qubit_start_time(*qubits) def qubit_start_time(self, *qubits: Union[Qubit, int]) -> float: """Return the start time of the first instruction, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Return 0 if there are no instructions over qubits Args: *qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating indices of ``self.qubits``. Returns: Return the start time of the first instruction, excluding delays, over the qubits Raises: CircuitError: if ``self`` is a not-yet scheduled circuit. """ if self.duration is None: # circuit has only delays, this is kind of scheduled for instruction in self._data: if not isinstance(instruction.operation, Delay): raise CircuitError( "qubit_start_time undefined. Circuit must be scheduled first." ) return 0 qubits = [self.qubits[q] if isinstance(q, int) else q for q in qubits] starts = {q: 0 for q in qubits} dones = {q: False for q in qubits} for instruction in self._data: for q in qubits: if q in instruction.qubits: if isinstance(instruction.operation, Delay): if not dones[q]: starts[q] += instruction.operation.duration else: dones[q] = True if len(qubits) == len([done for done in dones.values() if done]): # all done return min(start for start in starts.values()) return 0 # If there are no instructions over bits def qubit_stop_time(self, *qubits: Union[Qubit, int]) -> float: """Return the stop time of the last instruction, excluding delays, over the supplied qubits. Its time unit is ``self.unit``. Return 0 if there are no instructions over qubits Args: *qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating indices of ``self.qubits``. Returns: Return the stop time of the last instruction, excluding delays, over the qubits Raises: CircuitError: if ``self`` is a not-yet scheduled circuit. """ if self.duration is None: # circuit has only delays, this is kind of scheduled for instruction in self._data: if not isinstance(instruction.operation, Delay): raise CircuitError( "qubit_stop_time undefined. Circuit must be scheduled first." ) return 0 qubits = [self.qubits[q] if isinstance(q, int) else q for q in qubits] stops = {q: self.duration for q in qubits} dones = {q: False for q in qubits} for instruction in reversed(self._data): for q in qubits: if q in instruction.qubits: if isinstance(instruction.operation, Delay): if not dones[q]: stops[q] -= instruction.operation.duration else: dones[q] = True if len(qubits) == len([done for done in dones.values() if done]): # all done return max(stop for stop in stops.values()) return 0 # If there are no instructions over bits class _ParameterBindsDict: __slots__ = ("mapping", "allowed_keys") def __init__(self, mapping, allowed_keys): self.mapping = mapping self.allowed_keys = allowed_keys def items(self): """Iterator through all the keys in the mapping that we care about. Wrapping the main mapping allows us to avoid reconstructing a new 'dict', but just use the given 'mapping' without any copy / reconstruction.""" for parameter, value in self.mapping.items(): if parameter in self.allowed_keys: yield parameter, value class _ParameterBindsSequence: __slots__ = ("parameters", "values", "mapping_cache") def __init__(self, parameters, values): self.parameters = parameters self.values = values self.mapping_cache = None def items(self): """Iterator through all the keys in the mapping that we care about.""" return zip(self.parameters, self.values) @property def mapping(self): """Cached version of a mapping. This is only generated on demand.""" if self.mapping_cache is None: self.mapping_cache = dict(zip(self.parameters, self.values)) return self.mapping_cache # Used by the OQ2 exporter. Just needs to have enough parameters to support the largest standard # (non-controlled) gate in our standard library. We have to use the same `Parameter` instances each # time so the equality comparisons will work. _QASM2_FIXED_PARAMETERS = [Parameter("param0"), Parameter("param1"), Parameter("param2")] def _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, bit_labels ): operation = _qasm2_define_custom_operation( instruction.operation, existing_gate_names, gates_to_define ) # Insert qasm representation of the original instruction if instruction.clbits: bits = itertools.chain(instruction.qubits, instruction.clbits) else: bits = instruction.qubits bits_qasm = ",".join(bit_labels[j] for j in bits) instruction_qasm = f"{_instruction_qasm2(operation)} {bits_qasm};" return instruction_qasm def _qasm2_define_custom_operation(operation, existing_gate_names, gates_to_define): """Extract a custom definition from the given operation, and append any necessary additional subcomponents' definitions to the ``gates_to_define`` ordered dictionary. Returns a potentially new :class:`.Instruction`, which should be used for the :meth:`~.Instruction.qasm` call (it may have been renamed).""" # pylint: disable=cyclic-import from qiskit.circuit import library as lib from qiskit.qasm2 import QASM2ExportError if operation.name in existing_gate_names: return operation # Check instructions names or label are valid escaped = _qasm_escape_name(operation.name, "gate_") if escaped != operation.name: operation = operation.copy(name=escaped) # These are built-in gates that are known to be safe to construct by passing the correct number # of `Parameter` instances positionally, and have no other information. We can't guarantee that # if they've been subclassed, though. This is a total hack; ideally we'd be able to inspect the # "calling" signatures of Qiskit `Gate` objects to know whether they're safe to re-parameterise. known_good_parameterized = { lib.PhaseGate, lib.RGate, lib.RXGate, lib.RXXGate, lib.RYGate, lib.RYYGate, lib.RZGate, lib.RZXGate, lib.RZZGate, lib.XXMinusYYGate, lib.XXPlusYYGate, lib.UGate, lib.U1Gate, lib.U2Gate, lib.U3Gate, } # In known-good situations we want to use a manually parametrised object as the source of the # definition, but still continue to return the given object as the call-site object. if type(operation) in known_good_parameterized: parameterized_operation = type(operation)(*_QASM2_FIXED_PARAMETERS[: len(operation.params)]) elif hasattr(operation, "_qasm2_decomposition"): new_op = operation._qasm2_decomposition() parameterized_operation = operation = new_op.copy( name=_qasm_escape_name(new_op.name, "gate_") ) else: parameterized_operation = operation # If there's an _equal_ operation in the existing circuits to be defined, then our job is done. previous_definition_source, _ = gates_to_define.get(operation.name, (None, None)) if parameterized_operation == previous_definition_source: return operation # Otherwise, if there's a naming clash, we need a unique name. if operation.name in gates_to_define: operation = _rename_operation(operation) new_name = operation.name if parameterized_operation.params: parameters_qasm = ( "(" + ",".join(f"param{i}" for i in range(len(parameterized_operation.params))) + ")" ) else: parameters_qasm = "" if operation.num_qubits == 0: raise QASM2ExportError( f"OpenQASM 2 cannot represent '{operation.name}, which acts on zero qubits." ) if operation.num_clbits != 0: raise QASM2ExportError( f"OpenQASM 2 cannot represent '{operation.name}', which acts on {operation.num_clbits}" " classical bits." ) qubits_qasm = ",".join(f"q{i}" for i in range(parameterized_operation.num_qubits)) parameterized_definition = getattr(parameterized_operation, "definition", None) if parameterized_definition is None: gates_to_define[new_name] = ( parameterized_operation, f"opaque {new_name}{parameters_qasm} {qubits_qasm};", ) else: qubit_labels = {bit: f"q{i}" for i, bit in enumerate(parameterized_definition.qubits)} body_qasm = " ".join( _qasm2_custom_operation_statement( instruction, existing_gate_names, gates_to_define, qubit_labels ) for instruction in parameterized_definition.data ) # if an inner operation has the same name as the actual operation, it needs to be renamed if operation.name in gates_to_define: operation = _rename_operation(operation) new_name = operation.name definition_qasm = f"gate {new_name}{parameters_qasm} {qubits_qasm} {{ {body_qasm} }}" gates_to_define[new_name] = (parameterized_operation, definition_qasm) return operation def _rename_operation(operation): """Returns the operation with a new name following this pattern: {operation name}_{operation id}""" new_name = f"{operation.name}_{id(operation)}" updated_operation = operation.copy(name=new_name) return updated_operation def _qasm_escape_name(name: str, prefix: str) -> str: """Returns a valid OpenQASM identifier, using `prefix` as a prefix if necessary. `prefix` must itself be a valid identifier.""" # Replace all non-ASCII-word characters (letters, digits, underscore) with the underscore. escaped_name = re.sub(r"\W", "_", name, flags=re.ASCII) if ( not escaped_name or escaped_name[0] not in string.ascii_lowercase or escaped_name in QASM2_RESERVED ): escaped_name = prefix + escaped_name return escaped_name def _instruction_qasm2(operation): """Return an OpenQASM 2 string for the instruction.""" from qiskit.qasm2 import QASM2ExportError # pylint: disable=cyclic-import if operation.name == "c3sx": qasm2_call = "c3sqrtx" else: qasm2_call = operation.name if operation.params: qasm2_call = "{}({})".format( qasm2_call, ",".join([pi_check(i, output="qasm", eps=1e-12) for i in operation.params]), ) if operation.condition is not None: if not isinstance(operation.condition[0], ClassicalRegister): raise QASM2ExportError( "OpenQASM 2 can only condition on registers, but got '{operation.condition[0]}'" ) qasm2_call = ( "if(%s==%d) " % (operation.condition[0].name, operation.condition[1]) + qasm2_call ) return qasm2_call def _make_unique(name: str, already_defined: collections.abc.Set[str]) -> str: """Generate a name by suffixing the given stem that is unique within the defined set.""" if name not in already_defined: return name used = {in_use[len(name) :] for in_use in already_defined if in_use.startswith(name)} characters = (string.digits + string.ascii_letters) if name else string.ascii_letters for parts in itertools.chain.from_iterable( itertools.product(characters, repeat=n) for n in itertools.count(1) ): suffix = "".join(parts) if suffix not in used: return name + suffix # This isn't actually reachable because the above loop is infinite. return name def _bit_argument_conversion(specifier, bit_sequence, bit_set, type_) -> list[Bit]: """Get the list of bits referred to by the specifier ``specifier``. Valid types for ``specifier`` are integers, bits of the correct type (as given in ``type_``), or iterables of one of those two scalar types. Integers are interpreted as indices into the sequence ``bit_sequence``. All allowed bits must be in ``bit_set`` (which should implement fast lookup), which is assumed to contain the same bits as ``bit_sequence``. Returns: List[Bit]: a list of the specified bits from ``bits``. Raises: CircuitError: if an incorrect type or index is encountered, if the same bit is specified more than once, or if the specifier is to a bit not in the ``bit_set``. """ # The duplication between this function and `_bit_argument_conversion_scalar` is so that fast # paths return as quickly as possible, and all valid specifiers will resolve without needing to # try/catch exceptions (which is too slow for inner-loop code). if isinstance(specifier, type_): if specifier in bit_set: return [specifier] raise CircuitError(f"Bit '{specifier}' is not in the circuit.") if isinstance(specifier, (int, np.integer)): try: return [bit_sequence[specifier]] except IndexError as ex: raise CircuitError( f"Index {specifier} out of range for size {len(bit_sequence)}." ) from ex # Slices can't raise IndexError - they just return an empty list. if isinstance(specifier, slice): return bit_sequence[specifier] try: return [ _bit_argument_conversion_scalar(index, bit_sequence, bit_set, type_) for index in specifier ] except TypeError as ex: message = ( f"Incorrect bit type: expected '{type_.__name__}' but got '{type(specifier).__name__}'" if isinstance(specifier, Bit) else f"Invalid bit index: '{specifier}' of type '{type(specifier)}'" ) raise CircuitError(message) from ex def _bit_argument_conversion_scalar(specifier, bit_sequence, bit_set, type_): if isinstance(specifier, type_): if specifier in bit_set: return specifier raise CircuitError(f"Bit '{specifier}' is not in the circuit.") if isinstance(specifier, (int, np.integer)): try: return bit_sequence[specifier] except IndexError as ex: raise CircuitError( f"Index {specifier} out of range for size {len(bit_sequence)}." ) from ex message = ( f"Incorrect bit type: expected '{type_.__name__}' but got '{type(specifier).__name__}'" if isinstance(specifier, Bit) else f"Invalid bit index: '{specifier}' of type '{type(specifier)}'" ) raise CircuitError(message)
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. """Tests for Statevector quantum state class.""" import unittest import logging from itertools import permutations from ddt import ddt, data import numpy as np from numpy.testing import assert_allclose from qiskit.test import QiskitTestCase from qiskit import QiskitError from qiskit import QuantumRegister, QuantumCircuit from qiskit import transpile from qiskit.circuit.library import HGate, QFT, GlobalPhaseGate from qiskit.providers.basicaer import QasmSimulatorPy from qiskit.utils import optionals from qiskit.quantum_info.random import random_unitary, random_statevector, random_pauli from qiskit.quantum_info.states import Statevector from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic import Pauli, SparsePauliOp from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.visualization.state_visualization import numbers_to_latex_terms, state_to_latex logger = logging.getLogger(__name__) @ddt class TestStatevector(QiskitTestCase): """Tests for Statevector class.""" @classmethod def rand_vec(cls, n, normalize=False): """Return complex vector or statevector""" seed = np.random.randint(0, np.iinfo(np.int32).max) logger.debug("rand_vec default_rng seeded with seed=%s", seed) rng = np.random.default_rng(seed) vec = rng.random(n) + 1j * rng.random(n) if normalize: vec /= np.sqrt(np.dot(vec, np.conj(vec))) return vec def test_init_array_qubit(self): """Test subsystem initialization from N-qubit array.""" # Test automatic inference of qubit subsystems vec = self.rand_vec(8) for dims in [None, 8]: state = Statevector(vec, dims=dims) assert_allclose(state.data, vec) self.assertEqual(state.dim, 8) self.assertEqual(state.dims(), (2, 2, 2)) self.assertEqual(state.num_qubits, 3) def test_init_array(self): """Test initialization from array.""" vec = self.rand_vec(3) state = Statevector(vec) assert_allclose(state.data, vec) self.assertEqual(state.dim, 3) self.assertEqual(state.dims(), (3,)) self.assertIsNone(state.num_qubits) vec = self.rand_vec(2 * 3 * 4) state = Statevector(vec, dims=[2, 3, 4]) assert_allclose(state.data, vec) self.assertEqual(state.dim, 2 * 3 * 4) self.assertEqual(state.dims(), (2, 3, 4)) self.assertIsNone(state.num_qubits) def test_init_circuit(self): """Test initialization from circuit.""" circuit = QuantumCircuit(3) circuit.x(0) state = Statevector(circuit) self.assertEqual(state.dim, 8) self.assertEqual(state.dims(), (2, 2, 2)) self.assertTrue(all(state.data == np.array([0, 1, 0, 0, 0, 0, 0, 0], dtype=complex))) self.assertEqual(state.num_qubits, 3) def test_init_array_except(self): """Test initialization exception from array.""" vec = self.rand_vec(4) self.assertRaises(QiskitError, Statevector, vec, dims=[4, 2]) self.assertRaises(QiskitError, Statevector, vec, dims=[2, 4]) self.assertRaises(QiskitError, Statevector, vec, dims=5) def test_init_statevector(self): """Test initialization from Statevector.""" vec1 = Statevector(self.rand_vec(4)) vec2 = Statevector(vec1) self.assertEqual(vec1, vec2) def test_from_circuit(self): """Test initialization from a circuit.""" # random unitaries u0 = random_unitary(2).data u1 = random_unitary(2).data # add to circuit qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.unitary(u0, [qr[0]]) circ.unitary(u1, [qr[1]]) target = Statevector(np.kron(u1, u0).dot([1, 0, 0, 0])) vec = Statevector.from_instruction(circ) self.assertEqual(vec, target) # Test tensor product of 1-qubit gates circuit = QuantumCircuit(3) circuit.h(0) circuit.x(1) circuit.ry(np.pi / 2, 2) target = Statevector.from_label("000").evolve(Operator(circuit)) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test decomposition of Controlled-Phase gate lam = np.pi / 4 circuit = QuantumCircuit(2) circuit.h(0) circuit.h(1) circuit.cp(lam, 0, 1) target = Statevector.from_label("00").evolve(Operator(circuit)) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test decomposition of controlled-H gate circuit = QuantumCircuit(2) circ.x(0) circuit.ch(0, 1) target = Statevector.from_label("00").evolve(Operator(circuit)) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test custom controlled gate qc = QuantumCircuit(2) qc.x(0) qc.h(1) gate = qc.to_gate() gate_ctrl = gate.control() circuit = QuantumCircuit(3) circuit.x(0) circuit.append(gate_ctrl, range(3)) target = Statevector.from_label("000").evolve(Operator(circuit)) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test initialize instruction target = Statevector([1, 0, 0, 1j]) / np.sqrt(2) circuit = QuantumCircuit(2) circuit.initialize(target.data, [0, 1]) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) target = Statevector([1, 0, 1, 0]) / np.sqrt(2) circuit = QuantumCircuit(2) circuit.initialize("+", [1]) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) target = Statevector([1, 0, 0, 0]) circuit = QuantumCircuit(2) circuit.initialize(0, [0, 1]) # initialize from int psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test reset instruction target = Statevector([1, 0]) circuit = QuantumCircuit(1) circuit.h(0) circuit.reset(0) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) # Test 0q instruction target = Statevector([1j, 0]) circuit = QuantumCircuit(1) circuit.append(GlobalPhaseGate(np.pi / 2), [], []) psi = Statevector.from_instruction(circuit) self.assertEqual(psi, target) def test_from_instruction(self): """Test initialization from an instruction.""" target = np.dot(HGate().to_matrix(), [1, 0]) vec = Statevector.from_instruction(HGate()).data global_phase_equivalent = matrix_equal(vec, target, ignore_phase=True) self.assertTrue(global_phase_equivalent) def test_from_label(self): """Test initialization from a label""" x_p = Statevector(np.array([1, 1]) / np.sqrt(2)) x_m = Statevector(np.array([1, -1]) / np.sqrt(2)) y_p = Statevector(np.array([1, 1j]) / np.sqrt(2)) y_m = Statevector(np.array([1, -1j]) / np.sqrt(2)) z_p = Statevector(np.array([1, 0])) z_m = Statevector(np.array([0, 1])) label = "01" target = z_p.tensor(z_m) self.assertEqual(target, Statevector.from_label(label)) label = "+-" target = x_p.tensor(x_m) self.assertEqual(target, Statevector.from_label(label)) label = "rl" target = y_p.tensor(y_m) self.assertEqual(target, Statevector.from_label(label)) def test_equal(self): """Test __eq__ method""" for _ in range(10): vec = self.rand_vec(4) self.assertEqual(Statevector(vec), Statevector(vec.tolist())) def test_getitem(self): """Test __getitem__ method""" for _ in range(10): vec = self.rand_vec(4) state = Statevector(vec) for i in range(4): self.assertEqual(state[i], vec[i]) self.assertEqual(state[format(i, "b")], vec[i]) def test_getitem_except(self): """Test __getitem__ method raises exceptions.""" for i in range(1, 4): state = Statevector(self.rand_vec(2**i)) self.assertRaises(QiskitError, state.__getitem__, 2**i) self.assertRaises(QiskitError, state.__getitem__, -1) def test_copy(self): """Test Statevector copy method""" for _ in range(5): vec = self.rand_vec(4) orig = Statevector(vec) cpy = orig.copy() cpy._data[0] += 1.0 self.assertFalse(cpy == orig) def test_is_valid(self): """Test is_valid method.""" state = Statevector([1, 1]) self.assertFalse(state.is_valid()) for _ in range(10): state = Statevector(self.rand_vec(4, normalize=True)) self.assertTrue(state.is_valid()) def test_to_operator(self): """Test to_operator method for returning projector.""" for _ in range(10): vec = self.rand_vec(4) target = Operator(np.outer(vec, np.conj(vec))) op = Statevector(vec).to_operator() self.assertEqual(op, target) def test_evolve(self): """Test _evolve method.""" for _ in range(10): op = random_unitary(4) vec = self.rand_vec(4) target = Statevector(np.dot(op.data, vec)) evolved = Statevector(vec).evolve(op) self.assertEqual(target, evolved) def test_evolve_subsystem(self): """Test subsystem _evolve method.""" # Test evolving single-qubit of 3-qubit system for _ in range(5): vec = self.rand_vec(8) state = Statevector(vec) op0 = random_unitary(2) op1 = random_unitary(2) op2 = random_unitary(2) # Test evolve on 1-qubit op = op0 op_full = Operator(np.eye(4)).tensor(op) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[0]), target) # Evolve on qubit 1 op_full = Operator(np.eye(2)).tensor(op).tensor(np.eye(2)) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[1]), target) # Evolve on qubit 2 op_full = op.tensor(np.eye(4)) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[2]), target) # Test evolve on 2-qubits op = op1.tensor(op0) # Evolve on qubits [0, 2] op_full = op1.tensor(np.eye(2)).tensor(op0) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[0, 2]), target) # Evolve on qubits [2, 0] op_full = op0.tensor(np.eye(2)).tensor(op1) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[2, 0]), target) # Test evolve on 3-qubits op = op2.tensor(op1).tensor(op0) # Evolve on qubits [0, 1, 2] op_full = op target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[0, 1, 2]), target) # Evolve on qubits [2, 1, 0] op_full = op0.tensor(op1).tensor(op2) target = Statevector(np.dot(op_full.data, vec)) self.assertEqual(state.evolve(op, qargs=[2, 1, 0]), target) def test_evolve_qudit_subsystems(self): """Test nested evolve calls on qudit subsystems.""" dims = (3, 4, 5) init = self.rand_vec(np.prod(dims)) ops = [random_unitary((dim,)) for dim in dims] state = Statevector(init, dims) for i, op in enumerate(ops): state = state.evolve(op, [i]) target_op = np.eye(1) for op in ops: target_op = np.kron(op.data, target_op) target = Statevector(np.dot(target_op, init), dims) self.assertEqual(state, target) def test_evolve_global_phase(self): """Test evolve circuit with global phase.""" state_i = Statevector([1, 0]) qr = QuantumRegister(2) phase = np.pi / 4 circ = QuantumCircuit(qr, global_phase=phase) circ.x(0) state_f = state_i.evolve(circ, qargs=[0]) target = Statevector([0, 1]) * np.exp(1j * phase) self.assertEqual(state_f, target) def test_conjugate(self): """Test conjugate method.""" for _ in range(10): vec = self.rand_vec(4) target = Statevector(np.conj(vec)) state = Statevector(vec).conjugate() self.assertEqual(state, target) def test_expand(self): """Test expand method.""" for _ in range(10): vec0 = self.rand_vec(2) vec1 = self.rand_vec(3) target = np.kron(vec1, vec0) state = Statevector(vec0).expand(Statevector(vec1)) self.assertEqual(state.dim, 6) self.assertEqual(state.dims(), (2, 3)) assert_allclose(state.data, target) def test_tensor(self): """Test tensor method.""" for _ in range(10): vec0 = self.rand_vec(2) vec1 = self.rand_vec(3) target = np.kron(vec0, vec1) state = Statevector(vec0).tensor(Statevector(vec1)) self.assertEqual(state.dim, 6) self.assertEqual(state.dims(), (3, 2)) assert_allclose(state.data, target) def test_inner(self): """Test inner method.""" for _ in range(10): vec0 = Statevector(self.rand_vec(4)) vec1 = Statevector(self.rand_vec(4)) target = np.vdot(vec0.data, vec1.data) result = vec0.inner(vec1) self.assertAlmostEqual(result, target) vec0 = Statevector(self.rand_vec(6), dims=(2, 3)) vec1 = Statevector(self.rand_vec(6), dims=(2, 3)) target = np.vdot(vec0.data, vec1.data) result = vec0.inner(vec1) self.assertAlmostEqual(result, target) def test_inner_except(self): """Test inner method raises exceptions.""" vec0 = Statevector(self.rand_vec(4)) vec1 = Statevector(self.rand_vec(3)) self.assertRaises(QiskitError, vec0.inner, vec1) vec0 = Statevector(self.rand_vec(6), dims=(2, 3)) vec1 = Statevector(self.rand_vec(6), dims=(3, 2)) self.assertRaises(QiskitError, vec0.inner, vec1) def test_add(self): """Test add method.""" for _ in range(10): vec0 = self.rand_vec(4) vec1 = self.rand_vec(4) state0 = Statevector(vec0) state1 = Statevector(vec1) self.assertEqual(state0 + state1, Statevector(vec0 + vec1)) def test_add_except(self): """Test add method raises exceptions.""" state1 = Statevector(self.rand_vec(2)) state2 = Statevector(self.rand_vec(3)) self.assertRaises(QiskitError, state1.__add__, state2) def test_subtract(self): """Test subtract method.""" for _ in range(10): vec0 = self.rand_vec(4) vec1 = self.rand_vec(4) state0 = Statevector(vec0) state1 = Statevector(vec1) self.assertEqual(state0 - state1, Statevector(vec0 - vec1)) def test_multiply(self): """Test multiply method.""" for _ in range(10): vec = self.rand_vec(4) state = Statevector(vec) val = np.random.rand() + 1j * np.random.rand() self.assertEqual(val * state, Statevector(val * state)) def test_negate(self): """Test negate method""" for _ in range(10): vec = self.rand_vec(4) state = Statevector(vec) self.assertEqual(-state, Statevector(-1 * vec)) def test_equiv(self): """Test equiv method""" vec = np.array([1, 0, 0, -1j]) / np.sqrt(2) phase = np.exp(-1j * np.pi / 4) statevec = Statevector(vec) self.assertTrue(statevec.equiv(phase * vec)) self.assertTrue(statevec.equiv(Statevector(phase * vec))) self.assertFalse(statevec.equiv(2 * vec)) def test_equiv_on_circuit(self): """Test the equiv method on different types of input.""" statevec = Statevector([1, 0]) qc = QuantumCircuit(1) self.assertTrue(statevec.equiv(qc)) qc.x(0) self.assertFalse(statevec.equiv(qc)) def test_to_dict(self): """Test to_dict method""" with self.subTest(msg="dims = (2, 3)"): vec = Statevector(np.arange(1, 7), dims=(2, 3)) target = {"00": 1, "01": 2, "10": 3, "11": 4, "20": 5, "21": 6} self.assertDictAlmostEqual(target, vec.to_dict()) with self.subTest(msg="dims = (11, )"): vec = Statevector(np.arange(1, 12), dims=(11,)) target = {str(i): i + 1 for i in range(11)} self.assertDictAlmostEqual(target, vec.to_dict()) with self.subTest(msg="dims = (2, 11)"): vec = Statevector(np.arange(1, 23), dims=(2, 11)) target = {} for i in range(11): for j in range(2): key = f"{i},{j}" target[key] = 2 * i + j + 1 self.assertDictAlmostEqual(target, vec.to_dict()) def test_probabilities_product(self): """Test probabilities method for product state""" state = Statevector.from_label("+0") # 2-qubit qargs with self.subTest(msg="P(None)"): probs = state.probabilities() target = np.array([0.5, 0, 0.5, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([0, 1])"): probs = state.probabilities([0, 1]) target = np.array([0.5, 0, 0.5, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([1, 0]"): probs = state.probabilities([1, 0]) target = np.array([0.5, 0.5, 0, 0]) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs with self.subTest(msg="P([0])"): probs = state.probabilities([0]) target = np.array([1, 0]) self.assertTrue(np.allclose(probs, target)) with self.subTest(msg="P([1])"): probs = state.probabilities([1]) target = np.array([0.5, 0.5]) self.assertTrue(np.allclose(probs, target)) def test_probabilities_ghz(self): """Test probabilities method for GHZ state""" state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) # 3-qubit qargs target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5]) for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 2-qubit qargs target = np.array([0.5, 0, 0, 0.5]) for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs target = np.array([0.5, 0.5]) for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) def test_probabilities_w(self): """Test probabilities method with W state""" state = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) # 3-qubit qargs target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0]) for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 2-qubit qargs target = np.array([1 / 3, 1 / 3, 1 / 3, 0]) for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) # 1-qubit qargs target = np.array([2 / 3, 1 / 3]) for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities(qargs) self.assertTrue(np.allclose(probs, target)) def test_probabilities_dict_product(self): """Test probabilities_dict method for product state""" state = Statevector.from_label("+0") # 2-qubit qargs with self.subTest(msg="P(None)"): probs = state.probabilities_dict() target = {"00": 0.5, "10": 0.5} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([0, 1])"): probs = state.probabilities_dict([0, 1]) target = {"00": 0.5, "10": 0.5} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([1, 0]"): probs = state.probabilities_dict([1, 0]) target = {"00": 0.5, "01": 0.5} self.assertDictAlmostEqual(probs, target) # 1-qubit qargs with self.subTest(msg="P([0])"): probs = state.probabilities_dict([0]) target = {"0": 1} self.assertDictAlmostEqual(probs, target) with self.subTest(msg="P([1])"): probs = state.probabilities_dict([1]) target = {"0": 0.5, "1": 0.5} self.assertDictAlmostEqual(probs, target) def test_probabilities_dict_ghz(self): """Test probabilities_dict method for GHZ state""" state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) # 3-qubit qargs target = {"000": 0.5, "111": 0.5} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 2-qubit qargs target = {"00": 0.5, "11": 0.5} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 1-qubit qargs target = {"0": 0.5, "1": 0.5} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) def test_probabilities_dict_w(self): """Test probabilities_dict method with W state""" state = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) # 3-qubit qargs target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0]) target = {"001": 1 / 3, "010": 1 / 3, "100": 1 / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 2-qubit qargs target = {"00": 1 / 3, "01": 1 / 3, "10": 1 / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) # 1-qubit qargs target = {"0": 2 / 3, "1": 1 / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): probs = state.probabilities_dict(qargs) self.assertDictAlmostEqual(probs, target) def test_sample_counts_ghz(self): """Test sample_counts method for GHZ state""" shots = 2000 threshold = 0.02 * shots state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) state.seed(100) # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"counts (qargs={qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) def test_sample_counts_w(self): """Test sample_counts method for W state""" shots = 3000 threshold = 0.02 * shots state = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) state.seed(100) target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"P({qargs})"): counts = state.sample_counts(shots, qargs=qargs) self.assertDictAlmostEqual(counts, target, threshold) def test_probabilities_dict_unequal_dims(self): """Test probabilities_dict for a state with unequal subsystem dimensions.""" vec = np.zeros(60, dtype=float) vec[15:20] = np.ones(5) vec[40:46] = np.ones(6) state = Statevector(vec / np.sqrt(11.0), dims=[3, 4, 5]) p = 1.0 / 11.0 self.assertDictEqual( state.probabilities_dict(), { s: p for s in [ "110", "111", "112", "120", "121", "311", "312", "320", "321", "322", "330", ] }, ) # differences due to rounding self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0]), {"0": 4 * p, "1": 4 * p, "2": 3 * p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[1]), {"1": 5 * p, "2": 5 * p, "3": p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[2]), {"1": 5 * p, "3": 6 * p}, delta=1e-10 ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0, 1]), {"10": p, "11": 2 * p, "12": 2 * p, "20": 2 * p, "21": 2 * p, "22": p, "30": p}, delta=1e-10, ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[1, 0]), {"01": p, "11": 2 * p, "21": 2 * p, "02": 2 * p, "12": 2 * p, "22": p, "03": p}, delta=1e-10, ) self.assertDictAlmostEqual( state.probabilities_dict(qargs=[0, 2]), {"10": 2 * p, "11": 2 * p, "12": p, "31": 2 * p, "32": 2 * p, "30": 2 * p}, delta=1e-10, ) def test_sample_counts_qutrit(self): """Test sample_counts method for qutrit state""" p = 0.3 shots = 1000 threshold = 0.03 * shots state = Statevector([np.sqrt(p), 0, np.sqrt(1 - p)]) state.seed(100) with self.subTest(msg="counts"): target = {"0": shots * p, "2": shots * (1 - p)} counts = state.sample_counts(shots=shots) self.assertDictAlmostEqual(counts, target, threshold) def test_sample_memory_ghz(self): """Test sample_memory method for GHZ state""" shots = 2000 state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2) state.seed(100) # 3-qubit qargs target = {"000": shots / 2, "111": shots / 2} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = {"00": shots / 2, "11": shots / 2} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": shots / 2, "1": shots / 2} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) def test_sample_memory_w(self): """Test sample_memory method for W state""" shots = 3000 state = ( Statevector.from_label("001") + Statevector.from_label("010") + Statevector.from_label("100") ) / np.sqrt(3) state.seed(100) target = {"001": shots / 3, "010": shots / 3, "100": shots / 3} for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 2-qubit qargs target = {"00": shots / 3, "01": shots / 3, "10": shots / 3} for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) # 1-qubit qargs target = {"0": 2 * shots / 3, "1": shots / 3} for qargs in [[0], [1], [2]]: with self.subTest(msg=f"memory (qargs={qargs})"): memory = state.sample_memory(shots, qargs=qargs) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), set(target)) def test_sample_memory_qutrit(self): """Test sample_memory method for qutrit state""" p = 0.3 shots = 1000 state = Statevector([np.sqrt(p), 0, np.sqrt(1 - p)]) state.seed(100) with self.subTest(msg="memory"): memory = state.sample_memory(shots) self.assertEqual(len(memory), shots) self.assertEqual(set(memory), {"0", "2"}) def test_reset_2qubit(self): """Test reset method for 2-qubit state""" state = Statevector(np.array([1, 0, 0, 1]) / np.sqrt(2)) state.seed(100) with self.subTest(msg="reset"): psi = state.copy() value = psi.reset() target = Statevector(np.array([1, 0, 0, 0])) self.assertEqual(value, target) with self.subTest(msg="reset"): psi = state.copy() value = psi.reset([0, 1]) target = Statevector(np.array([1, 0, 0, 0])) self.assertEqual(value, target) with self.subTest(msg="reset [0]"): psi = state.copy() value = psi.reset([0]) targets = [Statevector(np.array([1, 0, 0, 0])), Statevector(np.array([0, 0, 1, 0]))] self.assertIn(value, targets) with self.subTest(msg="reset [0]"): psi = state.copy() value = psi.reset([1]) targets = [Statevector(np.array([1, 0, 0, 0])), Statevector(np.array([0, 1, 0, 0]))] self.assertIn(value, targets) def test_reset_qutrit(self): """Test reset method for qutrit""" state = Statevector(np.array([1, 1, 1]) / np.sqrt(3)) state.seed(200) value = state.reset() target = Statevector(np.array([1, 0, 0])) self.assertEqual(value, target) def test_measure_2qubit(self): """Test measure method for 2-qubit state""" state = Statevector.from_label("+0") seed = 200 shots = 100 with self.subTest(msg="measure"): for i in range(shots): psi = state.copy() psi.seed(seed + i) outcome, value = psi.measure() self.assertIn(outcome, ["00", "10"]) if outcome == "00": target = Statevector.from_label("00") self.assertEqual(value, target) else: target = Statevector.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [0, 1]"): for i in range(shots): psi = state.copy() outcome, value = psi.measure([0, 1]) self.assertIn(outcome, ["00", "10"]) if outcome == "00": target = Statevector.from_label("00") self.assertEqual(value, target) else: target = Statevector.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [1, 0]"): for i in range(shots): psi = state.copy() outcome, value = psi.measure([1, 0]) self.assertIn(outcome, ["00", "01"]) if outcome == "00": target = Statevector.from_label("00") self.assertEqual(value, target) else: target = Statevector.from_label("10") self.assertEqual(value, target) with self.subTest(msg="measure [0]"): for i in range(shots): psi = state.copy() outcome, value = psi.measure([0]) self.assertEqual(outcome, "0") target = Statevector(np.array([1, 0, 1, 0]) / np.sqrt(2)) self.assertEqual(value, target) with self.subTest(msg="measure [1]"): for i in range(shots): psi = state.copy() outcome, value = psi.measure([1]) self.assertIn(outcome, ["0", "1"]) if outcome == "0": target = Statevector.from_label("00") self.assertEqual(value, target) else: target = Statevector.from_label("10") self.assertEqual(value, target) def test_measure_qutrit(self): """Test measure method for qutrit""" state = Statevector(np.array([1, 1, 1]) / np.sqrt(3)) seed = 200 shots = 100 for i in range(shots): psi = state.copy() psi.seed(seed + i) outcome, value = psi.measure() self.assertIn(outcome, ["0", "1", "2"]) if outcome == "0": target = Statevector([1, 0, 0]) self.assertEqual(value, target) elif outcome == "1": target = Statevector([0, 1, 0]) self.assertEqual(value, target) else: target = Statevector([0, 0, 1]) self.assertEqual(value, target) def test_from_int(self): """Test from_int method""" with self.subTest(msg="from_int(0, 4)"): target = Statevector([1, 0, 0, 0]) value = Statevector.from_int(0, 4) self.assertEqual(target, value) with self.subTest(msg="from_int(3, 4)"): target = Statevector([0, 0, 0, 1]) value = Statevector.from_int(3, 4) self.assertEqual(target, value) with self.subTest(msg="from_int(8, (3, 3))"): target = Statevector([0, 0, 0, 0, 0, 0, 0, 0, 1], dims=(3, 3)) value = Statevector.from_int(8, (3, 3)) self.assertEqual(target, value) def test_expval(self): """Test expectation_value method""" psi = Statevector([1, 0, 0, 1]) / np.sqrt(2) for label, target in [ ("II", 1), ("XX", 1), ("YY", -1), ("ZZ", 1), ("IX", 0), ("YZ", 0), ("ZX", 0), ("YI", 0), ]: with self.subTest(msg=f"<{label}>"): op = Pauli(label) expval = psi.expectation_value(op) self.assertAlmostEqual(expval, target) psi = Statevector([np.sqrt(2), 0, 0, 0, 0, 0, 0, 1 + 1j]) / 2 for label, target in [ ("XXX", np.sqrt(2) / 2), ("YYY", -np.sqrt(2) / 2), ("ZZZ", 0), ("XYZ", 0), ("YIY", 0), ]: with self.subTest(msg=f"<{label}>"): op = Pauli(label) expval = psi.expectation_value(op) self.assertAlmostEqual(expval, target) labels = ["XXX", "IXI", "YYY", "III"] coeffs = [3.0, 5.5, -1j, 23] spp_op = SparsePauliOp.from_list(list(zip(labels, coeffs))) expval = psi.expectation_value(spp_op) target = 25.121320343559642 + 0.7071067811865476j self.assertAlmostEqual(expval, target) @data( "II", "IX", "IY", "IZ", "XI", "XX", "XY", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "ZZ", "-II", "-IX", "-IY", "-IZ", "-XI", "-XX", "-XY", "-XZ", "-YI", "-YX", "-YY", "-YZ", "-ZI", "-ZX", "-ZY", "-ZZ", "iII", "iIX", "iIY", "iIZ", "iXI", "iXX", "iXY", "iXZ", "iYI", "iYX", "iYY", "iYZ", "iZI", "iZX", "iZY", "iZZ", "-iII", "-iIX", "-iIY", "-iIZ", "-iXI", "-iXX", "-iXY", "-iXZ", "-iYI", "-iYX", "-iYY", "-iYZ", "-iZI", "-iZX", "-iZY", "-iZZ", ) def test_expval_pauli(self, pauli): """Test expectation_value method for Pauli op""" seed = 1020 op = Pauli(pauli) state = random_statevector(2**op.num_qubits, seed=seed) target = state.expectation_value(op.to_matrix()) expval = state.expectation_value(op) self.assertAlmostEqual(expval, target) @data([0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]) def test_expval_pauli_qargs(self, qubits): """Test expectation_value method for Pauli op""" seed = 1020 op = random_pauli(2, seed=seed) state = random_statevector(2**3, seed=seed) target = state.expectation_value(op.to_matrix(), qubits) expval = state.expectation_value(op, qubits) self.assertAlmostEqual(expval, target) @data(*(qargs for i in range(4) for qargs in permutations(range(4), r=i + 1))) def test_probabilities_qargs(self, qargs): """Test probabilities method with qargs""" # Get initial state nq = 4 nc = len(qargs) state_circ = QuantumCircuit(nq, nc) for i in range(nq): state_circ.ry((i + 1) * np.pi / (nq + 1), i) # Get probabilities state = Statevector(state_circ) probs = state.probabilities(qargs) # Estimate target probs from simulator measurement sim = QasmSimulatorPy() shots = 5000 seed = 100 circ = transpile(state_circ, sim) circ.measure(qargs, range(nc)) result = sim.run(circ, shots=shots, seed_simulator=seed).result() target = np.zeros(2**nc, dtype=float) for i, p in result.get_counts(0).int_outcomes().items(): target[i] = p / shots # Compare delta = np.linalg.norm(probs - target) self.assertLess(delta, 0.05) def test_global_phase(self): """Test global phase is handled correctly when evolving statevector.""" qc = QuantumCircuit(1) qc.rz(0.5, 0) qc2 = transpile(qc, basis_gates=["p"]) sv = Statevector.from_instruction(qc2) expected = np.array([0.96891242 - 0.24740396j, 0]) self.assertEqual(float(qc2.global_phase), 2 * np.pi - 0.25) self.assertEqual(sv, Statevector(expected)) def test_reverse_qargs(self): """Test reverse_qargs method""" circ1 = QFT(5) circ2 = circ1.reverse_bits() state1 = Statevector.from_instruction(circ1) state2 = Statevector.from_instruction(circ2) self.assertEqual(state1.reverse_qargs(), state2) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "requires matplotlib") @unittest.skipUnless(optionals.HAS_PYLATEX, "requires pylatexenc") def test_drawings(self): """Test draw method""" qc1 = QFT(5) sv = Statevector.from_instruction(qc1) with self.subTest(msg="str(statevector)"): str(sv) for drawtype in ["repr", "text", "latex", "latex_source", "qsphere", "hinton", "bloch"]: with self.subTest(msg=f"draw('{drawtype}')"): sv.draw(drawtype) with self.subTest(msg=" draw('latex', convention='vector')"): sv.draw("latex", convention="vector") def test_state_to_latex_for_none(self): """ Test for `\rangleNone` output in latex representation See https://github.com/Qiskit/qiskit-terra/issues/8169 """ sv = Statevector( [ 7.07106781e-01 - 8.65956056e-17j, -5.55111512e-17 - 8.65956056e-17j, 7.85046229e-17 + 8.65956056e-17j, -7.07106781e-01 + 8.65956056e-17j, 0.00000000e00 + 0.00000000e00j, -0.00000000e00 + 0.00000000e00j, -0.00000000e00 + 0.00000000e00j, 0.00000000e00 - 0.00000000e00j, ], dims=(2, 2, 2), ) latex_representation = state_to_latex(sv) self.assertEqual( latex_representation, "\\frac{\\sqrt{2}}{2} |000\\rangle- \\frac{\\sqrt{2}}{2} |011\\rangle", ) def test_state_to_latex_for_large_statevector(self): """Test conversion of large dense state vector""" sv = Statevector(np.ones((2**15, 1))) latex_representation = state_to_latex(sv) self.assertEqual( latex_representation, " |000000000000000\\rangle+ |000000000000001\\rangle+ |000000000000010\\rangle+" " |000000000000011\\rangle+ |000000000000100\\rangle+ |000000000000101\\rangle +" " \\ldots + |111111111111011\\rangle+ |111111111111100\\rangle+" " |111111111111101\\rangle+ |111111111111110\\rangle+ |111111111111111\\rangle", ) def test_state_to_latex_with_prefix(self): """Test adding prefix to state vector latex output""" psi = Statevector(np.array([np.sqrt(1 / 2), 0, 0, np.sqrt(1 / 2)])) prefix = "|\\psi_{AB}\\rangle = " latex_sv = state_to_latex(psi) latex_expected = prefix + latex_sv latex_representation = state_to_latex(psi, prefix=prefix) self.assertEqual(latex_representation, latex_expected) def test_state_to_latex_for_large_sparse_statevector(self): """Test conversion of large sparse state vector""" sv = Statevector(np.eye(2**15, 1)) latex_representation = state_to_latex(sv) self.assertEqual(latex_representation, " |000000000000000\\rangle") def test_state_to_latex_with_max_size_limit(self): """Test limit the maximum number of non-zero terms in the expression""" sv = Statevector( [ 0.35355339 + 0.0j, 0.35355339 + 0.0j, 0.35355339 + 0.0j, 0.35355339 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 - 0.35355339j, 0.0 + 0.35355339j, 0.0 + 0.35355339j, 0.0 - 0.35355339j, ], dims=(2, 2, 2, 2), ) latex_representation = state_to_latex(sv, max_size=5) self.assertEqual( latex_representation, "\\frac{\\sqrt{2}}{4} |0000\\rangle+" "\\frac{\\sqrt{2}}{4} |0001\\rangle + " "\\ldots +" "\\frac{\\sqrt{2} i}{4} |1110\\rangle- " "\\frac{\\sqrt{2} i}{4} |1111\\rangle", ) def test_state_to_latex_with_decimals_round(self): """Test rounding of decimal places in the expression""" sv = Statevector( [ 0.35355339 + 0.0j, 0.35355339 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 - 0.35355339j, 0.0 + 0.35355339j, ], dims=(2, 2, 2), ) latex_representation = state_to_latex(sv, decimals=3) self.assertEqual( latex_representation, "0.354 |000\\rangle+0.354 |001\\rangle- 0.354 i |110\\rangle+0.354 i |111\\rangle", ) def test_number_to_latex_terms(self): """Test conversions of complex numbers to latex terms""" cases = [ ([1 - 8e-17, 0], ["", None]), ([0, -1], [None, "-"]), ([0, 1], [None, ""]), ([0, 1j], [None, "i"]), ([-1, 1], ["-", "+"]), ([0, 1j], [None, "i"]), ([-1, 1j], ["-", "+i"]), ([1e-16 + 1j], ["i"]), ([-1 + 1e-16 * 1j], ["-"]), ([-1, -1 - 1j], ["-", "+(-1 - i)"]), ([np.sqrt(2) / 2, np.sqrt(2) / 2], ["\\frac{\\sqrt{2}}{2}", "+\\frac{\\sqrt{2}}{2}"]), ([1 + np.sqrt(2)], ["(1 + \\sqrt{2})"]), ] with self.assertWarns(DeprecationWarning): for numbers, latex_terms in cases: terms = numbers_to_latex_terms(numbers, 15) self.assertListEqual(terms, latex_terms) def test_statevector_draw_latex_regression(self): """Test numerical rounding errors are not printed""" sv = Statevector(np.array([1 - 8e-17, 8.32667268e-17j])) latex_string = sv.draw(output="latex_source") self.assertTrue(latex_string.startswith(" |0\\rangle")) self.assertNotIn("|1\\rangle", latex_string) def test_statevctor_iter(self): """Test iteration over a state vector""" empty_vector = [] dummy_vector = [1, 2, 3] empty_sv = Statevector([]) sv = Statevector(dummy_vector) # Assert that successive iterations behave as expected, i.e., the # iterator is reset upon each exhaustion of the corresponding # collection of elements. for _ in range(2): self.assertEqual(empty_vector, list(empty_sv)) self.assertEqual(dummy_vector, list(sv)) def test_statevector_len(self): """Test state vector length""" empty_vector = [] dummy_vector = [1, 2, 3] empty_sv = Statevector([]) sv = Statevector(dummy_vector) self.assertEqual(len(empty_vector), len(empty_sv)) self.assertEqual(len(dummy_vector), len(sv)) def test_clip_probabilities(self): """Test probabilities are clipped to [0, 1].""" sv = Statevector([1.1, 0]) self.assertEqual(list(sv.probabilities()), [1.0, 0.0]) # The "1" key should be zero and therefore omitted. self.assertEqual(sv.probabilities_dict(), {"0": 1.0}) def test_round_probabilities(self): """Test probabilities are correctly rounded. This is good to test to ensure clipping, renormalizing and rounding work together. """ p = np.sqrt(1 / 3) sv = Statevector([p, p, p, 0]) expected = [0.33, 0.33, 0.33, 0] self.assertEqual(list(sv.probabilities(decimals=2)), expected) if __name__ == "__main__": unittest.main()
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
GIRISHBELANI
""" Uniformly controlled rotation from arXiv:0407010 """ import numpy as np from sympy.combinatorics.graycode import GrayCode from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute def dot_product(str1, str2): """ dot product between 2 binary string """ prod = 0 for j in range(len(str1)): if str1[j] == '1' and str2[j] == '1': prod = (prod + 1)%2 return prod def conversion_matrix(N): M = np.zeros((N,N)) n = int(np.log2(N)) gc_list = list(GrayCode(n).generate_gray()) # list of gray code strings for i in range(N): g_i = gc_list[i] for j in range(N): b_j = np.binary_repr(j, width=n)[::-1] M[i,j] = (-1)**dot_product(g_i, b_j)/(2**n) return M def alpha2theta(alpha): """ alpha : list of angles that get applied controlled on 0,...,2^n-1 theta : list of angles occuring in circuit construction """ N = len(alpha) M = conversion_matrix(N) theta = M @ np.array(alpha) return theta def uni_con_rot_recursive_step(qc, qubits, anc, theta): """ qc : qiskit QuantumCircuit object qubits : qiskit QuantumRegister object anc : ancilla qubit register on which rotation acts theta : list of angles specifying rotations for 0, ..., 2^(n-1) """ if type(qubits) == list: n = len(qubits) else: n = qubits.size # lowest level of recursion if n == 1: qc.ry(theta[0], anc[0]) qc.cx(qubits[0], anc[0]) qc.ry(theta[1], anc[0]) elif n > 1: qc = uni_con_rot_recursive_step(qc, qubits[1:], anc, theta[0:int(len(theta)/2)]) qc.cx(qubits[0], anc[0]) qc = uni_con_rot_recursive_step(qc, qubits[1:], anc, theta[int(len(theta)/2):]) return qc def uniformly_controlled_rot(n, theta): qubits = QuantumRegister(n) anc_reg = QuantumRegister(1) qc = QuantumCircuit(qubits, anc_reg, name = 'INV_ROT') qc = uni_con_rot_recursive_step(qc, qubits, anc_reg, theta) qc.cx(qubits[0], anc_reg[0]) return qc # def uniformly_controlled_rot(qc, qubits, anc, theta): # """ # qc : qiskit QuantumCircuit object # qubits : qiskit QuantumRegister object # anc : ancilla qubit register on which rotation acts # theta : list of angles specifying rotations for 0, ..., 2^(n-1) # """ # qc = uni_con_rot_recursive_step(qc, qubits, anc, theta) # qc.cx(qubits[0], anc[0]) # return qc def test_circuit(n): shots = 10000 C = 0.25 N = 2**n # make list of rotation angles alpha = [2*np.arcsin(C)] for j in range(1,N): j_rev = int(np.binary_repr(j, width=n)[::-1],2) alpha.append(2*np.arcsin(C*N/j_rev)) theta = alpha2theta(alpha) for x in range(N): # state prep #x_bin = np.binary_repr(x, width=n) qubits = QuantumRegister(n) anc = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qubits, anc, cr) # state prep x_bin = np.binary_repr(x, width=n) for q in range(n): if x_bin[n-1-q] == '1': qc.x(q) qc.barrier() qc = uniformly_controlled_rot(qc, qubits, anc, theta) qc.barrier() qc.measure(anc[0], cr[0]) outcomes = sim_circuit(qc, shots) print(round(outcomes['1']/shots, 4)) def sim_circuit(qc, shots): simulator = Aer.get_backend('qasm_simulator') result = execute(qc, simulator, shots=shots).result() outcomes = result.get_counts(qc) return outcomes
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from qiskit import QuantumCircuit from crypto.b92.sender import Sender from crypto.b92.receiver import Receiver import binascii B92_SIMULATOR = 'B92 SIMULATOR' ## An implementation of the B92 protocol ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class B92Algorithm: ## Generate a key for Alice and Bob def generate_key(self, backend, original_bits_size, verbose): # Encoder Alice alice = Sender('Alice', original_bits_size) alice.set_values() message = alice.encode_quantum_message() # Interceptor Eve eve = Receiver('Eve', original_bits_size) eve.set_axes() message = eve.decode_quantum_message(message, self.measure_density, backend) # Decoder Bob bob = Receiver('Bob', original_bits_size) bob.set_axes() message = bob.decode_quantum_message(message, 1, backend) # Bob shares his positives reading indexes bob_positive_readings_indexes = bob.share_positive_readings_indexes() # Delete the difference alice.remove_garbage(bob_positive_readings_indexes) bob.remove_garbage(bob_positive_readings_indexes) # Bob share some values of the key to check SHARED_SIZE = round(0.5 * len(bob.key)) shared_key = bob.key[:SHARED_SIZE] if verbose: alice.show_values() eve.show_values() eve.show_axes() bob.show_values() bob.show_axes() alice.show_key() bob.show_key() print('\nShared Bob Key:') print(shared_key) # Alice check the shared key if alice.check_key(shared_key): shared_size = len(shared_key) alice.confirm_key(shared_size) bob.confirm_key(shared_size) if verbose: print('\nFinal Keys') alice.show_key() bob.show_key() print('\nSecure Communication!') elif verbose: print('\nUnsecure Communication! Eve has been detected intercepting messages\n') return alice, bob ## Run the implementation of B92 protocol def run(self, message, backend, original_bits_size, measure_density, n_bits, verbose): ## The original size of the message self.original_bits_size = original_bits_size ## The probability of an interception occurring self.measure_density = measure_density alice, bob = self.generate_key(backend, original_bits_size, verbose) if not (alice.is_safe_key and bob.is_safe_key): if verbose: print('❌ Message not send') return False alice.generate_otp(n_bits) bob.generate_otp(n_bits) encoded_message = alice.xor_otp_message(message) decoded_message = bob.xor_otp_message(encoded_message) if verbose: alice.show_otp() bob.show_otp() print('\nInitial Message:') print(message) print('Encoded Message:') print(encoded_message) print('💡 Decoded Message:') print(decoded_message) if message == decoded_message: print('\n✅ The initial message and the decoded message are identical') else: print('\n❌ The initial message and the decoded message are different') return True
https://github.com/ayush-vatsal/Grovers_Search_Algorithm
ayush-vatsal
from qiskit import QuantumCircuit, Aer, assemble, ClassicalRegister, QuantumRegister, transpile import numpy as np from qiskit.visualization import plot_histogram, plot_bloch_multivector #clause_list = [[0,1], [1,2], [2,3]] address = QuantumRegister(2, name='add') var = QuantumRegister(4, name='v') clause_qubits = QuantumRegister(3, name='c') output = QuantumRegister(1, name='out') result = ClassicalRegister(3, name='cbit') qc = QuantumCircuit(address, var, clause_qubits, output , result) def qRAM(qc, address, var): qc.x(address) qc.mct(address, var[3]) qc.x(address) qc.barrier(address, var) qc.x(address[0]) qc.mct(address, var[1]) qc.mct(address, var[3]) qc.x(address[0]) qc.barrier(address, var) qc.x(address[1]) qc.mct(address, var[1]) qc.mct(address, var[2]) qc.x(address[1]) qc.barrier(address, var) qc.mct(address, var[0]) qc.mct(address, var[2]) qRAM(qc, address, var) qc.draw() def oracle(qc, var, clause_qubits): qc.cx(var[0], clause_qubits[0]) qc.cx(var[1], clause_qubits[0]) qc.cx(var[1], clause_qubits[1]) qc.cx(var[2], clause_qubits[1]) qc.cx(var[2], clause_qubits[2]) qc.cx(var[3], clause_qubits[2]) qc.mct(clause_qubits, output) qc.cx(var[0], clause_qubits[0]) qc.cx(var[1], clause_qubits[0]) qc.cx(var[1], clause_qubits[1]) qc.cx(var[2], clause_qubits[1]) qc.cx(var[2], clause_qubits[2]) qc.cx(var[3], clause_qubits[2]) oracle(qc, var, clause_qubits) qc.draw(fold=-1) def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "U$_s$" return U_s address = QuantumRegister(2, name='add') var = QuantumRegister(4, name='v') clause_qubits = QuantumRegister(3, name='c') output = QuantumRegister(1, name='out') result = ClassicalRegister(2, name='cbit') results = ClassicalRegister(4, name='cbits') qc = QuantumCircuit(address, var, clause_qubits, output , result, results) qc.initialize([1, -1]/np.sqrt(2), output) qc.h(address) qc.barrier() qRAM(qc, address, var) qc.barrier() #qc.h(var)#remove# oracle(qc, var, clause_qubits) qc.barrier() qc.append(diffuser(2), [0,1]) qc.append(diffuser(4), [2,3,4,5]) #qc.measure(address, result[0:2]) qc.measure(var, results) qc.draw(fold=-1) aer_simulator = Aer.get_backend('aer_simulator') transpiled_qc = transpile(qc, aer_simulator) qobj = assemble(transpiled_qc) result = aer_simulator.run(qobj).result() plot_histogram(result.get_counts())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0) plot_circuit_layout(new_circ_lv0, backend)
https://github.com/QuantumBarcelona/Qiskit-Hackathon-BCN
QuantumBarcelona
## Black scholes, simulation parameters and basic imports import matplotlib.pyplot as plt import numpy as np K = 100 # strike price sigma = 0.4 # volatility in % T = 1 r = 0 Smin = 50 Smax = 150 Nqubits = 4 #Define range of stock price S = np.arange(Smin,Smax,5) #Define the Payoff Function def call_payoff(S,K): # TO DO pass #Define the underlying strike price K = 100 #Calculate the payoff for the option payoff = call_payoff(S,K) #Plot the Payoff Graph fig, ax = plt.subplots() ax.spines['bottom'].set_position('zero') ax.plot(S, payoff, '--', color='g') plt.xlabel('x') plt.ylabel('Payoff') plt.title('Call Option Payoff') plt.show() ## PUT CODE HERE ## PUT CODE HERE ## PUT CODE HERE
https://github.com/sam-pf/pf-qiskit
sam-pf
def _initialize (): # <<< import qiskit from math import isclose, sqrt from numpy import exp, pi # pylint: disable=E0401,E0611 from qiskit.circuit.library.data_preparation import state_preparation # pylint: enable=E0401,E0611 _EPS = state_preparation._EPS _initialize_orig = qiskit.QuantumCircuit.initialize # pylint: disable=E1101 docstr = """ A patched version of :meth:`qiskit.QuantumCircuit.initialize` so that ``params`` accepts probability-centric expressions (in % unit). When ``params`` is an iterable of strings, and only strings, then the string expressions are parsed by this method as probability expressions (with optional probability amplitude phases) and then converted to the probability amplitudes for internal use. Additionally, ``params`` may be a string that includes all probability-centric expressions, separated by ',' and enclosed by '[' and ']'. Probability-centric string expression must be in the following format .. parsed-literal:: '<probability> %' '<probability> % <phase>' where ``<probability>`` and ``<phase>`` must be expressions for real numbers (non-negative for ``<probability>``) and any white space before ``%`` or after ``%`` is optional. So, in addition to specifying the probability, the phase of the probability amplitude can also be optionally specified. The phase here corresponds to the angle in the complex plane (as probability amplitude is complex number; see the conversion forma below), and so it may just be considered angle. Its unit is (implicitly) fixed as degrees. Here are some basic phase values. 360 degrees, or any integer multiples of 360 degrees, is the same as 0 degrees (which means a positive amplitude), 180 degrees means a negative amplitude, 90 degrees means multiplying the amplitude by 1j, 270 degrees means multiplying the amplitude by -1j, etc. For instance, all the following examples are valid inputs for ``params`` for a single qubit. For refernece, corresponding numeric expressions for the probably amplitude are also given. .. code-block:: ['100 %', '0 %'] : [1, 0] '[100 % 360, 0 %]' : [1, 0] '[100 % 720.0, 0 %]' : [1, 0] ['100 % -360', '0 %'] : [1, 0] '[100 % 180, 0 %]' : [-1, 0] '[50 % 90, 50 % 180]' : [sqrt(0.5)*1j, -sqrt(0.5)] '[70 % 2, 30 % 270]' : [sqrt(0.7)*exp(2j*pi/180), -sqrt(0.3)*1j] ['70 % 2', '30 % 270'] : [sqrt(0.7)*exp(2j*pi/180), -sqrt(0.3)*1j] As these examples demonstrate, the formula going from the `<probability>` and `<phase>` to the probability amplitude is as follows: ``sqrt(<probability>) * exp(<phase> * 1j * pi/180)``. In this way, the probabiliy-centric specification of ``params`` using string is equal in terms of its expressive power as the probabiliy amplitude specification using (generally complex) numbers. For example the following two circuits ``c1`` and ``c2`` are initialized exactly the same way. .. code-block:: import numpy as np from qiskit import QuantumCircuit c1 = QuantumCircuit (1) c1.initialize ([1/np.sqrt(2), -1/np.sqrt(2)]) c2 = QuantumCircuit (1) c2.initialize (['50 %', '50 % 180']) """.strip () if _initialize_orig.__doc__: docstr += """ --- The documentation for the unpatched version of this method follows. --- """ + _initialize_orig.__doc__ phase_arg_factor = 1j * pi / 180. from collections.abc import Iterable def initialize (self, params, qubits = None): # <<< if isinstance (params, str): s = params.strip () if s.startswith ('[') and s.endswith (']'): s = s [1:-1] params = s.split (',') if isinstance (params, Iterable) and not isinstance (params, str): params = list (params) score = sum (1 if isinstance (v, str) else 0 for v in params) if score == len (params): params_new = [] pr_sum = 0. for v in params: if '%' not in v: raise ValueError ("Any string iterated by params " "must contain %.") pr, pf = v.split ('%', 1) pr = float (pr) pf = (exp (float (pf) * phase_arg_factor) if pf.strip () else 1.) if pr < 0: if isclose (pr, 0., abs_tol = _EPS): pr = 0. else: raise ValueError (f"Probability in {v!r} is not " "non-negative.") params_new.append (sqrt (pr) * pf / 10.) pr_sum += pr if not isclose (pr_sum, 100., abs_tol = _EPS * 100.): raise ValueError ("Sum of probabilities must be equal to " "100 (%).") params = params_new elif score: raise TypeError ("If a string is an element of params then " "all elements must be strings.") return _initialize_orig (self, params, qubits = qubits) # >>> initialize.__doc__ = docstr return initialize # >>> _initialize = _initialize () def _ (): # <<< import qiskit if qiskit.QuantumCircuit.initialize is _initialize: # pylint: disable=E1101 return qiskit.QuantumCircuit.initialize = _initialize # pylint: disable=E1101 # >>> _ ()
https://github.com/PayalSolanki2906/Quantum_algorithms_using_Qiskit
PayalSolanki2906
from qiskit import QuantumCircuit, Aer, assemble import numpy as np from qiskit.visualization import plot_histogram, plot_bloch_multivector from qiskit.visualization import array_to_latex qc = QuantumCircuit(3) # Apply H-gate to each qubit: for qubit in range(3): qc.h(qubit) # See the circuit: qc.draw() # Let's see the result svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() # 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(final_state) instead. array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.x(0) qc.draw() svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.h(0) qc.draw() svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.x(0) qc.h(1) qc.draw() svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.h(1) qc.draw() svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.draw() usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Circuit = }\n") qc = QuantumCircuit(1) qc.x(0) qc.z(0) qc.h(0) qc.draw() usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Circuit = }\n") qc = QuantumCircuit(3) qc.x(2) qc.z(1) qc.h(0) qc.draw() usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Circuit = }\n") qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) # Apply a CNOT: qc.cx(0,1) qc.draw() # Let's get the result: qc.save_statevector() qobj = assemble(qc) result = svsim.run(qobj).result() # Print the statevector neatly: final_state = result.get_statevector() array_to_latex(final_state, prefix="\\text{Statevector = }") plot_bloch_multivector(final_state) qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) qc.draw() # Let's get the result: qc.save_statevector() qobj = assemble(qc) result = svsim.run(qobj).result() # Print the statevector neatly: final_state = result.get_statevector() array_to_latex(final_state, prefix="\\text{Statevector = }") plot_bloch_multivector(final_state) qc = QuantumCircuit(2) # Apply H-gate to the first: qc.x(0) qc.h(1) qc.cx(1,0) qc.draw() # Let's get the result: qc.save_statevector() qobj = assemble(qc) result = svsim.run(qobj).result() # Print the statevector neatly: final_state = result.get_statevector() array_to_latex(final_state, prefix="\\text{Statevector = }") qc = QuantumCircuit(2) # Apply H-gate to the first: qc.x(0) qc.h(1) qc.cx(1,0) usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Circuit = }\n")
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import * from qiskit.tools.parallel import parallel_map from qiskit.tools.events import TextProgressBar from qiskit.tools.jupyter import * # Needed to load the Jupyter HTMLProgressBar num_circuits = 1000 width = 4 depth = 4 import copy import math import numpy as np from qiskit.tools.qi.qi import random_unitary_matrix from qiskit.mapper import two_qubit_kak def build_qv_circuit(idx, seeds, width, depth): """Builds a single Quantum Volume circuit. Two circuits, one with measurements, and one widthout, are returned. The model circuits consist of layers of Haar random elements of SU(4) applied between corresponding pairs of qubits in a random bipartition. See: https://arxiv.org/abs/1811.12926 """ np.random.seed(seeds[idx]) q = QuantumRegister(width, "q") c = ClassicalRegister(width, "c") # Create measurement subcircuit qc = QuantumCircuit(q,c) # For each layer for j in range(depth): # Generate uniformly random permutation Pj of [0...n-1] perm = np.random.permutation(width) # For each pair p in Pj, generate Haar random SU(4) # Decompose each SU(4) into CNOT + SU(2) and add to Ci for k in range(math.floor(width/2)): qubits = [int(perm[2*k]), int(perm[2*k+1])] U = random_unitary_matrix(4) for gate in two_qubit_kak(U): i0 = qubits[gate["args"][0]] if gate["name"] == "cx": i1 = qubits[gate["args"][1]] qc.cx(q[i0], q[i1]) elif gate["name"] == "u1": qc.u1(gate["params"][2], q[i0]) elif gate["name"] == "u2": qc.u2(gate["params"][1], gate["params"][2], q[i0]) elif gate["name"] == "u3": qc.u3(gate["params"][0], gate["params"][1], gate["params"][2], q[i0]) elif gate["name"] == "id": pass # do nothing qc_no_meas = copy.deepcopy(qc) # Create circuit with final measurement qc.measure(q,c) return qc, qc_no_meas num_circuits = 1000 seeds = np.random.randint(np.iinfo(np.int32).max, size=num_circuits) TextProgressBar() parallel_map(build_qv_circuit, np.arange(num_circuits), task_args=(seeds, width, depth)); seeds = np.random.randint(np.iinfo(np.int32).max, size=num_circuits) HTMLProgressBar() parallel_map(build_qv_circuit, np.arange(num_circuits), task_args=(seeds, width, depth));
https://github.com/ranaarp/Qiskit-Meetup-content
ranaarp
#initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.tools.visualization import plot_histogram # IBMQ.save_account('your account id') provider = IBMQ.load_account() q = QuantumRegister(7) c = ClassicalRegister(4) qc = QuantumCircuit(q, c) # initialize in a superposition of all possible states qc.x(q[4]) qc.h(q[0:5]) qc.barrier(q) qc.barrier(q) # build oracle. ex: to find 1010 state qc.x(q[1]) qc.x(q[3]) qc.barrier(q) qc.mct([q[0], q[1], q[2], q[3]], q[4], q[5:7]) # control qubits, target qubit, ancilla qubits = number of control qubits - 2 qc.barrier(q) qc.x(q[1]) qc.x(q[3]) qc.barrier(q) qc.barrier(q) qc.h(q[0:4]) qc.barrier(q) qc.x(q[0:4]) qc.barrier(q) qc.h(q[3]) qc.barrier(q) qc.mct([q[0], q[1], q[2]], q[3], q[5:6]) qc.barrier(q) qc.h(q[3]) qc.barrier(q) qc.x(q[0:4]) qc.barrier(q) qc.h(q[0:4]) qc.barrier(q) qc.measure(q[0:4], c[0:4]) qc.draw(output='mpl') # in the output drawing # running and getting results backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1000) # backend = provider.get_backend('ibmq_qasm_simulator') # job = execute(qc, backend=backend, shots=8000, seed_simulator=12345, backend_options={"fusion_enable":True}) result = job.result() count = result.get_counts() print(count) # the code snippet below can be used to retreive your job in case your jupyter notebook loses connection with IBMQ servers before completion of the job # backend = provider.get_backend('ibmq_qasm_simulator') # job = backend.retrieve_job('enter your job id here. it can be found in your IBM Q Experience dashboard') # counts = job.result().get_counts() # print(counts) plot_histogram(count) # the answer may seem inverted, i.e, 0101 is actually state 1010. that's just the notation used by qiskit.
https://github.com/DaisukeIto-ynu/KosakaQ_client
DaisukeIto-ynu
# -*- coding: utf-8 -*- """ Created on Thu Nov 17 15:00:00 2022 @author: Yokohama National University, Kosaka Lab """ import requests from qiskit.providers import ProviderV1 as Provider #抽象クラスのインポート from qiskit.providers.exceptions import QiskitBackendNotFoundError #エラー用のクラスをインポート from exceptions import KosakaQTokenError, KosakaQBackendJobIdError, KosakaQBackendFilterError #エラー用のクラス(自作)をインポート from kosakaq_backend import KosakaQBackend from kosakaq_job import KosakaQJob from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister class KosakaQProvider(Provider): #抽象クラスからの継承としてproviderクラスを作る def __init__(self, access_token=None):#引数はself(必須)とtoken(認証が必要な場合)、ユーザーに自分でコピペしてもらう super().__init__() #ソースコードは()空なので真似した self.access_token = access_token #トークン定義 self.name = 'kosakaq_provider' #nameという変数を右辺に初期化、このproviderクラスの名づけ self.url = 'http://192.168.1.82' #リンク変更可能 self.wjson = '/api/backends.json' #jsonに何を入れてサーバーに送るか self.jobson = '/job/' def backends(self, name=None, **kwargs):#API(サーバー)に今使えるbackendを聞く(Rabiが使えるとかunicornが使えるとかをreturn[使えるもの]で教えてくれる) """指定したフィルタリングと合うバックエンドたちを返すメソッド 引数: name (str): バックエンドの名前(Rabiやunicorn). **kwargs: フィルタリングに使用される辞書型 戻り値: list[Backend]: フィルタリング基準に合うバックエンドたちのリスト """ self._backend = [] #availableなバックエンドクラスのbkednameを入れていくためのリスト res = requests.get(self.url + self.wjson, headers={"Authorization": "Token " + self.access_token}) response = res.json() #[{'id': 1, 'bkedid': 0, 'bkedname': 'Rabi', 'bkedstatus': 'unavailable','detail': 'Authentication credentials were not provided',...}, {'id': 2, 'bkedid': 1, 'bkedname': 'Unicorn', 'bkedstatus': 'available'}] if 'detail' in response[0]: #トークンが違ったらdetailの辞書一つだけがresponseのリストに入っていることになる raise KosakaQTokenError('access_token was wrong') #トークン間違いを警告 for i in range(len(response)): if response[i]['bkedstatus'] =='available': if name == None: self._backend.append(KosakaQBackend(self, response[i]['bkedname'], self.url, response[i]['bkedversion'], response[i]['bkednqubits'], 4096, 1)) elif name == response[i]['bkedname']: self._backend.append(KosakaQBackend(self, response[i]['bkedname'], self.url, response[i]['bkedversion'], response[i]['bkednqubits'], 4096, 1)) else: pass return self._backend#responseのstatusがavailableかつフィルタリングにあうバックエンドたちのバックエンドクラスのインスタンスリストを返す def get_backend(self, name=None, **kwargs): #ユーザーに"Rabi"などを引数として入れてもらう、もしbackendsメソッドのreturnにRabiがあればインスタンスを作れる """指定されたフィルタリングに合うバックエンドを一つだけ返す(一つ下のメソッドbackendsの一つ目を取り出す) 引数: name (str): バックエンドの名前 **kwargs: フィルタリングに使用される辞書型 戻り値: Backend: 指定されたフィルタリングに合うバックエンド Raises: QiskitBackendNotFoundError: バックエンドが見つからなかった場合、もしくは複数のバックエンドがフィルタリングに合う場合、もしくは一つもフィルタリング条件に合わない場合 """ backends = self.backends(name, **kwargs) #backendsという変数にbackendsメソッドのreturnのリストを代入 if len(backends) > 1: raise QiskitBackendNotFoundError('More than one backend matches criteria') if not backends: raise QiskitBackendNotFoundError('No backend matches criteria.') return backends[0] def retrieve_job(self, job_id: str):#jobidを文字列として代入してもらう(指定してもらう),対応するJobを返す """このバックエンドに投入されたjobを一つだけ返す 引数: job_id: 取得したいjobのID 戻り値: 与えられたIDのjob Raises: KosakaQBackendJobIdError: もしjobの取得に失敗した場合、ID間違いのせいにする """ res = requests.get(self.url + self.jobson, headers={"Authorization": "Token " + self.access_token}, params={"jobid": job_id}) response = res.json()#辞書型{bkedlist,jobist,qobjlist} print(response) if response['joblist'][0]['jobid'] == job_id: for i in range(len(response['bkedlist'])): if response['bkedlist'][i]['bkedid'] == response['joblist'][0]['bkedid']: bkedname = response['bkedlist'][i]['bkedname'] backend = KosakaQBackend(self, bkedname, self.url, response['bkedlist'][i]['bkedversion'], response['bkedlist'][i]['bkednqubits'], 4096, 1) #量子レジスタqを生成する。 q = QuantumRegister(1) #古典レジスタcを生成する c = ClassicalRegister(2) qc = QuantumCircuit(q, c) string = response['qobjlist'][0][0]['gates'] gateslist = eval(string) #gatelist=["H","X"] for gate_name in gateslist: if gate_name == "I": qc.i(q[0]) elif gate_name == "X": qc.x(q[0]) elif gate_name == "Y": qc.y(q[0]) elif gate_name == "Z": qc.z(q[0]) elif gate_name == "H": qc.h(q[0]) elif gate_name == "S": qc.s(q[0]) elif gate_name == "SDG": qc.sdg(q[0]) elif gate_name == "SX": qc.sx(q[0]) elif gate_name == "SXDG": qc.sxdg(q[0]) else: pass return KosakaQJob(backend, response['joblist'][0]['jobid'], self.access_token, qc) else: raise KosakaQBackendJobIdError('Job_id was wrong') def jobs(self, limit: int = 10, skip: int = 0, jobstatus = None, jobid = None, begtime = None, bkedid = None, fintime = None, job_num = None, note = None, posttime = None, qobjid = None, userid = None ): #list[KosakaQJob]を返す """このバックエンドに送信されたjobのうち指定したフィルタに合うものを取得して、返す 引数: limit: 取得するjobの上限数 skip: jobを飛ばしながら参照 jobstatus: このステータスを持つjobのみを取得する。 指定方法の例 `status=JobStatus.RUNNING` or `status="RUNNING"` or `status=["RUNNING", "ERROR"]` jobid: jobの名前でのフィルタリング用。 job名は部分的にマッチする、そして `regular expressions(正規表現) <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions>`_ が使われる。 begtime: 指定された開始日(現地時間)でのフィルター用。これは作成日がこの指定した現地時間より後のjobを探すのに使われる。 fintime: 指定された終了日(現地時間)でのフィルター用。 これは作成日がこの指定された現地時間よりも前に作られたjobを見つけるために使われる。 job_num: jobの番号 note: メモ posttime: 投稿時間 qobjid: qobjのID userid: ユーザーID 戻り値: 条件に合うjobのリスト Raises: KosakaQBackendFilterError: キーワード値が認識されない場合 (でも、メソッド内で使われてない) """ jobs_list = [] #返す用のリスト res = requests.get(self.url + self.jobson, headers={"Authorization": "Token " + self.access_token}) response = res.json()#辞書型{bkedlist(ラビ、ユニコーン),jobist(jobnumがjobの数だけ),qobjlist(qobjnumがqobjの数だけ、ゲートもたくさん)} print(response) for i in range(len(response['joblist'])): if response['joblist'][i]['begtime'] == begtime or response['joblist'][i]['begtime'] == None : if response['joblist'][i]['bkedid'] == bkedid or response['joblist'][i]['bkedid'] == None: if response['joblist'][i]['fintime'] == fintime or response['joblist'][i]['fintime'] == None: if response['joblist'][i]['job_num'] == job_num or response['joblist'][i]['job_num'] == None: if response['joblist'][i]['jobid'] == jobid or response['joblist'][i]['jobid'] == None: if response['joblist'][i]['jobstatus'] == jobstatus or response['joblist'][i]['jobstatus'] == None: if response['joblist'][i]['note'] == note or response['joblist'][i]['note'] == None: if response['joblist'][i]['posttime'] == posttime or response['joblist'][i]['posttime'] == None: if response['joblist'][i]['qobjid'] == qobjid or response['joblist'][i]['qobjid'] == None: if response['joblist'][i]['userid'] == userid or response['joblist'][i]['userid'] == None: bked_id = response['joblist'][i]['bkedid']#代入用bkedid bked_posi =bked_id-1 #代入用バックエンド番号 backend = KosakaQBackend(self, response['bkedlist'][bked_posi]['bkedname'], self.url, response['bkedlist'][bked_posi]['bkedversion'], response['bkedlist'][bked_posi]['bkednqubits'], 4096, 1) #量子レジスタqを生成する。 q = QuantumRegister(1) #古典レジスタcを生成する c = ClassicalRegister(2) qc = QuantumCircuit(q, c) string = response['qobjlist'][i]['gates'] gateslist = eval(string) #gatelist=["H","X"] for gate_name in gateslist: if gate_name == "I": qc.i(q[0]) elif gate_name == "X": qc.x(q[0]) elif gate_name == "Y": qc.y(q[0]) elif gate_name == "Z": qc.z(q[0]) elif gate_name == "H": qc.h(q[0]) elif gate_name == "S": qc.s(q[0]) elif gate_name == "SDG": qc.sdg(q[0]) elif gate_name == "SX": qc.sx(q[0]) elif gate_name == "SXDG": qc.sxdg(q[0]) else: pass jobs_list.insert(i, KosakaQJob(backend, response['joblist'][i]['jobid'], self.access_token, qc)) if len(jobs_list) == 0: raise KosakaQBackendFilterError('Filter was Error') return jobs_list def __eq__(self, other): #等号の定義 """Equality comparison. By default, it is assumed that two `Providers` from the same class are equal. Subclassed providers can override this behavior. """ return type(self).__name__ == type(other).__name__
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from sklearn.datasets import load_iris iris_data = load_iris() print(iris_data.DESCR) features = iris_data.data labels = iris_data.target from sklearn.preprocessing import MinMaxScaler features = MinMaxScaler().fit_transform(features) import pandas as pd import seaborn as sns df = pd.DataFrame(iris_data.data, columns=iris_data.feature_names) df["class"] = pd.Series(iris_data.target) sns.pairplot(df, hue="class", palette="tab10") from sklearn.model_selection import train_test_split from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123 train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=0.8, random_state=algorithm_globals.random_seed ) from sklearn.svm import SVC svc = SVC() _ = svc.fit(train_features, train_labels) # suppress printing the return value train_score_c4 = svc.score(train_features, train_labels) test_score_c4 = svc.score(test_features, test_labels) print(f"Classical SVC on the training dataset: {train_score_c4:.2f}") print(f"Classical SVC on the test dataset: {test_score_c4:.2f}") from qiskit.circuit.library import ZZFeatureMap num_features = features.shape[1] feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1) feature_map.decompose().draw(output="mpl", fold=20) from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=num_features, reps=3) ansatz.decompose().draw(output="mpl", fold=20) from qiskit.algorithms.optimizers import COBYLA optimizer = COBYLA(maxiter=100) from qiskit.primitives import Sampler sampler = Sampler() from matplotlib import pyplot as plt from IPython.display import clear_output objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) 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() import time from qiskit_machine_learning.algorithms.classifiers import VQC vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q4 = vqc.score(train_features, train_labels) test_score_q4 = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}") print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}") from sklearn.decomposition import PCA features = PCA(n_components=2).fit_transform(features) plt.rcParams["figure.figsize"] = (6, 6) sns.scatterplot(x=features[:, 0], y=features[:, 1], hue=labels, palette="tab10") train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=0.8, random_state=algorithm_globals.random_seed ) svc.fit(train_features, train_labels) train_score_c2 = svc.score(train_features, train_labels) test_score_c2 = svc.score(test_features, test_labels) print(f"Classical SVC on the training dataset: {train_score_c2:.2f}") print(f"Classical SVC on the test dataset: {test_score_c2:.2f}") num_features = features.shape[1] feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1) ansatz = RealAmplitudes(num_qubits=num_features, reps=3) optimizer = COBYLA(maxiter=40) vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] # make the objective function plot look nicer. plt.rcParams["figure.figsize"] = (12, 6) start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q2_ra = vqc.score(train_features, train_labels) test_score_q2_ra = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset using RealAmplitudes: {train_score_q2_ra:.2f}") print(f"Quantum VQC on the test dataset using RealAmplitudes: {test_score_q2_ra:.2f}") from qiskit.circuit.library import EfficientSU2 ansatz = EfficientSU2(num_qubits=num_features, reps=3) optimizer = COBYLA(maxiter=40) vqc = VQC( sampler=sampler, feature_map=feature_map, ansatz=ansatz, optimizer=optimizer, callback=callback_graph, ) # clear objective value history objective_func_vals = [] start = time.time() vqc.fit(train_features, train_labels) elapsed = time.time() - start print(f"Training time: {round(elapsed)} seconds") train_score_q2_eff = vqc.score(train_features, train_labels) test_score_q2_eff = vqc.score(test_features, test_labels) print(f"Quantum VQC on the training dataset using EfficientSU2: {train_score_q2_eff:.2f}") print(f"Quantum VQC on the test dataset using EfficientSU2: {test_score_q2_eff:.2f}") print(f"Model | Test Score | Train Score") print(f"SVC, 4 features | {train_score_c4:10.2f} | {test_score_c4:10.2f}") print(f"VQC, 4 features, RealAmplitudes | {train_score_q4:10.2f} | {test_score_q4:10.2f}") print(f"----------------------------------------------------------") print(f"SVC, 2 features | {train_score_c2:10.2f} | {test_score_c2:10.2f}") print(f"VQC, 2 features, RealAmplitudes | {train_score_q2_ra:10.2f} | {test_score_q2_ra:10.2f}") print(f"VQC, 2 features, EfficientSU2 | {train_score_q2_eff:10.2f} | {test_score_q2_eff:10.2f}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/quantumjim/qreative
quantumjim
# coding: utf-8 # Aug 2018 version: Copyright © 2018 James Wootton, University of Basel # Later versions: Copyright © 2018 IBM Research from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, execute, IBMQ from qiskit import Aer from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error from qiskit.providers.aer import noise from qiskit.transpiler import PassManager import numpy as np import random import matplotlib.pyplot as plt from matplotlib.patches import Circle, Rectangle import copy import networkx as nx import datetime try: from pydub import AudioSegment # pydub can be a bit dodgy and might cause some warnings except: pass try: IBMQ.load_account() except: print("No IBMQ account was found, so you'll only be able to simulate locally.") def get_backend(device): """Returns backend object for device specified by input string.""" try: backend = Aer.get_backend(device) except: print("You are using an IBMQ backend. The results for this are provided in accordance with the IBM Q Experience EULA.\nhttps://quantumexperience.ng.bluemix.net/qx/terms") # Legal stuff! Yay! for provider in IBMQ.providers(): for potential_backend in provider.backends(): if potential_backend.name()==device_name: backend = potential_backend return backend def get_noise(noisy): """Returns a noise model when input is not False or None. A string will be interpreted as the name of a backend, and the noise model of this will be extracted. A float will be interpreted as an error probability for a depolarizing+measurement error model. Anything else (such as True) will give the depolarizing+measurement error model with default error probabilities.""" if noisy: if type(noisy) is str: # get noise information from a real device (via the IBM Q Experience) device = get_backend(noisy) noise_model = noise.device.basic_device_noise_model( device.properties() ) else: # make a simple noise model for a given noise strength if type(noisy) is float: p_meas = noisy p_gate1 = noisy else: # default values p_meas = 0.08 p_gate1 = 0.04 error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)]) # bit flip error with prob p_meas error_gate1 = depolarizing_error(p_gate1, 1) # replaces qubit state with nonsense with prob p_gate1 error_gate2 = error_gate1.tensor(error_gate1) # as above, but independently on two qubits noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error_meas, "measure") # add bit flip noise to measurement noise_model.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"]) # add depolarising to single qubit gates noise_model.add_all_qubit_quantum_error(error_gate2, ["cx"]) # add two qubit depolarising to two qubit gates else: noise_model = None return noise_model class ladder: """An integer implemented on a single qubit. Addition and subtraction are implemented via partial NOT gates.""" def __init__(self,d): """Create a new ladder object. This has the attribute `value`, which is an int that can be 0 at minimum and the supplied value `d` at maximum. This value is initialized to 0.""" self.d = d self.qr = QuantumRegister(1) # declare our single qubit self.cr = ClassicalRegister(1) # declare a single bit to hold the result self.qc = QuantumCircuit(self.qr, self.cr) # combine them in an empty quantum circuit def add(self,delta): """Changes value of ladder object by the given amount `delta`. This is initially done by addition, but it changes to subtraction once the maximum value of `d` is reached. It will then change back to addition once 0 is reached, and so on. delta = Amount by which to change the value of the ladder object. Can be int or float.""" self.qc.rx(np.pi*delta/self.d,self.qr[0]) def value(self,device='qasm_simulator',noisy=False,shots=1024): """Returns the current version of the ladder operator as an int. If floats have been added to this value, the sum of all floats added thus far are rounded. device = A string specifying a backend. The noisy behaviour from a real device will result in some randomness in the value given, and can lead to the reported value being less than the true value on average. These effects will be more evident for high `d`. shots = Number of shots used when extracting results from the qubit. A low value will result in randomness in the value given. This should be neglible when the value is a few orders of magnitude greater than `d`. """ temp_qc = copy.deepcopy(self.qc) temp_qc.barrier(self.qr) temp_qc.measure(self.qr,self.cr) try: job = execute(temp_qc,backend=get_backend(device),noise_model=get_noise(noisy),shots=shots) except: job = execute(temp_qc,backend=get_backend(device),shots=shots) if '1' in job.result().get_counts(): p = job.result().get_counts()['1']/shots else: p = 0 delta = round(2*np.arcsin(np.sqrt(p))*self.d/np.pi) return int(delta) class twobit: """An object that can store a single boolean value, but can do so in two incompatible ways. It is implemented on a single qubit using two complementary measurement bases.""" def __init__(self): """Create a twobit object, initialized to give a random boolean value for both measurement types.""" self.qr = QuantumRegister(1) self.cr = ClassicalRegister(1) self.qc = QuantumCircuit(self.qr, self.cr) self.prepare({'Y':None}) def prepare(self,state): """Supplying `state={basis,b}` prepares a twobit with the boolean `b` stored using the measurement type specified by `basis` (which can be 'X', 'Y' or 'Z'). Note that `basis='Y'` (and arbitrary `b`) will result in the twobit giving a random result for both 'X' and 'Z' (and similarly for any one versus the remaining two). """ self.qc = QuantumCircuit(self.qr, self.cr) if 'Y' in state: self.qc.h(self.qr[0]) if state['Y']: self.qc.sdg(self.qr[0]) else: self.qc.s(self.qr[0]) elif 'X' in state: if state['X']: self.qc.x(self.qr[0]) self.qc.h(self.qr[0]) elif 'Z' in state: if state['Z']: self.qc.x(self.qr[0]) def value (self,basis,device='qasm_simulator',noisy=False,shots=1024,mitigate=True): """Extracts the boolean value for the given measurement type. The twobit is also reinitialized to ensure that the same value would if the same call to `measure()` was repeated. basis = 'X' or 'Z', specifying the desired measurement type. device = A string specifying a backend. The noisy behaviour from a real device will result in some randomness in the value given, even if it has been set to a definite value for a given measurement type. This effect can be reduced using `mitigate=True`. shots = Number of shots used when extracting results from the qubit. A value of greater than 1 only has any effect for `mitigate=True`, in which case larger values of `shots` allow for better mitigation. mitigate = Boolean specifying whether mitigation should be applied. If so the values obtained over `shots` samples are considered, and the fraction which output `True` is calculated. If this is more than 90%, measure will return `True`. If less than 10%, it will return `False`, otherwise it returns a random value using the fraction as the probability.""" if basis=='X': self.qc.h(self.qr[0]) elif basis=='Y': self.qc.sdg(self.qr[0]) self.qc.h(self.qr[0]) self.qc.barrier(self.qr) self.qc.measure(self.qr,self.cr) try: job = execute(self.qc, backend=get_backend(device), noise_model=get_noise(noisy), shots=shots) except: job = execute(self.qc, backend=get_backend(device), shots=shots) stats = job.result().get_counts() if '1' in stats: p = stats['1']/shots else: p = 0 if mitigate: # if p is close to 0 or 1, just make it 0 or 1 if p<0.1: p = 0 elif p>0.9: p = 1 measured_value = ( p>random.random() ) self.prepare({basis:measured_value}) return measured_value def X_value (self,device='qasm_simulator',noisy=False,shots=1024,mitigate=True): """Extracts the boolean value via the X basis. For details of kwargs, see `value()`.""" return self.value('X',device=device,noisy=noisy,shots=shots,mitigate=mitigate) def Y_value (self,device='qasm_simulator',noisy=False,shots=1024,mitigate=True): """Extracts the boolean value via the X basis. For details of kwargs, see `value()`.""" return self.value('Y',device=device,noisy=noisy,shots=shots,mitigate=mitigate) def Z_value (self,device='qasm_simulator',noisy=False,shots=1024,mitigate=True): """Extracts the boolean value via the X basis. For details of kwargs, see `value()`.""" return self.value('Z',device=device,noisy=noisy,shots=shots,mitigate=mitigate) def bell_correlation (basis,device='qasm_simulator',noisy=False,shots=1024): """Prepares a rotated Bell state of two qubits. Measurement is done in the specified basis for each qubit. The fraction of results for which the two qubits agree is returned. basis = String specifying measurement bases. 'XX' denotes X measurement on each qubit, 'XZ' denotes X measurement on qubit 0 and Z on qubit 1, vice-versa for 'ZX', and 'ZZ' denotes 'Z' measurement on both. device = A string specifying a backend. The noisy behaviour from a real device will result in the correlations being less strong than in the ideal case. shots = Number of shots used when extracting results from the qubit. For shots=1, the returned value will randomly be 0 (if the results for the two qubits disagree) or 1 (if they agree). For large shots, the returned value will be probability for this random process. """ qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr,cr) qc.h( qr[0] ) qc.cx( qr[0], qr[1] ) qc.ry( np.pi/4, qr[1]) qc.h( qr[1] ) #qc.x( qr[0] ) #qc.z( qr[0] ) for j in range(2): if basis[j]=='X': qc.h(qr[j]) qc.barrier(qr) qc.measure(qr,cr) try: job = execute(qc, backend=get_backend(device), noise_model=get_noise(noisy), shots=shots, memory=True) except: job = execute(qc, backend=get_backend(device), shots=shots, memory=True) stats = job.result().get_counts() P = 0 for string in stats: p = stats[string]/shots if string in ['00','11']: P += p return {'P':P, 'samples':job.result().get_memory() } def bitstring_superposer (strings,bias=0.5,device='qasm_simulator',noisy=False,shots=1024): """Prepares the superposition of the two given n bit strings. The number of qubits used is equal to the length of the string. The superposition is measured, and the process repeated many times. A dictionary with the fraction of shots for which each string occurred is returned. string = List of two binary strings. If the list has more than two elements, all but the first two are ignored. device = A string specifying a backend. The noisy behaviour from a real device will result in strings other than the two supplied occuring with non-zero fraction. shots = Number of times the process is repeated to calculate the fractions. For shots=1, only a single randomnly generated bit string is return (as the key of a dict).""" # make it so that the input is a list of list of strings, even if it was just a list of strings strings_list = [] if type(strings[0])==str: strings_list = [strings] else: strings_list = strings batch = [] for strings in strings_list: # find the length of the longest string, and pad any that are shorter num = 0 for string in strings: num = max(len(string),num) for string in strings: string = '0'*(num-len(string)) + string qr = QuantumRegister(num) cr = ClassicalRegister(num) qc = QuantumCircuit(qr,cr) if len(strings)==2**num: # create equal superposition of all if all are asked for for n in range(num): qc.h(qr[n]) else: # create superposition of just two diff = [] for bit in range(num): if strings[0][bit]==strings[1][bit]: if strings[0][bit]=='1': qc.x(qr[bit]) if strings[0][bit]!=strings[1][bit]: diff.append(bit) if diff: frac = np.arccos(np.sqrt(bias))/(np.pi/2) qc.rx(np.pi*frac,qr[diff[0]]) for bit in diff[1:]: qc.cx(qr[diff[0]],qr[bit]) for bit in diff: if strings[0][bit]=='1': qc.x(qr[bit]) qc.barrier(qr) qc.measure(qr,cr) batch.append(qc) try: job = execute(batch, backend=get_backend(device), noise_model=get_noise(noisy), shots=shots) except: job = execute(batch, backend=get_backend(device), shots=shots) stats_raw_list = [] for j in range(len(strings_list)): stats_raw_list.append( job.result().get_counts(batch[j]) ) stats_list = [] for stats_raw in stats_raw_list: stats = {} for string in stats_raw: stats[string[::-1]] = stats_raw[string]/shots stats_list.append(stats) # if only one instance was given, output dict rather than list with a single dict if len(stats_list)==1: stats_list = stats_list[0] return stats_list def emoticon_superposer (emoticons,bias=0.5,device='qasm_simulator',noisy=False,shots=1024,figsize=(20,20),encoding=7): """Creates superposition of two emoticons. A dictionary is returned, which supplies the relative strength of each pair of ascii characters in the superposition. An image representing the superposition, with each pair of ascii characters appearing with an weight that represents their strength in the superposition, is also created. emoticons = A list of two strings, each of which is composed of two ascii characters, such as [ ";)" , "8)" ]. device = A string specifying a backend. The noisy behaviour from a real device will result in emoticons other than the two supplied occuring with non-zero strength. shots = Number of times the process is repeated to calculate the fractions used as strengths. For shots=1, only a single randomnly generated emoticon is return (as the key of the dict). emcoding = Number of bits used to encode ascii characters.""" # make it so that the input is a list of list of strings, even if it was just a list of strings if type(emoticons[0])==str: emoticons_list = [emoticons] else: emoticons_list = emoticons strings = [] for emoticons in emoticons_list: string = [] for emoticon in emoticons: bin4emoticon = "" for character in emoticon: bin4char = bin(ord(character))[2:] bin4char = (encoding-len(bin4char))*'0'+bin4char bin4emoticon += bin4char string.append(bin4emoticon) strings.append(string) stats = bitstring_superposer(strings,bias=bias,device=device,noisy=noisy,shots=shots) # make a list of dicts from stats if type(stats) is dict: stats_list = [stats] else: stats_list = stats ascii_stats_list = [] for stats in stats_list: fig = plt.figure() ax=fig.add_subplot(111) plt.rc('font', family='monospace') ascii_stats = {} for string in stats: char = chr(int( string[0:encoding] ,2)) # get string of the leftmost bits and convert to an ASCII character char += chr(int( string[encoding:2*encoding] ,2)) # do the same for string of rightmost bits, and add it to the previous character prob = stats[string] # fraction of shots for which this result occurred ascii_stats[char] = prob # create plot with all characters on top of each other with alpha given by how often it turned up in the output try: plt.annotate( char, (0.5,0.5), va="center", ha="center", color = (0,0,0, prob ), size = 300) except: pass ascii_stats_list.append(ascii_stats) plt.axis('off') plt.savefig('outputs/emoticon_'+datetime.datetime.now().strftime("%H:%M:%S %p on %B %d, %Y")+'.png') plt.show() # if only one instance was given, output dict rather than list with a single dict if len(ascii_stats_list)==1: ascii_stats_list = ascii_stats_list[0] return ascii_stats_list def _filename_superposer (all_files,files,bias,device,noisy,shots): """Takes a list of all possible filenames (all_files) as well as a pair to be superposed or list of such pairs (files) and superposes them for a given bias and number of shots on a given device. Output is a dictionary will filenames as keys and the corresponding fractions of shots as target.""" file_num = len(all_files) bit_num = int(np.ceil( np.log2(file_num) )) all_files += [None]*(2**bit_num-file_num) # make it so that the input is a list of list of strings, even if it was just a list of strings if type(files[0])==str: files_list = [files] else: files_list = files strings = [] for files in files_list: string = [] for file in files: bin4pic = "{0:b}".format(all_files.index(file)) bin4pic = '0'*(bit_num-len(bin4pic)) + bin4pic string.append( bin4pic ) strings.append(string) full_stats = bitstring_superposer(strings,bias=bias,device=device,noisy=noisy,shots=shots) # make a list of dicts from stats if type(full_stats) is dict: full_stats_list = [full_stats] else: full_stats_list = full_stats stats_list = [] for full_stats in full_stats_list: Z = 0 for j in range(file_num): string = "{0:b}".format(j) string = '0'*(bit_num-len(string)) + string if string in full_stats: Z += full_stats[string] stats = {} for j in range(file_num): string = "{0:b}".format(j) string = '0'*(bit_num-len(string)) + string if string in full_stats: stats[string] = full_stats[string]/Z stats_list.append(stats) file_stats_list = [] for stats in stats_list: file_stats = {} for string in stats: file_stats[ all_files[int(string,2)] ] = stats[string] file_stats_list.append(file_stats) return file_stats_list def image_superposer (all_images,images,bias=0.5,device='qasm_simulator',noisy=False,shots=1024,figsize=(20,20)): """Creates superposition of two images from a set of images. A dictionary is returned, which supplies the relative strength of each pair of ascii characters in the superposition. An image representing the superposition, with each of the original images appearing with an weight that represents their strength in the superposition, is also created. all_images = List of strings that are filenames for a set of images. The files should be located in 'images/<filename>.png relative to where the code is executed. images = List of strings for image files to be superposed. This can either contain the strings for two files, or for all in all_images. Other options are not currently supported. device = A string specifying a backend. The noisy behaviour from a real device will result in images other than those intended appearing with non-zero strength. shots = Number of times the process is repeated to calculate the fractions used as strengths.""" image_stats_list = _filename_superposer (all_images,images,bias,device,noisy,shots) print(image_stats_list) for image_stats in image_stats_list: # sort from least to most likely and create corresponding lists of the strings and fractions sorted_strings = sorted(image_stats,key=image_stats.get) sorted_fracs = sorted(image_stats.values()) n = len(image_stats) # construct alpha values such that the final image is a weighted average of the images specified by the keys of `image_stats` alpha = [ sorted_fracs[0] ] for j in range(0,n-1): alpha.append( ( alpha[j]/(1-alpha[j]) ) * ( sorted_fracs[j+1] / sorted_fracs[j] ) ) fig, ax = plt.subplots(figsize=figsize) for j in reversed(range(n)): filename = sorted_strings[j] if filename: image = plt.imread( "images/"+filename+".png" ) plt.imshow(image,alpha=alpha[j]) plt.axis('off') plt.savefig('outputs/image_'+datetime.datetime.now().strftime("%H:%M:%S %p on %B %d, %Y")+'.png') plt.show() # if only one instance was given, output dict rather than list with a single dict if len(image_stats_list)==1: image_stats_list = image_stats_list[0] return image_stats_list def audio_superposer (all_audio,audio,bias=0.5,device='qasm_simulator',noisy=False,shots=1024,format='wav'): audio_stats_list = _filename_superposer (all_audio,audio,bias,device,noisy,shots) for audio_stats in audio_stats_list: loudest = max(audio_stats, key=audio_stats.get) mixed = AudioSegment.from_wav('audio/'+loudest+'.'+format) for filename in audio_stats: if filename != loudest: dBFS = np.log10( audio_stats[filename]/audio_stats[loudest] ) file = AudioSegment.from_wav('audio/'+filename+'.'+format) - dBFS mixed = mixed.overlay(file) mixed.export('outputs/audio_'+'_'.join(audio)+'.'+format, format=format) return audio_stats_list class layout: """Processing and display of data in ways that depend on the layout of a quantum device.""" def __init__(self,device): """Given a device, specified by device = A string specifying a device, or a list of two integers to define a grid. the following attributes are determined. num = Number of qubits on the device. pairs = Dictionary detailing the pairs of qubits for which cnot gates can be directly implemented. Each value is a list of two qubits for which this is possible. The corresponding key is a string that is used as the name of the pair. pos = A dictionary of positions for qubits, to be used in plots. """ if device in ['ibmq_5_yorktown', 'ibmq_16_melbourne']: backend = get_backend(device) self.num = backend.configuration().n_qubits coupling = backend.configuration().coupling_map self.pairs = {} char = 65 for pair in coupling: self.pairs[chr(char)] = pair char += 1 if device in ['ibmq_5_yorktown']: self.pos = { 0: [1,1], 1: [1,0], 2: [0.5,0.5], 3: [0,0], 4: [0,1] } elif device=='ibmq_16_melbourne': self.pos = { 0: (0,1), 1: (1,1), 2: (2,1), 3: (3,1), 4: (4,1), 5: (5,1), 6: (6,1), 7: (7,0), 8: (6,0), 9: (5,0), 10: (4,0), 11: (3,0), 12: (2,0), 13: (1,0) } elif type(device) is list: Lx = device[0] Ly = device[1] self.num = Lx*Ly self.pairs = {} char = 65 for x in range(Lx-1): for y in range(Ly): n = x + y*Ly m = n+1 self.pairs[chr(char)] = [n,m] char += 1 for x in range(Lx): for y in range(Ly-1): n = x + y*Ly m = n+Ly self.pairs[chr(char)] = [n,m] char += 1 self.pos = {} for x in range(Lx): for y in range(Ly): n = x + y*Ly self.pos[n] = [x,y] else: print("Error: Device not recognized.\nMake sure it is a list of two integers (to specify a grid) or one of the supported IBM devices ('ibmqx2', 'ibmqx4' and 'ibmqx5').") for pair in self.pairs: self.pos[pair] = [(self.pos[self.pairs[pair][0]][j] + self.pos[self.pairs[pair][1]][j])/2 for j in range(2)] def calculate_probs(self,raw_stats): """Given a counts dictionary as the input `raw_stats`, a dictionary of probabilities is returned. The keys for these are either integers (referring to qubits) or strings (referring to pairs of neighbouring qubits). For the qubit entries, the corresponding value is the probability that the qubit is in state `1`. For the pair entries, the values are the probabilities that the two qubits disagree (so either the outcome `01` or `10`.""" Z = 0 for string in raw_stats: Z += raw_stats[string] stats = {} for string in raw_stats: stats[string] = raw_stats[string]/Z probs = {} for n in self.pos: probs[n] = 0 for string in stats: for n in range(self.num): if string[-n-1]=='1': probs[n] += stats[string] for pair in self.pairs: if string[-self.pairs[pair][0]-1]!=string[-self.pairs[pair][1]-1]: probs[pair] += stats[string] return probs def plot(self,probs={},labels={},colors={},sizes={}): """An image representing the device is created and displayed. When no kwargs are supplied, qubits are labelled according to their numbers. The pairs of qubits for which a cnot is possible are shown by lines connecting the qubitsm, and are labelled with letters. The kwargs should all be supplied in the form of dictionaries for which qubit numbers and pair labels are the keys (i.e., the same keys as for the `pos` attribute). If `probs` is supplied (such as from the output of the `calculate_probs()` method, the labels, colors and sizes of qubits and pairs will be determined by these probabilities. Otherwise, the other kwargs set these properties directly.""" G=nx.Graph() for pair in self.pairs: G.add_edge(self.pairs[pair][0],self.pairs[pair][1]) G.add_edge(self.pairs[pair][0],pair) G.add_edge(self.pairs[pair][1],pair) if probs: label_changes = copy.deepcopy(labels) color_changes = copy.deepcopy(colors) size_changes = copy.deepcopy(sizes) labels = {} colors = {} sizes = {} for node in G: if probs[node]>1: labels[node] = "" colors[node] = 'grey' sizes[node] = 3000 else: labels[node] = "%.0f" % ( 100 * ( probs[node] ) ) colors[node] =( 1-probs[node],0,probs[node] ) if type(node)!=str: if labels[node]=='0': sizes[node] = 3000 else: sizes[node] = 4000 else: if labels[node]=='0': sizes[node] = 800 else: sizes[node] = 1150 for node in label_changes: labels[node] = label_changes[node] for node in color_changes: colors[node] = color_changes[node] for node in size_changes: sizes[node] = size_changes[node] else: if not labels: labels = {} for node in G: labels[node] = node if not colors: colors = {} for node in G: if type(node) is int: colors[node] = (node/self.num,0,1-node/self.num) else: colors[node] = (0,0,0) if not sizes: sizes = {} for node in G: if type(node)!=str: sizes[node] = 3000 else: sizes[node] = 750 # convert to lists, which is required by nx color_list = [] size_list = [] for node in G: color_list.append(colors[node]) size_list.append(sizes[node]) area = [0,0] for coord in self.pos.values(): for j in range(2): area[j] = max(area[j],coord[j]) for j in range(2): area[j] = (area[j] + 1 )*1.1 if area[0]>2*area[1]: ratio = 0.65 else: ratio = 1 plt.figure(2,figsize=(2*area[0],2*ratio*area[1])) nx.draw(G, self.pos, node_color = color_list, node_size = size_list, labels = labels, with_labels = True, font_color ='w', font_size = 18) plt.show() class pauli_grid(): # Allows a quantum circuit to be created, modified and implemented, and visualizes the output in the style of 'Hello Quantum'. def __init__(self,device='qasm_simulator',noisy=False,shots=1024,mode='circle',y_boxes=False): """ device='qasm_simulator' Backend to be used by Qiskit to calculate expectation values (defaults to local simulator). shots=1024 Number of shots used to to calculate expectation values. mode='circle' Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line'). y_boxes=True Whether to display full grid that includes Y expectation values. """ self.backend = get_backend(device) self.noise_model = get_noise(noisy) self.shots = shots self.y_boxes = y_boxes if self.y_boxes: self.box = {'ZI':(-1, 2),'XI':(-3, 4),'IZ':( 1, 2),'IX':( 3, 4),'ZZ':( 0, 3),'ZX':( 2, 5),'XZ':(-2, 5),'XX':( 0, 7), 'YY':(0,5), 'YI':(-2,3), 'IY':(2,3), 'YZ':(-1,4), 'ZY':(1,4), 'YX':(1,6), 'XY':(-1,6) } else: self.box = {'ZI':(-1, 2),'XI':(-2, 3),'IZ':( 1, 2),'IX':( 2, 3),'ZZ':( 0, 3),'ZX':( 1, 4),'XZ':(-1, 4),'XX':( 0, 5)} self.rho = {} for pauli in self.box: self.rho[pauli] = 0.0 for pauli in ['ZI','IZ','ZZ']: self.rho[pauli] = 1.0 self.qr = QuantumRegister(2) self.cr = ClassicalRegister(2) self.qc = QuantumCircuit(self.qr, self.cr) self.mode = mode # colors are background, qubit circles and correlation circles, respectively if self.mode=='line': self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)] else: self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)] self.fig = plt.figure(figsize=(5,5),facecolor=self.colors[0]) self.ax = self.fig.add_subplot(111) plt.axis('off') self.bottom = self.ax.text(-3,1,"",size=9,va='top',color='w') self.lines = {} for pauli in self.box: w = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(1.0,1.0,1.0), lw=0 ) b = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(0.0,0.0,0.0), lw=0 ) c = {} c['w'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(0,0,0), zorder=10) ) c['b'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(1,1,1), zorder=10) ) self.lines[pauli] = {'w':w,'b':b,'c':c} def get_rho(self): # Runs the circuit specified by self.qc and determines the expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ' (and the ones with Ys too if needed). if self.y_boxes: corr = ['ZZ','ZX','XZ','XX','YY','YX','YZ','XY','ZY'] ps = ['X','Y','Z'] else: corr = ['ZZ','ZX','XZ','XX'] ps = ['X','Z'] results = {} for basis in corr: temp_qc = copy.deepcopy(self.qc) for j in range(2): if basis[j]=='X': temp_qc.h(self.qr[j]) elif basis[j]=='Y': temp_qc.sdg(self.qr[j]) temp_qc.h(self.qr[j]) temp_qc.barrier(self.qr) temp_qc.measure(self.qr,self.cr) try: job = execute(temp_qc, backend=self.backend, noise_model=self.noise_model, shots=self.shots) except: job = execute(temp_qc, backend=self.backend, shots=self.shots) results[basis] = job.result().get_counts() for string in results[basis]: results[basis][string] = results[basis][string]/self.shots prob = {} # prob of expectation value -1 for single qubit observables for j in range(2): for p in ps: pauli = {} for pp in ['I']+ps: pauli[pp] = (j==1)*pp + p + (j==0)*pp prob[pauli['I']] = 0 for ppp in ps: basis = pauli[ppp] for string in results[basis]: if string[(j+1)%2]=='1': prob[pauli['I']] += results[basis][string]/(2+self.y_boxes) # prob of expectation value -1 for two qubit observables for basis in corr: prob[basis] = 0 for string in results[basis]: if string[0]!=string[1]: prob[basis] += results[basis][string] for pauli in prob: self.rho[pauli] = 1-2*prob[pauli] def update_grid(self,rho=None,labels=False,bloch=None,hidden=[],qubit=True,corr=True,message=""): """ rho = None Dictionary of expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. If supplied, this will be visualized instead of the results of running self.qc. labels = False Determines whether basis labels are printed in the corresponding boxes. bloch = None If a qubit name is supplied, and if mode='line', Bloch circles are displayed for this qubit hidden = [] Which qubits have their circles hidden (empty list if both shown). qubit = True Whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles). corr = True Whether the correlation circles (the four in the middle) are shown. message A string of text that is displayed below the grid. """ def see_if_unhidden(pauli): # For a given Pauli, see whether its circle should be shown. unhidden = True # first: does it act non-trivially on a qubit in `hidden` for j in hidden: unhidden = unhidden and (pauli[j]=='I') # second: does it contain something other than 'I' or 'Z' when only bits are shown if qubit==False: for j in range(2): unhidden = unhidden and (pauli[j] in ['I','Z']) # third: is it a correlation pauli when these are not allowed if corr==False: unhidden = unhidden and ((pauli[0]=='I') or (pauli[1]=='I')) return unhidden def add_line(line,pauli_pos,pauli): """ For mode='line', add in the line. line = the type of line to be drawn (X, Z or the other one) pauli = the box where the line is to be drawn expect = the expectation value that determines its length """ unhidden = see_if_unhidden(pauli) coord = None p = (1-self.rho[pauli])/2 # prob of 1 output # in the following, white lines goes from a to b, and black from b to c if unhidden: if line=='Z': a = ( self.box[pauli_pos][0], self.box[pauli_pos][1]+l/2 ) c = ( self.box[pauli_pos][0], self.box[pauli_pos][1]-l/2 ) b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] ) lw = 8 coord = (b[1] - (a[1]+c[1])/2)*1.2 + (a[1]+c[1])/2 elif line=='X': a = ( self.box[pauli_pos][0]+l/2, self.box[pauli_pos][1] ) c = ( self.box[pauli_pos][0]-l/2, self.box[pauli_pos][1] ) b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] ) lw = 9 coord = (b[0] - (a[0]+c[0])/2)*1.1 + (a[0]+c[0])/2 else: a = ( self.box[pauli_pos][0]+l/(2*np.sqrt(2)), self.box[pauli_pos][1]+l/(2*np.sqrt(2)) ) c = ( self.box[pauli_pos][0]-l/(2*np.sqrt(2)), self.box[pauli_pos][1]-l/(2*np.sqrt(2)) ) b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] ) lw = 9 self.lines[pauli]['w'].pop(0).remove() self.lines[pauli]['b'].pop(0).remove() self.lines[pauli]['w'] = plt.plot( [a[0],b[0]], [a[1],b[1]], color=(1.0,1.0,1.0), lw=lw ) self.lines[pauli]['b'] = plt.plot( [b[0],c[0]], [b[1],c[1]], color=(0.0,0.0,0.0), lw=lw ) return coord l = 0.9 # line length r = 0.6 # circle radius L = 0.98*np.sqrt(2) # box height and width if rho==None: self.get_rho() # draw boxes for pauli in self.box: if 'I' in pauli: color = self.colors[1] else: color = self.colors[2] self.ax.add_patch( Rectangle( (self.box[pauli][0],self.box[pauli][1]-1), L, L, angle=45, color=color) ) # draw circles for pauli in self.box: unhidden = see_if_unhidden(pauli) if unhidden: if self.mode=='line': self.ax.add_patch( Circle(self.box[pauli], r, color=(0.5,0.5,0.5)) ) else: prob = (1-self.rho[pauli])/2 self.ax.add_patch( Circle(self.box[pauli], r, color=(prob,prob,prob)) ) # update bars if required if self.mode=='line': if bloch in ['0','1']: for other in 'IXZ': px = other*(bloch=='1') + 'X' + other*(bloch=='0') pz = other*(bloch=='1') + 'Z' + other*(bloch=='0') z_coord = add_line('Z',pz,pz) x_coord = add_line('X',pz,px) for j in self.lines[pz]['c']: self.lines[pz]['c'][j].center = (x_coord,z_coord) self.lines[pz]['c'][j].radius = (j=='w')*0.05 + (j=='b')*0.04 px = 'I'*(bloch=='0') + 'X' + 'I'*(bloch=='1') pz = 'I'*(bloch=='0') + 'Z' + 'I'*(bloch=='1') add_line('Z',pz,pz) add_line('X',px,px) else: for pauli in self.box: for j in self.lines[pauli]['c']: self.lines[pauli]['c'][j].radius = 0.0 if pauli in ['ZI','IZ','ZZ']: add_line('Z',pauli,pauli) if pauli in ['XI','IX','XX']: add_line('X',pauli,pauli) if pauli in ['XZ','ZX']: add_line('ZX',pauli,pauli) self.bottom.set_text(message) if labels: for pauli in self.box: plt.text(self.box[pauli][0]-0.18,self.box[pauli][1]-0.85, pauli) if self.y_boxes: self.ax.set_xlim([-4,4]) self.ax.set_ylim([0,8]) else: self.ax.set_xlim([-3,3]) self.ax.set_ylim([0,6]) self.fig.canvas.draw() class qrng (): """This object generations `num` strings, each of `precision=8192/num` bits. These are then dispensed one-by-one as random integers, floats, etc, depending on the method called. Once all `num` strings are used, it'll loop back around.""" def __init__( self, precision=None, num = 1280, sim=True, noisy=False, noise_only=False, verbose=True ): if precision: self.precision = precision self.num = int(np.floor( 5*8192/self.precision )) else: self.num = num self.precision = int(np.floor( 5*8192/self.num )) q = QuantumRegister(5) c = ClassicalRegister(5) qc = QuantumCircuit(q,c) if not noise_only: qc.h(q) qc.measure(q,c) if sim: backend = get_backend('qasm_simulator') else: backend = get_backend('ibmq_5_yorktown') if verbose and not sim: print('Sending job to quantum device') try: job = execute(qc,backend,shots=8192,noise_model=get_noise(noisy),memory=True) except: job = execute(qc,backend,shots=8192,memory=True) data = job.result().get_memory() if verbose and not sim: print('Results from device received') full_data = [] for datum in data: full_data += list(datum) self.int_list = [] self.bit_list = [] n = 0 for _ in range(num): bitstring = '' for b in range(self.precision): bitstring += full_data[n] n += 1 self.bit_list.append(bitstring) self.int_list.append( int(bitstring,2) ) self.n = 0 def _iterate(self): self.n = self.n+1 % self.num def rand_int(self): # get a random integer rand_int = self.int_list[self.n] self._iterate() return rand_int def rand(self): # get a random float rand_float = self.int_list[self.n] / 2**self.precision self._iterate() return rand_float class random_grid (): """Creates an Lx by Ly grid of random bit values""" def __init__(self,Lx,Ly,coord_map=None): self.Lx = Lx self.Ly = Ly self.coord_map = coord_map self.qr = QuantumRegister(Lx*Ly) self.cr = ClassicalRegister(Lx*Ly) self.qc = QuantumCircuit(self.qr,self.cr) def address(self,x,y): # returns the index for the qubit associated with grid point (x,y) # if self.coord_map: address = coord_map( (x,y) ) else: address = y*self.Lx + x return address def neighbours(self,coords): # determines a list of coordinates that neighbour the input coords (x,y) = coords neighbours = [] for (xx,yy) in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]: if (xx>=0) and (xx<=self.Lx-1) and (yy>=0) and (yy<=self.Ly-1): neighbours.append( (xx,yy) ) return neighbours def get_samples(self,device='qasm_simulator',noisy=False,shots=1024): # run the program and get samples def separate_string(string): string = string[::-1] grid = [] for y in range(self.Ly): line = '' for x in range(self.Lx): line += string[self.address(x,y)] grid.append(line) return '\n'.join(grid) temp_qc = copy.deepcopy(self.qc) temp_qc.barrier(self.qr) temp_qc.measure(self.qr,self.cr) # different backends require different executions, and this block somehow works try: job = execute(temp_qc,backend=get_backend(device),noise_model=get_noise(noisy),shots=shots,memory=True) except: try: if device=='ibmq_qasm_simulator': raise backend=get_backend(device) qobj = compile(temp_qc,backend,pass_manager=PassManager()) job = backend.run(qobj) except: job = execute(temp_qc,backend=get_backend(device),shots=shots,memory=True) stats = job.result().get_counts() grid_stats = {} for string in stats: grid_stats[separate_string(string)] = stats[string] try: # real memory data = job.result().get_memory() grid_data = [] for string in data: grid_data.append(separate_string(string)) except: # fake memory from stats grid_data = [] for string in grid_stats: grid_data += [string]*grid_stats[string] return grid_stats, grid_data def NOT (self,coords,frac=1,axis='x'): '''Implement an rx or ry on the qubit for the given coords, according to the given fraction (`frac=1` is a NOT gate) and the given axis ('x' or 'y').''' if axis=='x': self.qc.rx(np.pi*frac,self.qr[self.address(coords[0],coords[1])]) else: self.qc.ry(np.pi*frac,self.qr[self.address(coords[0],coords[1])]) def CNOT (self,ctl,tgt,frac=1,axis='x'): '''Controlled version of the `NOT` above''' if axis=='y': self.qc.sdg(self.qr[self.address(tgt[0],tgt[1])]) self.qc.h(self.qr[self.address(tgt[0],tgt[1])]) self.qc.crz(np.pi*frac,self.qr[self.address(ctl[0],ctl[1])],self.qr[self.address(tgt[0],tgt[1])]) self.qc.h(self.qr[self.address(tgt[0],tgt[1])]) if axis=='y': self.qc.s(self.qr[self.address(tgt[0],tgt[1])]) class random_mountain(): '''Create a random set of (x,y,z) coordinates that look something like a mountain''' def __init__(self,n): # initializes the quantum circuit of n qubits used to generate the n points self.n = n self.qr = QuantumRegister(n) self.cr = ClassicalRegister(n) self.qc = QuantumCircuit(self.qr,self.cr) def get_mountain(self,new_data=True,method='square',device='qasm_simulator',noisy=False,shots=None): # run based on the current circuit performed on self.qc if shots==None: shots = 2**(2*self.n) if new_data: temp_qc = copy.deepcopy(self.qc) temp_qc.measure(self.qr,self.cr) job = execute(temp_qc, backend=get_backend(device),noise_model=get_noise(noisy),shots=shots) stats = job.result().get_counts() self.prob = {} for string in ['0'*(self.n-len(bin(j)[2:])) + bin(j)[2:] for j in range(2**self.n)]: # loop over all n-bit strings try: self.prob[string] = stats[string]/shots except: self.prob[string] = 0 nodes = sorted(self.prob, key=self.prob.get)[::-1] Z = {} for node in nodes: Z[node] = max(self.prob[node],1/shots) if method=='rings': pos = {} for node in nodes: distance = 0 for j in range(self.n): distance += (node[j]!=nodes[0][j])/self.n theta = random.random()*2*np.pi pos[node] = (distance*np.cos(theta),distance*np.sin(theta)) else: Lx = int(2**np.ceil(self.n/2)) Ly = int(2**np.floor(self.n/2)) strings = [ ['' for k in range(Lx)] for j in range(Ly)] for y in range(Ly): for x in range(Lx): for j in range(self.n): if (j%2)==0: xx = np.floor(x/2**(j/2)) strings[y][x] = str( int( ( xx + np.floor(xx/2) )%2 ) ) + strings[y][x] else: yy = np.floor(y/2**((j-1)/2)) strings[y][x] = str( int( ( yy + np.floor(yy/2) )%2 ) ) + strings[y][x] center = strings[int(np.floor(Ly/2))][int(np.floor(Lx/2))] maxstring = nodes[0] diff = '' for j in range(self.n): diff += '0'*(center[j]==maxstring[j]) + '1'*(center[j]!=maxstring[j]) for y in range(Ly): for x in range(Lx): newstring = '' for j in range(self.n): newstring += strings[y][x][j]*(diff[j]=='0') + ('0'*(strings[y][x][j]=='1')+'1'*(strings[y][x][j]=='0'))*(diff[j]=='1') strings[y][x] = newstring pos = {} for y in range(Ly): for x in range(Lx): pos[strings[y][x]] = (x,y) return pos,Z
https://github.com/JouziP/MQITE
JouziP
from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram # simulate in statevector_simulator def simulateStatevector(circuit): backend = Aer.get_backend('statevector_simulator') result = execute(circuit.remove_final_measurements(inplace=False), backend, shots=1).result() counts = result.get_counts() return result.get_statevector(circuit) # return plot_histogram(counts, color='midnightblue', title="StateVector Histogram") # simulate in qasm_simulator def simulateQasm(circuit, count=1024): backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend, shots=count).result() counts = result.get_counts() return plot_histogram(counts, color='midnightblue', title="Qasm Histogram")
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/qiskit-community/qiskit-translations-staging
qiskit-community
# Useful additional packages import matplotlib.pyplot as plt import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer backend = BasicAer.get_backend('unitary_simulator') q = QuantumRegister(1) qc = QuantumCircuit(q) qc.u(pi/2,pi/4,pi/8,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.p(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.id(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.x(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.y(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.z(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.h(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.s(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.sdg(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.t(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.tdg(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.rx(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ry(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.rz(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cx(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cy(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cz(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ch(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.crz(pi/2,q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cp(pi/2,q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cu(pi/2, pi/2, pi/2, 0, q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.swap(q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.ccx(q[0], q[1], q[2]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cswap(q[0], q[1], q[2]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.measure(q, c) qc.draw() backend = BasicAer.get_backend('qasm_simulator') job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.reset(q[0]) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.reset(q[0]) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.x(q[0]).c_if(c, 0) qc.measure(q,c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q,c) qc.x(q[0]).c_if(c, 0) qc.measure(q,c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) # Initializing a three-qubit quantum state import math desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0] q = QuantumRegister(3) qc = QuantumCircuit(q) qc.initialize(desired_vector, [q[0],q[1],q[2]]) qc.draw() backend = BasicAer.get_backend('statevector_simulator') job = backend.run(transpile(qc, backend)) qc_state = job.result().get_statevector(qc) qc_state state_fidelity(desired_vector,qc_state) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/arthurfaria/Qiskit_certificate_prep
arthurfaria
from qiskit import IBMQ, BasicAer, QuantumCircuit, execute import qiskit.tools.jupyter from qiskit.tools import job_monitor from qiskit.visualization import plot_gate_map, plot_error_map from qiskit.providers.ibmq import least_busy provider = IBMQ.load_account() %qiskit_version_table print(qiskit.__qiskit_version__) ## qiskit terra version print(qiskit.__version__) %qiskit_copyright BasicAer.backends() # It works also for other simulators such as: Aer.backends() %qiskit_backend_overview backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and not b.configuration().simulator and b.status().operational==True)) print(backend) # Plot gate map plot_gate_map(backend, plot_directed = True) # Plot error map plot_error_map(backend) qc_open = QuantumCircuit.from_qasm_file('myfile.qasm') qc_open.draw('mpl') temp = QuantumCircuit(2) temp.h(0) temp.h(1) temp.s(0) temp.s(1) qasm_str = temp.qasm() #returning a qasm string, THIS SIMPLE qasm_str qc_open1 = QuantumCircuit.from_qasm_str(qasm_str) qc_open1 == qc_open %qiskit_job_watcher backend_sim = BasicAer.get_backend('qasm_simulator') job = execute(qc_open1, backend_sim, shots = 1024) job_monitor(job) # or job.status()
https://github.com/lkcoredo/qiskitWorkshop
lkcoredo
#initialization import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, assemble, transpile from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.providers.ibmq import least_busy # import basic plot tools from qiskit.visualization import plot_histogram n = 2 grover_circuit = QuantumCircuit(n) def initialize_s(qc, qubits): """Apply a H-gate to 'qubits' in qc""" for q in qubits: qc.h(q) return qc def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "U$_s$" return U_s grover_circuit = initialize_s(grover_circuit, [0,1]) grover_circuit.draw(output="mpl") grover_circuit.cz(0,1) # Oracle grover_circuit.draw(output="mpl") # Diffusion operator (U_s) grover_circuit.append(diffuser(n),[0,1]) grover_circuit.draw(output="mpl") sim = Aer.get_backend('aer_simulator') # we need to make a copy of the circuit with the 'save_statevector' # instruction to run on the Aer simulator grover_circuit_sim = grover_circuit.copy() grover_circuit_sim.save_statevector() qobj = assemble(grover_circuit_sim) result = sim.run(qobj).result() statevec = result.get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") grover_circuit.measure_all() aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(grover_circuit) result = aer_sim.run(qobj).result() counts = result.get_counts() plot_histogram(counts) nqubits = 4 qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) qc.barrier() # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) qc.barrier() # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) qc.draw(output="mpl") from qiskit.circuit import classical_function, Int1 # define a classical function f(x): this returns 1 for the solutions of the problem # in this case, the solutions are 1010 and 1100 @classical_function def f(x1: Int1, x2: Int1, x3: Int1, x4: Int1) -> Int1: return (x1 and not x2 and x3 and not x4) or (x1 and x2 and not x3 and not x4) nqubits = 4 Uf = f.synth() # turn it into a circuit oracle = QuantumCircuit(nqubits+1) oracle.compose(Uf, inplace=True) oracle.draw(output="mpl") # We will return the diffuser as a gate #U_f = oracle.to_gate() # U_f.name = "U$_f$" # return U_f
https://github.com/Glebegor/Quantum-programming-algorithms
Glebegor
import time from qiskit_ibm_runtime import QiskitRuntimeService import qiskit import qiskit_ibm_runtime import qiskit_aer import numpy as np import random as rand import os # Projecting Quantum class class Quantum: def __init__(self, gStack, qbCount): self.id = 0 self.qiskitVersion = qiskit.__version__ self.imagesPath = "./Images" # Folder to Images self.loggerPath = "./Logger" # Folder to Loggs self.gatesStack = gStack # Stack of the gates self.qubitsCount = qbCount # count of the qubits # Registers self.regQ = qiskit.QuantumRegister(self.qubitsCount, "QRegister") # Quantum self.regC = qiskit.ClassicalRegister(self.qubitsCount, "CRegister") # Classic self.circuit = qiskit.QuantumCircuit(self.regQ, self.regC) # Circuit self.gates = ["h", "x", "z", "ry", "cx", "cu3", "ccx"] # Ibm connection def connIBMService(self): QiskitRuntimeService.save_account( channel="channel", name="name", token="token", set_as_default=True ) return QiskitRuntimeService() def connectBack(self, serviceIBM): print(serviceIBM) return serviceIBM.backend("quantum device") # Logic def findId(self): self.id += 1 return time.ctime().replace(" ", "_").replace(":", "-") + "_" + str(self.id) def saveImage(self, name): self.circuit.draw(output='mpl', filename=self.imagesPath + "/" + name) def loggCircuit(self, name): file_path = os.path.join(self.loggerPath, f"{name}.txt") fd = os.open(file_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o666) try: with os.fdopen(fd, 'w') as openedFile: for el in self.gatesStack: newRow = "" for row in el: newRow += str(row) + ", " openedFile.write(newRow + '\n') # Add a newline after each row for better readability except Exception as e: raise e def isInCircuit(self, qubitIdList): for qubitId in qubitIdList: if not (qubitId > 0 and qubitId < self.qubitsCount): return False return True # Using of the gates def useGate(self, gateElement): gate = gateElement[0] if (gate == "h"): if len(gateElement) != 2: print("Gate h has 1 param.") return self.isInCircuit(gateElement[1:]) self.circuit.h(self.regQ[gateElement[1]]) # ("h", 1,) elif (gate == "x"): if len(gateElement) != 2: print("Gate x has 1 param.") return self.isInCircuit(gateElement[1:]) self.circuit.h(self.regQ[gateElement[1]]) # ("x", 1,) elif (gate == "z"): if len(gateElement) != 2: print("Gate z has 1 param.") return self.isInCircuit(gateElement[1:]) self.circuit.h(self.regQ[gateElement[1]]) # ("z", 1,) elif (gate == "ry"): if len(gateElement) != 3: print("Gate ry has 2 params.") return self.isInCircuit(gateElement[1:2]) self.circuit.ry(2*gateElement[2], self.regQ[gateElement[1]]) # ("ry", 1, 45) elif (gate == "cx"): if len(gateElement) != 3: print("Gate cx has 2 params.") return self.isInCircuit(gateElement[1:3]) self.circuit.cx(self.regQ[gateElement[1]], self.regQ[gateElement[2]]) # ("cx", 1, 2) elif (gate == "cu3"): if len(gateElement) != 4: print("Gate cu3 has 3 params.") return self.isInCircuit(gateElement[1:3]) self.circuit.cu3(self.regQ[gateElement[3]], 0, 0, self.regQ[gateElement[1]], self.regQ[gateElement[2]]) # ("cu3", 1, 2, 45) elif (gate == "ccx"): if len(gateElement) != 4: print("Gate ccx has 3 params.") return self.isInCircuit(gateElement[1:4]) self.circuit.ccx(self.regQ[gateElement[1]], self.regQ[gateElement[2]], self.regQ[gateElement[3]]) # ("ccx", 1, 2, 3) else: print("Doesn't found gate: " + gate) return None return gate def run(self): self.regQ = qiskit.QuantumRegister(self.qubitsCount, "QRegister") # Quantum self.regC = qiskit.ClassicalRegister(self.qubitsCount, "CRegister") # Classic self.circuit = qiskit.QuantumCircuit(self.regQ, self.regC) for el in self.gatesStack: result = self.useGate(el) if result == None: return else: # print("Operator - " + result + " - used.") pass self.build() def build(self): self.circuit.measure(self.regQ, self.regC) print("Circuit was measured.") idOfJob = self.findId() print("Created job: " + idOfJob) self.saveImage(idOfJob) self.loggCircuit(idOfJob) job = qiskit_aer.AerSimulator(method='automatic').run(self.circuit, shots=1024) # get the result counts = job.result().get_counts(self.circuit) print(counts) def setupNewStack(self, newGatesStack): self.gatesStack = newGatesStack stackOfGates = [["h", 1],["h", 2],["h", 3],["ccx", 4, 1, 2]] quantum = Quantum(stackOfGates, 5) quantum.run() quantum.setupNewStack([["h", 1],["h", 2],["h", 2],["ccx", 0, 1, 4]]) quantum.run() quantum.run()
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ 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() a = 5 print(a) import numpy as np print(np.pi) print(np.random.randint(10)) from numpy.random import randint randint(10) a = -5 # Integers print(a) b = 16.001 # Floating point numbers print(b) c = 1+3j # Complex numbers print(c) list1 = [1,2,3,4] # A list of integers print(list1) print(len(list1)) # The number of elements list2 = [] # Square brackets initialises an empty list list2.append(10) # Append an element to the end of a list print(list2) print(list1[3]) # Accessing an element using square brackets. Indices start from 0 list1.remove(3) # Remove the element 3 print(list1) string1 = "Hello, World!" # Single or double quotes print(string1) print(string1[6:]) # Strings behave like a list of characters counts = { # Dictionaries are key-value pairs '00': 200, '10': 150, '01': 200, '11': 250 } counts.keys() # Get all the keys counts.values() # Get all the values counts.items() val = 10 if (val < 10): print("less than 10") else: print('10 or more') for i in range(0,11,2): # Range creates a list print(i) for num in [10,5,2,4]: print(num) for key, value in counts.items(): print(key, value) def foo(x): print(x) foo('hello') foo(10) def square(x): return x**2 square(4)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/sooodos/Quantum-Computing-Learning-Gate
sooodos
from qiskit import execute, Aer, QuantumCircuit, IBMQ class ThreeQubitSuperposition: @classmethod def run(cls): # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(3, 3) # Add a H gate on qubit 0 circuit.h(0) circuit.h(1) circuit.h(2) # Map the quantum measurement to the classical bits for i in range(3): circuit.measure(i, i) # Execute the circuit on the qasm simulator job = execute(circuit, simulator, shots=1024) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(circuit) print("\nTotal count all possible states are:", counts) provider = IBMQ.load_account() backend = provider.backends.ibmq_valencia # Execute the circuit on a real device job = execute(circuit, backend=backend, shots=1024) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(circuit) print("\nTotal count for all possible states are:", counts) # Draw the circuit print(circuit)
https://github.com/AnshDabkara/Qiskit_Algorithm
AnshDabkara
from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute, assemble, QuantumRegister, ClassicalRegister from qiskit.tools.monitor import job_monitor import matplotlib as mpl # import basic plot tools from qiskit.visualization import plot_histogram, plot_bloch_multivector import numpy as np from numpy import pi # Initializing the Qubits ql = QuantumRegister(3, name="ql") # logic qubits qa = QuantumRegister(2, name="qa") # Ancilla qubits mea = ClassicalRegister(3, name="mea") syn = ClassicalRegister(2, name="syn") qec_circuit = QuantumCircuit(ql,qa,mea,syn) # Encoding qec_circuit.clear() qec_circuit.cx(0,1) qec_circuit.cx(0,2) qec_circuit.barrier() # Bit flip error n = np.random.randint(3) qec_circuit.x(n) qec_circuit.barrier() # Syndrome Circuit qec_circuit.cx(0,3) qec_circuit.cx(1,3) qec_circuit.cx(0,4) qec_circuit.cx(2,4) qec_circuit.barrier() qec_circuit.measure(qa,syn) # Recovery cirucit qec_circuit.barrier() qec_circuit.mct([3,4],0) qec_circuit.x(4) qec_circuit.mct([3,4],1) qec_circuit.x(4) qec_circuit.x(3) qec_circuit.mct([3,4],2) qec_circuit.x(3) qec_circuit.barrier() # Decoding circuit qec_circuit.cx(0,2) qec_circuit.cx(0,1) qec_circuit.barrier() # measurement qec_circuit.measure(ql,mea) qec_circuit.draw("mpl") qec_circuit.draw('mpl') aer_sim = Aer.get_backend('aer_simulator') shots = 1024 t_qec = execute(qec_circuit, aer_sim, shots=shots).result() counts = t_qec.get_counts() plot_histogram(counts)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """Multiple-Control, Multiple-Target Gate.""" from __future__ import annotations from collections.abc import Callable from qiskit import circuit from qiskit.circuit import ControlledGate, Gate, Qubit, QuantumRegister, QuantumCircuit from qiskit.exceptions import QiskitError from ..standard_gates import XGate, YGate, ZGate, HGate, TGate, TdgGate, SGate, SdgGate class MCMT(QuantumCircuit): """The multi-controlled multi-target gate, for an arbitrary singly controlled target gate. For example, the H gate controlled on 3 qubits and acting on 2 target qubit is represented as: .. parsed-literal:: ───■──── │ ───■──── │ ───■──── ┌──┴───┐ ┤0 ├ │ 2-H │ ┤1 ├ └──────┘ This default implementations requires no ancilla qubits, by broadcasting the target gate to the number of target qubits and using Qiskit's generic control routine to control the broadcasted target on the control qubits. If ancilla qubits are available, a more efficient variant using the so-called V-chain decomposition can be used. This is implemented in :class:`~qiskit.circuit.library.MCMTVChain`. """ def __init__( self, gate: Gate | Callable[[QuantumCircuit, Qubit, Qubit], circuit.Instruction], num_ctrl_qubits: int, num_target_qubits: int, ) -> None: """Create a new multi-control multi-target gate. Args: gate: The gate to be applied controlled on the control qubits and applied to the target qubits. Can be either a Gate or a circuit method. If it is a callable, it will be casted to a Gate. num_ctrl_qubits: The number of control qubits. num_target_qubits: The number of target qubits. Raises: AttributeError: If the gate cannot be casted to a controlled gate. AttributeError: If the number of controls or targets is 0. """ if num_ctrl_qubits == 0 or num_target_qubits == 0: raise AttributeError("Need at least one control and one target qubit.") # set the internal properties and determine the number of qubits self.gate = self._identify_gate(gate) self.num_ctrl_qubits = num_ctrl_qubits self.num_target_qubits = num_target_qubits num_qubits = num_ctrl_qubits + num_target_qubits + self.num_ancilla_qubits # initialize the circuit object super().__init__(num_qubits, name="mcmt") self._label = f"{num_target_qubits}-{self.gate.name.capitalize()}" # build the circuit self._build() def _build(self): """Define the MCMT gate without ancillas.""" if self.num_target_qubits == 1: # no broadcasting needed (makes for better circuit diagrams) broadcasted_gate = self.gate else: broadcasted = QuantumCircuit(self.num_target_qubits, name=self._label) for target in list(range(self.num_target_qubits)): broadcasted.append(self.gate, [target], []) broadcasted_gate = broadcasted.to_gate() mcmt_gate = broadcasted_gate.control(self.num_ctrl_qubits) self.append(mcmt_gate, self.qubits, []) @property def num_ancilla_qubits(self): """Return the number of ancillas.""" return 0 def _identify_gate(self, gate): """Case the gate input to a gate.""" valid_gates = { "ch": HGate(), "cx": XGate(), "cy": YGate(), "cz": ZGate(), "h": HGate(), "s": SGate(), "sdg": SdgGate(), "x": XGate(), "y": YGate(), "z": ZGate(), "t": TGate(), "tdg": TdgGate(), } if isinstance(gate, ControlledGate): base_gate = gate.base_gate elif isinstance(gate, Gate): if gate.num_qubits != 1: raise AttributeError("Base gate must act on one qubit only.") base_gate = gate elif isinstance(gate, QuantumCircuit): if gate.num_qubits != 1: raise AttributeError( "The circuit you specified as control gate can only have one qubit!" ) base_gate = gate.to_gate() # raises error if circuit contains non-unitary instructions else: if callable(gate): # identify via name of the passed function name = gate.__name__ elif isinstance(gate, str): name = gate else: raise AttributeError(f"Invalid gate specified: {gate}") base_gate = valid_gates[name] return base_gate def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return the controlled version of the MCMT circuit.""" if ctrl_state is None: # TODO add ctrl state implementation by adding X gates return MCMT(self.gate, self.num_ctrl_qubits + num_ctrl_qubits, self.num_target_qubits) return super().control(num_ctrl_qubits, label, ctrl_state) def inverse(self): """Return the inverse MCMT circuit, which is itself.""" return MCMT(self.gate, self.num_ctrl_qubits, self.num_target_qubits) class MCMTVChain(MCMT): """The MCMT implementation using the CCX V-chain. This implementation requires ancillas but is decomposed into a much shallower circuit than the default implementation in :class:`~qiskit.circuit.library.MCMT`. **Expanded Circuit:** .. plot:: from qiskit.circuit.library import MCMTVChain, ZGate from qiskit.tools.jupyter.library import _generate_circuit_library_visualization circuit = MCMTVChain(ZGate(), 2, 2) _generate_circuit_library_visualization(circuit.decompose()) **Examples:** >>> from qiskit.circuit.library import HGate >>> MCMTVChain(HGate(), 3, 2).draw() q_0: ──■────────────────────────■── │ │ q_1: ──■────────────────────────■── │ │ q_2: ──┼────■──────────────■────┼── │ │ ┌───┐ │ │ q_3: ──┼────┼──┤ H ├───────┼────┼── │ │ └─┬─┘┌───┐ │ │ q_4: ──┼────┼────┼──┤ H ├──┼────┼── ┌─┴─┐ │ │ └─┬─┘ │ ┌─┴─┐ q_5: ┤ X ├──■────┼────┼────■──┤ X ├ └───┘┌─┴─┐ │ │ ┌─┴─┐└───┘ q_6: ─────┤ X ├──■────■──┤ X ├───── └───┘ └───┘ """ def _build(self): """Define the MCMT gate.""" control_qubits = self.qubits[: self.num_ctrl_qubits] target_qubits = self.qubits[ self.num_ctrl_qubits : self.num_ctrl_qubits + self.num_target_qubits ] ancilla_qubits = self.qubits[self.num_ctrl_qubits + self.num_target_qubits :] if len(ancilla_qubits) > 0: master_control = ancilla_qubits[-1] else: master_control = control_qubits[0] self._ccx_v_chain_rule(control_qubits, ancilla_qubits, reverse=False) for qubit in target_qubits: self.append(self.gate.control(), [master_control, qubit], []) self._ccx_v_chain_rule(control_qubits, ancilla_qubits, reverse=True) @property def num_ancilla_qubits(self): """Return the number of ancilla qubits required.""" return max(0, self.num_ctrl_qubits - 1) def _ccx_v_chain_rule( self, control_qubits: QuantumRegister | list[Qubit], ancilla_qubits: QuantumRegister | list[Qubit], reverse: bool = False, ) -> None: """Get the rule for the CCX V-chain. The CCX V-chain progressively computes the CCX of the control qubits and puts the final result in the last ancillary qubit. Args: control_qubits: The control qubits. ancilla_qubits: The ancilla qubits. reverse: If True, compute the chain down to the qubit. If False, compute upwards. Returns: The rule for the (reversed) CCX V-chain. Raises: QiskitError: If an insufficient number of ancilla qubits was provided. """ if len(ancilla_qubits) == 0: return if len(ancilla_qubits) < len(control_qubits) - 1: raise QiskitError("Insufficient number of ancilla qubits.") iterations = list(enumerate(range(2, len(control_qubits)))) if not reverse: self.ccx(control_qubits[0], control_qubits[1], ancilla_qubits[0]) for i, j in iterations: self.ccx(control_qubits[j], ancilla_qubits[i], ancilla_qubits[i + 1]) else: for i, j in reversed(iterations): self.ccx(control_qubits[j], ancilla_qubits[i], ancilla_qubits[i + 1]) self.ccx(control_qubits[0], control_qubits[1], ancilla_qubits[0]) def inverse(self): return MCMTVChain(self.gate, self.num_ctrl_qubits, self.num_target_qubits)
https://github.com/ShabaniLab/qiskit-hackaton-2019
ShabaniLab
import numpy as np from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from ising_kitaev import initialize_chain, run_adiabatic_zeeman_change, rotate_to_measurement_basis, add_measurement zeeman_ferro = 0.01 zeeman_para = 10 initial_config = np.array([zeeman_ferro, zeeman_ferro, zeeman_ferro, zeeman_ferro]) final_config = np.array([zeeman_para, zeeman_ferro, zeeman_ferro, zeeman_ferro]) qreg = QuantumRegister(4) creg = ClassicalRegister(3) qcirc = QuantumCircuit(qreg, creg) initialize_chain(qcirc, qreg, initial_config, 'logical_one') qcirc.draw() run_adiabatic_zeeman_change(qcirc, qreg, initial_config, final_config, 0, 0.25, 0.25, 2, 20) qcirc.depth() rotate_to_measurement_basis(qcirc, qreg, [1, 2, 3]) add_measurement(qcirc, qreg, creg, [1, 2, 3]) from qiskit import Aer, execute backend = Aer.get_backend('qasm_simulator') job = execute(qcirc, backend, shots=2000) job.status() result = job.result() print(result.get_counts())
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
MonitSharma
import pennylane as qml from pennylane import numpy as np from matplotlib import pyplot as plt # set the random seed np.random.seed(42) # create a device to execute the circuit on dev = qml.device("default.qubit", wires=3) @qml.qnode(dev, diff_method="parameter-shift") def circuit(params): qml.RX(params[0], wires=0) qml.RY(params[1], wires=1) qml.RZ(params[2], wires=2) qml.broadcast(qml.CNOT, wires=[0, 1, 2], pattern="ring") qml.RX(params[3], wires=0) qml.RY(params[4], wires=1) qml.RZ(params[5], wires=2) qml.broadcast(qml.CNOT, wires=[0, 1, 2], pattern="ring") return qml.expval(qml.PauliY(0) @ qml.PauliZ(2)) # initial parameters params = np.random.random([6], requires_grad=True) print("Parameters:", params) print("Expectation value:", circuit(params)) fig, ax = qml.draw_mpl(circuit, decimals=2)(params) plt.show() def parameter_shift_term(qnode, params, i): shifted = params.copy() shifted[i] += np.pi/2 forward = qnode(shifted) # forward evaluation shifted[i] -= np.pi backward = qnode(shifted) # backward evaluation return 0.5 * (forward - backward) # gradient with respect to the first parameter print(parameter_shift_term(circuit, params, 0)) def parameter_shift(qnode, params): gradients = np.zeros([len(params)]) for i in range(len(params)): gradients[i] = parameter_shift_term(qnode, params, i) return gradients print(parameter_shift(circuit, params)) grad_function = qml.grad(circuit) print(grad_function(params)[0]) print(qml.gradients.param_shift(circuit)(params)) dev = qml.device("default.qubit", wires=4) @qml.qnode(dev, diff_method="parameter-shift") def circuit(params): qml.StronglyEntanglingLayers(params, wires=[0, 1, 2, 3]) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliZ(2) @ qml.PauliZ(3)) # initialize circuit parameters param_shape = qml.StronglyEntanglingLayers.shape(n_wires=4, n_layers=15) params = np.random.normal(scale=0.1, size=param_shape, requires_grad=True) print(params.size) print(circuit(params)) import timeit reps = 3 num = 10 times = timeit.repeat("circuit(params)", globals=globals(), number=num, repeat=reps) forward_time = min(times) / num print(f"Forward pass (best of {reps}): {forward_time} sec per loop") # create the gradient function grad_fn = qml.grad(circuit) times = timeit.repeat("grad_fn(params)", globals=globals(), number=num, repeat=reps) backward_time = min(times) / num print(f"Gradient computation (best of {reps}): {backward_time} sec per loop") print(2 * forward_time * params.size) dev = qml.device("default.qubit", wires=4) @qml.qnode(dev, diff_method="backprop") def circuit(params): qml.StronglyEntanglingLayers(params, wires=[0, 1, 2, 3]) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliZ(2) @ qml.PauliZ(3)) # initialize circuit parameters param_shape = qml.StronglyEntanglingLayers.shape(n_wires=4, n_layers=15) params = np.random.normal(scale=0.1, size=param_shape, requires_grad=True) print(circuit(params)) import timeit reps = 3 num = 10 times = timeit.repeat("circuit(params)", globals=globals(), number=num, repeat=reps) forward_time = min(times) / num print(f"Forward pass (best of {reps}): {forward_time} sec per loop") times = timeit.repeat("qml.grad(circuit)(params)", globals=globals(), number=num, repeat=reps) backward_time = min(times) / num print(f"Backward pass (best of {reps}): {backward_time} sec per loop") dev = qml.device("default.qubit", wires=4) def circuit(params): qml.StronglyEntanglingLayers(params, wires=[0, 1, 2, 3]) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliZ(2) @ qml.PauliZ(3)) reps = 2 num = 3 forward_shift = [] gradient_shift = [] forward_backprop = [] gradient_backprop = [] for depth in range(0, 21): param_shape = qml.StronglyEntanglingLayers.shape(n_wires=4, n_layers=depth) params = np.random.normal(scale=0.1, size=param_shape, requires_grad=True) num_params = params.size # forward pass timing # =================== qnode_shift = qml.QNode(circuit, dev, diff_method="parameter-shift") qnode_backprop = qml.QNode(circuit, dev, diff_method="backprop") # parameter-shift t = timeit.repeat("qnode_shift(params)", globals=globals(), number=num, repeat=reps) forward_shift.append([num_params, min(t) / num]) # backprop t = timeit.repeat("qnode_backprop(params)", globals=globals(), number=num, repeat=reps) forward_backprop.append([num_params, min(t) / num]) if num_params == 0: continue # Gradient timing # =============== qnode_shift = qml.QNode(circuit, dev, diff_method="parameter-shift") qnode_backprop = qml.QNode(circuit, dev, diff_method="backprop") # parameter-shift t = timeit.repeat("qml.grad(qnode_shift)(params)", globals=globals(), number=num, repeat=reps) gradient_shift.append([num_params, min(t) / num]) # backprop t = timeit.repeat("qml.grad(qnode_backprop)(params)", globals=globals(), number=num, repeat=reps) gradient_backprop.append([num_params, min(t) / num]) gradient_shift = np.array(gradient_shift).T gradient_backprop = np.array(gradient_backprop).T forward_shift = np.array(forward_shift).T forward_backprop = np.array(forward_backprop).T plt.style.use("bmh") fig, ax = plt.subplots(1, 1, figsize=(6, 4)) ax.plot(*gradient_shift, '.-', label="Parameter-shift") ax.plot(*gradient_backprop, '.-', label="Backprop") ax.set_ylabel("Time (s)") ax.set_xlabel("Number of parameters") ax.legend() plt.show() gradient_shift[1] /= forward_shift[1, 1:] gradient_backprop[1] /= forward_backprop[1, 1:] fig, ax = plt.subplots(1, 1, figsize=(6, 4)) ax.plot(*gradient_shift, '.-', label="Parameter-shift") ax.plot(*gradient_backprop, '.-', label="Backprop") # perform a least squares regression to determine the linear best fit/gradient # for the normalized time vs. number of parameters x = gradient_shift[0] m_shift, c_shift = np.polyfit(*gradient_shift, deg=1) m_back, c_back = np.polyfit(*gradient_backprop, deg=1) ax.plot(x, m_shift * x + c_shift, '--', label=f"{m_shift:.2f}p{c_shift:+.2f}") ax.plot(x, m_back * x + c_back, '--', label=f"{m_back:.2f}p{c_back:+.2f}") ax.set_ylabel("Normalized time") ax.set_xlabel("Number of parameters") ax.set_xscale("log") ax.set_yscale("log") ax.legend() plt.show()
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. """DAGFixedPoint pass testing""" import unittest from qiskit.transpiler.passes import DAGFixedPoint from qiskit import QuantumRegister, QuantumCircuit from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestFixedPointPass(QiskitTestCase): """Tests for PropertySet methods.""" def test_empty_dag_true(self): """Test the dag fixed point of an empty dag.""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = DAGFixedPoint() pass_.run(dag) self.assertFalse(pass_.property_set["dag_fixed_point"]) pass_.run(dag) self.assertTrue(pass_.property_set["dag_fixed_point"]) def test_nonempty_dag_false(self): """Test the dag false fixed point of a non-empty dag.""" qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) pass_ = DAGFixedPoint() pass_.run(dag) self.assertFalse(pass_.property_set["dag_fixed_point"]) dag.remove_all_ops_named("h") pass_.run(dag) self.assertFalse(pass_.property_set["dag_fixed_point"]) if __name__ == "__main__": unittest.main()
https://github.com/yatharth0610/Quantum-Algorithms-qiskit-
yatharth0610
from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(2) # we will need seperates registers for using 'c_if' later. qc = QuantumCircuit(qr,crz,crx) qc.x(0) qc.h(0) # 'psi' can't be unknown to us as we are creating it here. Let us take '-' state as our 'psi' # We will verify later if the '-' is been teleported. qc.h(1) qc.cx(1,2) # creating a bell state qc.barrier() # Use barrier to separate steps, everything till this barrier is just intialisation. qc.cx(0,1) # '0' and '1' are with Alice and '2' is with Bob. # psi_1 prepared. qc.h(0) # psi_2 prepared. qc.barrier() qc.measure(0,0) qc.measure(1,1) qc.draw (output = 'mpl') qc.x(2).c_if(crx,1) # 'c_if' compares a classical register with a value (either 0 or 1) and performs the qc.z(2).c_if(crz,1) # operation if they are equal. qc.draw('mpl') # be careful of the order of applying X and Z! qc.h(2) qc.measure(2,crx[1]) def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 10000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc) print(counts) plot_histogram(counts) # the output should be '1xx' if the teleportation is successful. # Refer to above cell for a detailed explanation of the strategy. qc1 = QuantumCircuit(2, 2) # Preparing Alice's Bell state: \beta_{00} qc1.h(0) qc1.cx(0, 1) # Skyler's mischief: # Suppose for this example that she applied Pauli-Y. # You can change 'y' to 'x' or 'z' in the following line for other cases. qc1.y(0) # Alice's strategy: qc1.cx(0, 1) qc1.h(0) qc1.measure(0, 0) qc1.measure(1, 1) qc1.draw('mpl') def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 10000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc1) print(counts) if '10' in counts: print('Skyler used Pauli-X!') if '11' in counts: print('Skyler used Pauli-Y!') if '01' in counts: print('Skyler used Pauli-Z!') plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXSimple 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=IQXSimple())
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from crypto.six_state.participant import Participant from qiskit import QuantumCircuit from numpy.random import rand from qiskit import transpile ## The Receiver entity in the Six-State implementation ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class Receiver(Participant): ## Constructor def __init__(self, name='', original_bits_size=0): super().__init__(name, original_bits_size) ## Decode the message measuring the circuit (density-dependent) def decode_quantum_message(self, message, density, backend): ## The values of the participant self.values = [] for i, qc in enumerate(message): qc.barrier() if rand() < density: if self.axes[i] == 1: qc.h(0) elif self.axes[i] == 2: qc.append(self.hy, [0]) qc.measure(0, 0) transpiled_qc = transpile(qc, backend=backend) result = backend.run(transpiled_qc, shots=1, memory=True).result() measured_bit = int(result.get_memory()[0]) self.values.append(measured_bit) else: self.values.append(-1) return message
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. """Test the variational quantum eigensolver algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial import numpy as np from scipy.optimize import minimize as scipy_minimize from ddt import data, ddt from qiskit import QuantumCircuit from qiskit_algorithms import AlgorithmError from qiskit_algorithms.gradients import ParamShiftEstimatorGradient from qiskit_algorithms.minimum_eigensolvers import VQE from qiskit_algorithms.optimizers import ( CG, COBYLA, GradientDescent, L_BFGS_B, OptimizerResult, P_BFGS, QNSPSA, SLSQP, SPSA, TNC, ) from qiskit_algorithms.state_fidelities import ComputeUncompute from qiskit.circuit.library import RealAmplitudes, TwoLocal from qiskit.opflow import PauliSumOp, TwoQubitReduction from qiskit.quantum_info import SparsePauliOp, Operator, Pauli from qiskit.primitives import Estimator, Sampler from qiskit.utils import algorithm_globals # pylint: disable=invalid-name def _mock_optimizer(fun, x0, jac=None, bounds=None, inputs=None) -> OptimizerResult: """A mock of a callable that can be used as minimizer in the VQE.""" result = OptimizerResult() result.x = np.zeros_like(x0) result.fun = fun(result.x) result.nit = 0 if inputs is not None: inputs.update({"fun": fun, "x0": x0, "jac": jac, "bounds": bounds}) return result @ddt class TestVQE(QiskitAlgorithmsTestCase): """Test VQE""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed self.h2_op = SparsePauliOp( ["II", "IZ", "ZI", "ZZ", "XX"], coeffs=[ -1.052373245772859, 0.39793742484318045, -0.39793742484318045, -0.01128010425623538, 0.18093119978423156, ], ) self.h2_energy = -1.85727503 self.ryrz_wavefunction = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") self.ry_wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") @data(L_BFGS_B(), COBYLA()) def test_basic_aer_statevector(self, estimator): """Test VQE using reference Estimator.""" vqe = VQE(Estimator(), self.ryrz_wavefunction, estimator) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) with self.subTest(msg="test eigenvalue"): self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) with self.subTest(msg="test optimal_value"): self.assertAlmostEqual(result.optimal_value, self.h2_energy) with self.subTest(msg="test dimension of optimal point"): self.assertEqual(len(result.optimal_point), 16) with self.subTest(msg="assert cost_function_evals is set"): self.assertIsNotNone(result.cost_function_evals) with self.subTest(msg="assert optimizer_time is set"): self.assertIsNotNone(result.optimizer_time) with self.subTest(msg="assert optimizer_result is set"): self.assertIsNotNone(result.optimizer_result) with self.subTest(msg="assert optimizer_result."): self.assertAlmostEqual(result.optimizer_result.fun, self.h2_energy, places=5) with self.subTest(msg="assert return ansatz is set"): estimator = Estimator() job = estimator.run(result.optimal_circuit, self.h2_op, result.optimal_point) np.testing.assert_array_almost_equal(job.result().values, result.eigenvalue, 6) def test_invalid_initial_point(self): """Test the proper error is raised when the initial point has the wrong size.""" ansatz = self.ryrz_wavefunction initial_point = np.array([1]) vqe = VQE( Estimator(), ansatz, SLSQP(), initial_point=initial_point, ) with self.assertRaises(ValueError): _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_ansatz_resize(self): """Test the ansatz is properly resized if it's a blueprint circuit.""" ansatz = RealAmplitudes(1, reps=1) vqe = VQE(Estimator(), ansatz, SLSQP()) result = vqe.compute_minimum_eigenvalue(self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_invalid_ansatz_size(self): """Test an error is raised if the ansatz has the wrong number of qubits.""" ansatz = QuantumCircuit(1) ansatz.compose(RealAmplitudes(1, reps=2)) vqe = VQE(Estimator(), ansatz, SLSQP()) with self.assertRaises(AlgorithmError): _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_missing_ansatz_params(self): """Test specifying an ansatz with no parameters raises an error.""" ansatz = QuantumCircuit(self.h2_op.num_qubits) vqe = VQE(Estimator(), ansatz, SLSQP()) with self.assertRaises(AlgorithmError): vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_max_evals_grouped(self): """Test with SLSQP with max_evals_grouped.""" optimizer = SLSQP(maxiter=50, max_evals_grouped=5) vqe = VQE( Estimator(), self.ryrz_wavefunction, optimizer, ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) @data( CG(), L_BFGS_B(), P_BFGS(), SLSQP(), TNC(), ) def test_with_gradient(self, optimizer): """Test VQE using gradient primitive.""" estimator = Estimator() vqe = VQE( estimator, self.ry_wavefunction, optimizer, gradient=ParamShiftEstimatorGradient(estimator), ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_gradient_passed(self): """Test the gradient is properly passed into the optimizer.""" inputs = {} estimator = Estimator() vqe = VQE( estimator, RealAmplitudes(), partial(_mock_optimizer, inputs=inputs), gradient=ParamShiftEstimatorGradient(estimator), ) _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertIsNotNone(inputs["jac"]) def test_gradient_run(self): """Test using the gradient to calculate the minimum.""" estimator = Estimator() vqe = VQE( estimator, RealAmplitudes(), GradientDescent(maxiter=200, learning_rate=0.1), gradient=ParamShiftEstimatorGradient(estimator), ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_with_two_qubit_reduction(self): """Test the VQE using TwoQubitReduction.""" with self.assertWarns(DeprecationWarning): qubit_op = PauliSumOp.from_list( [ ("IIII", -0.8105479805373266), ("IIIZ", 0.17218393261915552), ("IIZZ", -0.22575349222402472), ("IZZI", 0.1721839326191556), ("ZZII", -0.22575349222402466), ("IIZI", 0.1209126326177663), ("IZZZ", 0.16892753870087912), ("IXZX", -0.045232799946057854), ("ZXIX", 0.045232799946057854), ("IXIX", 0.045232799946057854), ("ZXZX", -0.045232799946057854), ("ZZIZ", 0.16614543256382414), ("IZIZ", 0.16614543256382414), ("ZZZZ", 0.17464343068300453), ("ZIZI", 0.1209126326177663), ] ) tapered_qubit_op = TwoQubitReduction(num_particles=2).convert(qubit_op) vqe = VQE( Estimator(), self.ry_wavefunction, SPSA(maxiter=300, last_avg=5), ) result = vqe.compute_minimum_eigenvalue(tapered_qubit_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=2) def test_callback(self): """Test the callback on VQE.""" history = {"eval_count": [], "parameters": [], "mean": [], "metadata": []} def store_intermediate_result(eval_count, parameters, mean, metadata): history["eval_count"].append(eval_count) history["parameters"].append(parameters) history["mean"].append(mean) history["metadata"].append(metadata) optimizer = COBYLA(maxiter=3) wavefunction = self.ry_wavefunction estimator = Estimator() vqe = VQE( estimator, wavefunction, optimizer, callback=store_intermediate_result, ) vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertTrue(all(isinstance(count, int) for count in history["eval_count"])) self.assertTrue(all(isinstance(mean, float) for mean in history["mean"])) self.assertTrue(all(isinstance(metadata, dict) for metadata in history["metadata"])) for params in history["parameters"]: self.assertTrue(all(isinstance(param, float) for param in params)) def test_reuse(self): """Test re-using a VQE algorithm instance.""" ansatz = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") vqe = VQE(Estimator(), ansatz, SLSQP(maxiter=300)) with self.subTest(msg="assert VQE works once all info is available"): result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) operator = Operator(np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]])) with self.subTest(msg="assert vqe works on re-use."): result = vqe.compute_minimum_eigenvalue(operator=operator) self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5) def test_vqe_optimizer_reuse(self): """Test running same VQE twice to re-use optimizer, then switch optimizer""" vqe = VQE( Estimator(), self.ryrz_wavefunction, SLSQP(), ) def run_check(): result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) run_check() with self.subTest("Optimizer re-use."): run_check() with self.subTest("Optimizer replace."): vqe.optimizer = L_BFGS_B() run_check() def test_default_batch_evaluation_on_spsa(self): """Test the default batching works.""" ansatz = TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz") wrapped_estimator = Estimator() inner_estimator = Estimator() callcount = {"estimator": 0} def wrapped_estimator_run(*args, **kwargs): kwargs["callcount"]["estimator"] += 1 return inner_estimator.run(*args, **kwargs) wrapped_estimator.run = partial(wrapped_estimator_run, callcount=callcount) spsa = SPSA(maxiter=5) vqe = VQE(wrapped_estimator, ansatz, spsa) _ = vqe.compute_minimum_eigenvalue(Pauli("ZZ")) # 1 calibration + 5 loss + 1 return loss expected_estimator_runs = 1 + 5 + 1 with self.subTest(msg="check callcount"): self.assertEqual(callcount["estimator"], expected_estimator_runs) with self.subTest(msg="check reset to original max evals grouped"): self.assertIsNone(spsa._max_evals_grouped) def test_batch_evaluate_with_qnspsa(self): """Test batch evaluating with QNSPSA works.""" ansatz = TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz") wrapped_sampler = Sampler() inner_sampler = Sampler() wrapped_estimator = Estimator() inner_estimator = Estimator() callcount = {"sampler": 0, "estimator": 0} def wrapped_estimator_run(*args, **kwargs): kwargs["callcount"]["estimator"] += 1 return inner_estimator.run(*args, **kwargs) def wrapped_sampler_run(*args, **kwargs): kwargs["callcount"]["sampler"] += 1 return inner_sampler.run(*args, **kwargs) wrapped_estimator.run = partial(wrapped_estimator_run, callcount=callcount) wrapped_sampler.run = partial(wrapped_sampler_run, callcount=callcount) fidelity = ComputeUncompute(wrapped_sampler) def fidelity_callable(left, right): batchsize = np.asarray(left).shape[0] job = fidelity.run(batchsize * [ansatz], batchsize * [ansatz], left, right) return job.result().fidelities qnspsa = QNSPSA(fidelity_callable, maxiter=5) qnspsa.set_max_evals_grouped(100) vqe = VQE( wrapped_estimator, ansatz, qnspsa, ) _ = vqe.compute_minimum_eigenvalue(Pauli("ZZ")) # 5 (fidelity) expected_sampler_runs = 5 # 1 calibration + 1 stddev estimation + 1 initial blocking # + 5 (1 loss + 1 blocking) + 1 return loss expected_estimator_runs = 1 + 1 + 1 + 5 * 2 + 1 self.assertEqual(callcount["sampler"], expected_sampler_runs) self.assertEqual(callcount["estimator"], expected_estimator_runs) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" vqe = VQE( Estimator(), self.ryrz_wavefunction, partial(scipy_minimize, method="L-BFGS-B", options={"maxiter": 10}), ) result = vqe.compute_minimum_eigenvalue(self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=2) def test_optimizer_callable(self): """Test passing a optimizer directly as callable.""" ansatz = RealAmplitudes(1, reps=1) vqe = VQE(Estimator(), ansatz, _mock_optimizer) result = vqe.compute_minimum_eigenvalue(SparsePauliOp("Z")) self.assertTrue(np.all(result.optimal_point == np.zeros(ansatz.num_parameters))) def test_aux_operators_list(self): """Test list-based aux_operators.""" vqe = VQE(Estimator(), self.ry_wavefunction, SLSQP(maxiter=300)) with self.subTest("Test with an empty list."): result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=[]) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertIsInstance(result.aux_operators_evaluated, list) self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): with self.assertWarns(DeprecationWarning): aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list( [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] ) aux_ops = [aux_op1, aux_op2] result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0], 2.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[1][0], 0.0, places=6) # metadata self.assertIsInstance(result.aux_operators_evaluated[0][1], dict) self.assertIsInstance(result.aux_operators_evaluated[1][1], dict) with self.subTest("Test with additional zero operator."): extra_ops = [*aux_ops, 0] result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0], 2.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[1][0], 0.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[2][0], 0.0) # metadata self.assertIsInstance(result.aux_operators_evaluated[0][1], dict) self.assertIsInstance(result.aux_operators_evaluated[1][1], dict) self.assertIsInstance(result.aux_operators_evaluated[2][1], dict) def test_aux_operators_dict(self): """Test dictionary compatibility of aux_operators""" vqe = VQE(Estimator(), self.ry_wavefunction, SLSQP(maxiter=300)) with self.subTest("Test with an empty dictionary."): result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators={}) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertIsInstance(result.aux_operators_evaluated, dict) self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): with self.assertWarns(DeprecationWarning): aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list( [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] ) aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated["aux_op1"][0], 2.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["aux_op2"][0], 0.0, places=5) # metadata self.assertIsInstance(result.aux_operators_evaluated["aux_op1"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["aux_op2"][1], dict) with self.subTest("Test with additional zero operator."): extra_ops = {**aux_ops, "zero_operator": 0} result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated["aux_op1"][0], 2.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["aux_op2"][0], 0.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["zero_operator"][0], 0.0) # metadata self.assertIsInstance(result.aux_operators_evaluated["aux_op1"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["aux_op2"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["zero_operator"][1], dict) if __name__ == "__main__": unittest.main()
https://github.com/arthurfaria/QC_basic_agorithms_qiskit
arthurfaria
from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute, assemble, QuantumRegister, ClassicalRegister from qiskit.tools.monitor import job_monitor import matplotlib as mpl # import basic plot tools from qiskit.visualization import plot_histogram, plot_bloch_multivector import numpy as np from numpy import pi # Initializing the Qubits ql = QuantumRegister(3, name="ql") # logic qubits qa = QuantumRegister(2, name="qa") # Ancilla qubits mea = ClassicalRegister(3, name="mea") syn = ClassicalRegister(2, name="syn") qec_circuit = QuantumCircuit(ql,qa,mea,syn) # Encoding qec_circuit.clear() qec_circuit.cx(0,1) qec_circuit.cx(0,2) qec_circuit.barrier() # Bit flip error n = np.random.randint(3) qec_circuit.x(n) qec_circuit.barrier() # Syndrome Circuit qec_circuit.cx(0,3) qec_circuit.cx(1,3) qec_circuit.cx(0,4) qec_circuit.cx(2,4) qec_circuit.barrier() qec_circuit.measure(qa,syn) # Recovery cirucit qec_circuit.barrier() qec_circuit.mct([3,4],0) qec_circuit.x(4) qec_circuit.mct([3,4],1) qec_circuit.x(4) qec_circuit.x(3) qec_circuit.mct([3,4],2) qec_circuit.x(3) qec_circuit.barrier() # Decoding circuit qec_circuit.cx(0,2) qec_circuit.cx(0,1) qec_circuit.barrier() # measurement qec_circuit.measure(ql,mea) qec_circuit.draw("mpl") qec_circuit.draw('mpl') aer_sim = Aer.get_backend('aer_simulator') shots = 1024 t_qec = execute(qec_circuit, aer_sim, shots=shots).result() counts = t_qec.get_counts() plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization import QuadraticProgram problem = QuadraticProgram("sample") problem.binary_var("x") problem.binary_var("y") problem.maximize(linear={"x": 1, "y": -2}) print(problem.prettyprint()) from qiskit.algorithms import NumPyMinimumEigensolver from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = NumPyMinimumEigensolver() meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = NumPyMinimumEigensolver() meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) mes = QAOA(optimizer=COBYLA(), quantum_instance=qins) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer shots = 1000 mes = QAOA(sampler=Sampler(), optimizer=COBYLA()) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) mes = VQE(ansatz=RealAmplitudes(), optimizer=COBYLA(), quantum_instance=qins) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = SamplingVQE(sampler=Sampler(), ansatz=RealAmplitudes(), optimizer=COBYLA()) meo = MinimumEigenOptimizer(min_eigen_solver=mes) result = meo.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Estimator from qiskit_optimization.algorithms import MinimumEigenOptimizer mes = VQE(estimator=Estimator(), ansatz=RealAmplitudes(), optimizer=COBYLA()) try: meo = MinimumEigenOptimizer(min_eigen_solver=mes) except TypeError as ex: print(ex) from qiskit import BasicAer from qiskit.algorithms import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) qaoa = QAOA(optimizer=COBYLA(), quantum_instance=qins) optimizer = WarmStartQAOAOptimizer( pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25 ) result = optimizer.solve(problem) print(result) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer qaoa = QAOA(sampler=Sampler(), optimizer=COBYLA()) optimizer = WarmStartQAOAOptimizer( pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25 ) result = optimizer.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit_optimization.algorithms import GroverOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, quantum_instance=qins) result = optimizer.solve(problem) print(result) from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import GroverOptimizer optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, sampler=Sampler()) result = optimizer.solve(problem) print(result) from qiskit import BasicAer from qiskit.algorithms.optimizers import COBYLA from qiskit.utils import QuantumInstance from qiskit.primitives import Sampler from qiskit_optimization.algorithms import GroverOptimizer backend = BasicAer.get_backend("qasm_simulator") shots = 1000 qins = QuantumInstance(backend=backend, shots=shots) try: optimizer = GroverOptimizer( num_value_qubits=3, num_iterations=3, quantum_instance=qins, sampler=Sampler() ) # raises an error because both quantum_instance and sampler are set. except ValueError as ex: print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/abbarreto/qiskit4
abbarreto
from qiskit.circuit import Parameter from qiskit import QuantumCircuit theta = Parameter('$\\theta$') chsh_circuits_no_meas = QuantumCircuit(2) chsh_circuits_no_meas.h(0) chsh_circuits_no_meas.cx(0, 1) chsh_circuits_no_meas.ry(theta, 0) chsh_circuits_no_meas.draw('mpl') import numpy as np number_of_phases = 21 phases = np.linspace(0, 2*np.pi, number_of_phases) # Phases need to be expressed as list of lists in order to work individual_phases = [[ph] for ph in phases] individual_phases from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" from qiskit_ibm_runtime import Estimator, Session from qiskit.quantum_info import SparsePauliOp ZZ = SparsePauliOp.from_list([("ZZ", 1)]) ZX = SparsePauliOp.from_list([("ZX", 1)]) XZ = SparsePauliOp.from_list([("XZ", 1)]) XX = SparsePauliOp.from_list([("XX", 1)]) ops = [ZZ, ZX, XZ, XX] chsh_est_sim = [] # Simulator with Session(service=service, backend=backend): estimator = Estimator() for op in ops: job = estimator.run( circuits=[chsh_circuits_no_meas]*len(individual_phases), observables=[op]*len(individual_phases), parameter_values=individual_phases) est_result = job.result() chsh_est_sim.append(est_result) # <CHSH1> = <AB> - <Ab> + <aB> + <ab> chsh1_est_sim = chsh_est_sim[0].values - chsh_est_sim[1].values + chsh_est_sim[2].values + chsh_est_sim[3].values # <CHSH2> = <AB> + <Ab> - <aB> + <ab> chsh2_est_sim = chsh_est_sim[0].values + chsh_est_sim[1].values - chsh_est_sim[2].values + chsh_est_sim[3].values import matplotlib.pyplot as plt import matplotlib.ticker as tck fig, ax = plt.subplots(figsize=(10, 6)) # results from a simulator ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Simulation') ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Simulation') # classical bound +-2 ax.axhline(y=2, color='r', linestyle='--') ax.axhline(y=-2, color='r', linestyle='--') # quantum bound, +-2√2 ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.') ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.') # set x tick labels to the unit of pi ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$')) ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5)) # set title, labels, and legend plt.title('Violation of CHSH Inequality') plt.xlabel('Theta') plt.ylabel('CHSH witness') plt.legend() from qiskit_ibm_runtime import Estimator, Session from qiskit.quantum_info import SparsePauliOp backend = service.get_backend("ibmq_belem") ZZ = SparsePauliOp.from_list([("ZZ", 1)]) ZX = SparsePauliOp.from_list([("ZX", 1)]) XZ = SparsePauliOp.from_list([("XZ", 1)]) XX = SparsePauliOp.from_list([("XX", 1)]) ops = [ZZ, ZX, XZ, XX] chsh_est_sim = [] with Session(service=service, backend=backend): estimator = Estimator() for op in ops: job = estimator.run( circuits=[chsh_circuits_no_meas]*len(individual_phases), observables=[op]*len(individual_phases), parameter_values=individual_phases) print(job.job_id()) est_result = job.result() chsh_est_sim.append(est_result) # <CHSH1> = <AB> - <Ab> + <aB> + <ab> chsh1_est_sim = chsh_est_sim[0].values - chsh_est_sim[1].values + chsh_est_sim[2].values + chsh_est_sim[3].values # <CHSH2> = <AB> + <Ab> - <aB> + <ab> chsh2_est_sim = chsh_est_sim[0].values + chsh_est_sim[1].values - chsh_est_sim[2].values + chsh_est_sim[3].values import matplotlib.pyplot as plt import matplotlib.ticker as tck fig, ax = plt.subplots(figsize=(10, 6)) # results from a simulator ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Experiment') ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Experiment') # classical bound +-2 ax.axhline(y=2, color='r', linestyle='--') ax.axhline(y=-2, color='r', linestyle='--') # quantum bound, +-2√2 ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.') ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.') # set x tick labels to the unit of pi ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$')) ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5)) # set title, labels, and legend plt.title('Violation of CHSH Inequality') plt.xlabel('Theta') plt.ylabel('CHSH witness') plt.legend() (250/4)*3
https://github.com/JackHidary/quantumcomputingbook
JackHidary
"""Superdense coding.""" # Imports import qiskit # Create two quantum and classical registers qreg = qiskit.QuantumRegister(2) creg = qiskit.ClassicalRegister(2) circ = qiskit.QuantumCircuit(qreg, creg) # Add a Hadamard gate on qubit 0 to create a superposition circ.h(qreg[0]) # Apply the X operator to qubit 0 circ.x(qreg[0]) # To get the Bell state apply the CNOT operator on qubit 0 and 1 circ.cx(qreg[0], qreg[1]) # Apply the H operator to take qubit 0 out of superposition circ.h(qreg[0]) # Add a Measure gate to obtain the message circ.measure(qreg, creg) # Print out the circuit print("Circuit:") print(circ.draw()) # Run the quantum circuit on a simulator backend backend = qiskit.Aer.get_backend("statevector_simulator") job = qiskit.execute(circ, backend) res = job.result() print(res.get_counts())
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import qiskit.qasm3 program = """ OPENQASM 3.0; include "stdgates.inc"; input float[64] a; qubit[3] q; bit[2] mid; bit[3] out; let aliased = q[0:1]; gate my_gate(a) c, t { gphase(a / 2); ry(a) c; cx c, t; } gate my_phase(a) c { ctrl @ inv @ gphase(a) c; } my_gate(a * 2) aliased[0], q[{1, 2}][0]; measure q[0] -> mid[0]; measure q[1] -> mid[1]; while (mid == "00") { reset q[0]; reset q[1]; my_gate(a) q[0], q[1]; my_phase(a - pi/2) q[1]; mid[0] = measure q[0]; mid[1] = measure q[1]; } if (mid[0]) { let inner_alias = q[{0, 1}]; reset inner_alias; } out = measure q; """ circuit = qiskit.qasm3.loads(program) circuit.draw("mpl")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() print(problem) hamiltonian = problem.hamiltonian coefficients = hamiltonian.electronic_integrals print(coefficients.alpha) second_q_op = hamiltonian.second_q_op() print(second_q_op) hamiltonian.nuclear_repulsion_energy # NOT included in the second_q_op above problem.molecule problem.reference_energy problem.num_particles problem.num_spatial_orbitals problem.basis problem.properties problem.properties.particle_number problem.properties.angular_momentum problem.properties.magnetization problem.properties.electronic_dipole_moment from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import JordanWignerMapper solver = GroundStateEigensolver( JordanWignerMapper(), NumPyMinimumEigensolver(), ) result = solver.solve(problem) print(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Fergus-Hayes/qiskit_tools
Fergus-Hayes
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ import qiskit_tools as qt import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.rcParams['mathtext.fontset'] = 'stix' matplotlib.rcParams['font.family'] = 'STIXGeneral' width=0.75 color='black' fontsize=28 ticksize=22 figsize=(10,8) digit = 1. bounds = np.array([-2., 0., 1.5, 3.]) print('Domain boundaries:',bounds) m = int(np.ceil(np.log2(len(bounds)))) print('Label qubits:',m) phase = True nint = qt.get_nint([digit,*bounds]) npres = qt.get_npres([digit,*bounds]) n = nint + npres if phase: n+=1 binary_x = qt.my_binary_repr(digit, n, nint=nint, phase=phase) qx = QuantumRegister(n, 'x') qtarg = QuantumRegister(1, 'targ') qans = QuantumRegister(n-1, 'a') qlab = QuantumRegister(m, 'l') out_reg = ClassicalRegister(m,'out') circ = QuantumCircuit(qx, qtarg, qans, qlab, out_reg) x_gate = qt.input_bits_to_qubits(binary_x, circ, reg=qx, wrap=True) circ.append(x_gate, qx); circ = qt.label_gate(circ, qx, qtarg, qans, qlab, bounds=bounds, nint=nint, phase=phase) circ.measure(qlab, out_reg); circ.draw('latex') shots=10 emulator = Aer.get_backend('qasm_simulator') job = execute(circ, emulator, shots=shots ) hist = job.result().get_counts() print('Result:') for label in hist.keys(): if qt.bin_to_dec(label, nint=None, phase=False)==0.: print(digit,'is outwith the bounds of','['+str(bounds[0])+',',str(bounds[-1])+')','with probability',float(hist[label])/shots) else: print(bounds[int(qt.bin_to_dec(label, nint=None, phase=False))-1],'<=',digit,'<',bounds[int(qt.bin_to_dec(label, nint=None, phase=False))],'with probability',float(hist[label])/shots) digit = 1. bounds = np.array([-2., 0., 1.5, 3.]) print('Domain boundaries:',bounds) m = int(np.ceil(np.log2(len(bounds)))) phase = True nint = qt.get_nint([digit,*bounds]) npres = qt.get_npres([digit,*bounds]) n = nint + npres if phase: n+=1 binary_x = qt.my_binary_repr(digit, n, nint=nint, phase=phase) print('Label qubits:',m) A1s = np.array([3., -1., 2.5, -0.5]) nintc = qt.get_nint(A1s) npresc = qt.get_npres(A1s) nc = nintc + npresc if phase: nc+=1 n = np.max([n,nc]) qx = QuantumRegister(n, 'x') qcoff = QuantumRegister(n, 'c') qlab = QuantumRegister(m, 'l') out_reg = ClassicalRegister(n,'out') circ = QuantumCircuit(qx, qcoff, qlab, out_reg) qtarg = qcoff[0] qans = qcoff[1:] x_gate = qt.input_bits_to_qubits(binary_x, circ, reg=qx, wrap=True) circ.append(x_gate, qx); l_gate = qt.label_gate(circ, qx, qtarg, qans, qlab, bounds=bounds, nint=nint, phase=phase, wrap=True) circ.append(l_gate, [*qx, qtarg, *qans, *qlab]); circ = qt.cin_gate(circ, qcoff, qlab, A1s, nint=nintc, phase=phase) circ.measure(qcoff, out_reg); circ.draw('latex') shots=10 emulator = Aer.get_backend('qasm_simulator') job = execute(circ, emulator, shots=shots ) hist = job.result().get_counts() print('Target:') ind = np.argwhere((np.array([bounds[-1],*bounds[:-1]])<=digit)*(bounds>digit)).flatten()[0] print(A1s[ind],'as',bounds[ind-1],'<=',digit,'<',bounds[ind]) print('Result:') for label in hist.keys(): print(qt.bin_to_dec(label, nint=nintc, phase=phase),'->',label,'with probability',float(hist[label])/shots) qx = QuantumRegister(n, 'x') qcoff = QuantumRegister(n, 'c') qlab = QuantumRegister(m, 'l') out_reg = ClassicalRegister(n,'out') circ = QuantumCircuit(qx, qcoff, qlab, out_reg) qtarg = qcoff[0] qans = qcoff[1:] x_gate = qt.input_bits_to_qubits(binary_x, circ, reg=qx, wrap=True) circ.append(x_gate, qx); l_gate = qt.label_gate(circ, qx, qtarg, qans, qlab, bounds=bounds, nint=nint, phase=phase, wrap=True) circ.append(l_gate, [*qx, qtarg, *qans, *qlab]); X_gate = qt.cin_gate(circ, qcoff, qlab, A1s, nint=nintc, phase=phase, wrap=True, label='X') X_gate_inv = qt.cin_gate(circ, qcoff, qlab, A1s, nint=nintc, phase=phase, wrap=True, inverse=True, label='X') circ.append(X_gate, [*qcoff, *qlab]); circ.append(X_gate_inv, [*qcoff, *qlab]); circ.measure(qcoff, out_reg); circ.draw('latex') shots=10 emulator = Aer.get_backend('qasm_simulator') job = execute(circ, emulator, shots=shots ) hist = job.result().get_counts() print('Result:') for label in hist.keys(): print(qt.bin_to_dec(label, nint=nintc, phase=phase),'->',label,'with probability',float(hist[label])/shots) def f_x(x): return np.arctan(x) phase = True nintx = 3 nx = 5 npresx = nx - nintx if phase: npresx-=1 xmin = -2.**(nintx) xmax = 2.**(nintx) - 2.**(-npresx) xs = np.linspace(xmin,xmax,2**nx) npres0, npres1 = 4, 4 norder = 1 m = 3 n, n0, nint, nintcs, coeffs, bounds = qt.optimize_coeffs_qubits(f_x, xs, m, npres0, npres1, norder=norder, phase=phase, label_swap=True) print('Qubits:', nx, n, n0, m) print('Integer qubits:', nintx, nint, nintcs[0,0], nintcs[0,1]) print('Memory:', 16*(2**(n+n0+nx+m))/2**20) _, _, _, _, coeffs_, _ = qt.optimize_coeffs_qubits(f_x, xs, m, npres0, npres1, norder=norder, phase=phase, label_swap=False) ys_rnd = qt.piecewise_poly(xs, coeffs_.T, bounds) qx = QuantumRegister(nx, 'x') qout = QuantumRegister(n, 'o') qlab = QuantumRegister(m, 'l') qcoff = QuantumRegister(n0, 'c') circ = QuantumCircuit(qx, qout, qlab, qcoff) # 1. Initialize the x register (let as produce a superposition across all x values) for i in np.arange(nx): circ.h(qx[i]); # We can use the coefficient register as the ancillary register for the labelling step as before qtarg = qcoff[0] qans = [*qcoff[1:], *qout][:nx-1] # 2. Label the data with the labelling operation l_gate = qt.label_gate(circ, qx, qtarg, qans, qlab, bounds=bounds, nint=nintx, phase=phase, wrap=True) circ.append(l_gate, [*qx, qtarg, *qans, *qlab]); # 3. Load A1 into the coefficient register conditioned on the label register X1_gate = qt.cin_gate(circ, qcoff, qlab, coeffs[0], nint=nintcs[0,0], phase=phase, wrap=True) circ.append(X1_gate, [*qcoff, *qlab]); # 4. Multiply the coefficient and x registers and save the output on the output register mul_gate = qt.QFTMultPhase(circ, qcoff, qx, qout, wrap=True, nint1=nintcs[0,0], nint2=nintx, nint3=nint) circ.append(mul_gate, [*qcoff, *qx, *qout]); # 5. Unload A1 from the coefficient register with the inverse load operation X1_gate_inv = qt.cin_gate(circ, qcoff, qlab, coeffs[0], nint=nintcs[0,0], phase=phase, wrap=True, inverse=True) circ.append(X1_gate_inv, [*qcoff, *qlab]); # 6. Load A0 into the coefficient register conditioned on the label register X0_gate = qt.cin_gate(circ, qcoff, qlab, coeffs[1], nint=nintcs[0,1], phase=phase, wrap=True) circ.append(X0_gate, [*qcoff, *qlab]); # 7. Add the coefficient register to the output register add_gate = qt.QFTAddition(circ, qcoff, qout, nint1=nintcs[0,1], nint2=nint, wrap=True, phase=phase) circ.append(add_gate, [*qcoff, *qout]); # Unload A0 to clear the coefficient register X0_gate_inv = qt.cin_gate(circ, qcoff, qlab, coeffs[1], nint=nintcs[0,1], phase=phase, wrap=True, inverse=True) circ.append(X0_gate_inv, [*qcoff, *qlab]); # Unlabel the label register l_gate_inv = qt.label_gate(circ, qx, qtarg, qans, qlab, bounds=bounds, nint=nintx, phase=phase, wrap=True, inverse=True) circ.append(l_gate_inv, [*qx, qtarg, *qans, *qlab]); backend = Aer.get_backend('statevector_simulator') job = execute(circ, backend) result = job.result() state_vector = result.get_statevector() state_v = np.asarray(state_vector).reshape((2**n0,2**m,2**n,2**nx)).T state_v = np.sum(state_v, axis=(2,3)) y_unorm = np.argwhere(np.round(np.abs(state_v)**2,15)>0.)[:,1] y_out = [] for y in y_unorm: y_out.append(qt.bin_to_dec(qt.my_binary_repr(y, n=n, nint=None, phase=False), nint=nint, phase=phase)) xs_comp = [] xs_ = np.linspace(-2**(nx-1),2**(nx-1)-1,2**nx) for x in xs_: binary = qt.my_binary_repr(x, nx, nint=None, phase=True) xs_comp.append(int(qt.bin_to_dec(binary, nint=None, phase=False))) y_out = np.array(y_out)[xs_comp] fig = plt.figure(figsize=figsize) ax = fig.gca() for bound in bounds: ax.axvline(bound, ls=':', color='black') ax.plot(xs, f_x(xs), color='black'); ax.scatter(xs, y_out, color='black', lw=2); ax.plot(xs, ys_rnd, color='black', ls=':', lw=3); ax.set_xlabel(r'$x$', fontsize=fontsize); ax.set_ylabel(r'$f(x)$', fontsize=fontsize); ax.set_xlim(xmin,xmax); ax.tick_params(axis='both', labelsize=ticksize); plt.show() def f_x(x): return np.arctan(x) phase = True phasex = True nintx = 3 nx = 5 npresx = nx - nintx xmin = 0. if phasex: npresx-=1 xmin = -2.**(nintx) xmax = 2.**(nintx) - 2.**(-npresx) xs = np.linspace(xmin,xmax,2**nx) n, n0, nint, nintcs, coeffs, bounds = qt.optimize_coeffs_qubits(f_x, xs, m, npres0, npres1, norder=norder, phase=phase, label_swap=True) print('Qubits:', nx, n, n0, m) print('Integer qubits:', nintx, nint, nintcs[0,0], nintcs[0,1]) print('Memory:', 16*(2**(n+n0+nx+m))/2**20) qx = QuantumRegister(nx, 'x') qout = QuantumRegister(n, 'o') qlab = QuantumRegister(m, 'l') qcoff = QuantumRegister(n0, 'c') circ = QuantumCircuit(qx, qout, qlab, qcoff) for i in np.arange(nx): circ.h(qx[i]); lpf_gate = qt.lpf(circ, qx, qout, qlab, qcoff, coeffs, bounds, nintx=nintx, nintcs=nintcs, nint=nint, phase=phase, phasex=phasex, wrap=True) circ.append(lpf_gate, [*qx, *qout, *qlab, *qcoff]); backend = Aer.get_backend('statevector_simulator') job = execute(circ, backend) result = job.result() state_vector = result.get_statevector() state_v = np.asarray(state_vector).reshape((2**n0,2**m,2**n,2**nx)).T state_v = np.sum(state_v, axis=(2,3)) y_unorm = np.argwhere(np.round(np.abs(state_v)**2,15)>0.)[:,1] y_out = [] for y in y_unorm: y_out.append(qt.bin_to_dec(qt.my_binary_repr(y, n=n, nint=None, phase=False), nint=nint, phase=phase)) xs_comp = [] xs_ = np.linspace(-2**(nx-1),2**(nx-1)-1,2**nx) for x in xs_: binary = qt.my_binary_repr(x, nx, nint=None, phase=True) xs_comp.append(int(qt.bin_to_dec(binary, nint=None, phase=False))) y_out = np.array(y_out)[xs_comp] Ax = qt.piecewise_poly(xs, np.array([coeffs_[0],np.zeros(len(coeffs_[1]))]).T, bounds) fig = plt.figure(figsize=figsize) ax = fig.gca() for bound in bounds: ax.axvline(bound, ls=':', color='black') ax.plot(xs, f_x(xs), color='black'); ax.scatter(xs, y_out, color='black', lw=2); #ax.plot(xs, Ax, color='black', lw=2); ax.set_xlabel(r'$x$', fontsize=fontsize); ax.set_ylabel(r'$f(x)$', fontsize=fontsize); ax.set_xlim(xmin,xmax); ax.tick_params(axis='both', labelsize=ticksize); plt.show()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import BasicAer from qiskit.tools.visualization import circuit_drawer, plot_histogram q = QuantumRegister(2) c = ClassicalRegister(2) circuit = QuantumCircuit(q, c) circuit.h(q[0]) circuit.cx(q[0], q[1]) circuit_drawer(circuit) circuit.measure(q, c) circuit_drawer(circuit) backend = BasicAer.get_backend('qasm_simulator') job = execute(circuit, backend, shots=100) plot_histogram(job.result().get_counts(circuit)) from qiskit import compile compiled_circuit = compile(circuit, backend) compiled_circuit.as_dict()['experiments'][0]['instructions']
https://github.com/qBraid/qBraid
qBraid
import contextlib import pathlib import uuid import sys from typing import Iterable import pytest from qiskit.circuit import QuantumCircuit, Parameter import qiskit_qasm2.parse if sys.version_info >= (3, 8): def _unlink(path: pathlib.Path): path.unlink(missing_ok=True) else: def _unlink(path: pathlib.Path): try: path.unlink() except FileNotFoundError: pass def gate_builder(name: str, parameters: Iterable[Parameter], definition: QuantumCircuit): """Get a builder for a custom gate. Ideally we would just use an eagerly defined `Gate` instance here, but limitations in how `QuantumCircuit.__eq__` and `Instruction.__eq__` work mean that we have to ensure we're using the same class as the parser for equality checks to work.""" # Ideally we wouldn't have this at all, but hiding it away in one function is likely the safest # and easiest to update if the Python component of the library changes. # pylint: disable=protected-access def definer(*arguments): # We can supply empty lists for the gates and the bytecode, because we're going to override # the definition manually ourselves. gate = qiskit_qasm2.parse._DefinedGate(name, definition.num_qubits, arguments, (), ()) gate._definition = definition.assign_parameters(dict(zip(parameters, arguments))) return gate return definer class _TemporaryFilePathFactory: def __init__(self, basedir): self._basedir = basedir @contextlib.contextmanager def __call__(self): path = self._basedir / str(uuid.uuid4()) path.touch() try: yield path finally: _unlink(path) @pytest.fixture(scope="session") def tmp_file_path_factory(tmp_path_factory): """Get a path to a unique read/writeable temporary file that already exists on disk (with no content), has a valid file name, and can be opened for both reading and writing in any mode. The file will cleaned up after the function, if it still exists.""" return _TemporaryFilePathFactory(tmp_path_factory.getbasetemp())
https://github.com/daimurat/qiskit-implementation
daimurat
from qiskit import * from qiskit import Aer from qiskit.aqua import QuantumInstance from qiskit.aqua.operators import Z from qiskit.aqua.operators.state_fns import StateFn, CircuitStateFn from qiskit.aqua.operators.expectations import PauliExpectation, AerPauliExpectation from qiskit.aqua.operators.converters import CircuitSampler import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.colors as colors import numpy as np %matplotlib inline nqubits = 6 # 量子ビット数 sv = 2**nqubits # 状態数 t = 3.0 # ダイナミクスをシミュレーションする時間 M = 100 # トロッター分解の分割数 delta = t/M # 時間の刻み幅 h = 3 # 外部磁場 def get_expectation_val(psi, op): # define your backend or quantum instance backend = Aer.get_backend('qasm_simulator') q_instance = QuantumInstance(backend, shots=1024) # define the state to sample measurable_expression = StateFn(op, is_measurement=True).compose(psi) # convert to expectation value expectation = PauliExpectation().convert(measurable_expression) # expectation = AerPauliExpectation().convert(measurable_expression) # get state sampler (you can also pass the backend directly) sampler = CircuitSampler(q_instance).convert(expectation) # evaluate return sampler.eval().real #回路の準備 circuit_trotter_transIsing = QuantumCircuit(nqubits) # 初期状態の準備 print("{}ビットの初期状態を入力してください。重ね合わせは'+'。(例:000+)".format(nqubits)) b_str = input() # 入力ビットのバイナリ列 for qubit in range(len(b_str)): if b_str[qubit] == '1': circuit_trotter_transIsing.x(qubit) elif b_str[qubit] == '+': circuit_trotter_transIsing.h(qubit) arr = [] #結果を格納する配列 # 計算 for s in range(M): # トロッター分解の1回分、 for i in range(nqubits): circuit_trotter_transIsing.cx(i,(i+1)%nqubits) circuit_trotter_transIsing.rz(-2*delta,(i+1)%nqubits) circuit_trotter_transIsing.cx(i,(i+1)%nqubits) circuit_trotter_transIsing.rx(-2*delta*h, i) # 磁化の期待値を求める psi = CircuitStateFn(circuit_trotter_transIsing) op = Z result = get_expectation_val(psi, op) #状態ベクトルの保存 arr.append(result) # 磁化ダイナミクス表示 x = [i*delta for i in range(M)] plt.xlabel("time") plt.ylabel("magnetization") plt.plot(x, arr) plt.show()
https://github.com/RokiyaMG/Shors_Algorithm
RokiyaMG
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 import matplotlib.pyplot as plt from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram from math import gcd from numpy.random import randint import pandas as pd from fractions import Fraction print("Imports Successful") # Loading your IBM Quantum account(s) provider = IBMQ.load_account() #defining the U gates for mod 63 def c_amod63(a, power): """Controlled multiplication by a mod 63""" if a not in [2, 4, 5, 8, 10, 11, 13, 16, 17, 19, 20, 22, 23, 25, 26, 29, 31, 32, 34, 37, 38, 40, 41, 43, 44, 46, 47, 50, 52, 53, 55, 58, 59, 61, 62]: raise ValueError("'a' must be 2, 4, 5, 8, 10, 11, 13, 16, 17, 19, 20, 22, 23, 25, 26, 29, 31, 32, 34, 37, 38, 40, 41, 43, 44, 46, 47, 50, 52, 53, 55, 58, 59, 61, or 62") #the number of qubits used is 6 U = QuantumCircuit(6) #implementing the swap gates for rotation #we implement every number and see common behaivor between the numbers for iteration in range(power): if a in [2,61]: U.swap(0,1) U.swap(1,2) U.swap(2,3) U.swap(3,4) U.swap(4,5) if a in [4, 59]: U.swap(0,2) U.swap(1,3) U.swap(2,4) U.swap(3,5) if a in [5, 58]: U.swap(0,2) U.swap(1,3) U.swap(0,4) U.swap(1,5) if a in [8, 55]: U.swap(0,3) U.swap(1,4) U.swap(2,5) if a in [10, 53]: U.swap(0,2) U.swap(1,3) U.swap(0,4) U.swap(1,5) U.swap(0,2) U.swap(1,3) U.swap(0,4) U.swap(1,5) if a in [11, 52]: U.swap(0,1) U.swap(1,2) U.swap(2,3) U.swap(3,4) U.swap(4,5) U.swap(0,1) U.swap(1,2) U.swap(2,3) U.swap(3,4) U.swap(4,5) U.swap(0,1) U.swap(1,2) U.swap(2,3) U.swap(3,4) U.swap(4,5) U.swap(0,1) U.swap(1,2) U.swap(2,3) U.swap(3,4) U.swap(4,5) if a in [13, 50]: U.swap(0,5) U.swap(1,5) U.swap(2,5) U.swap(3,5) U.swap(4,5) if a in [16, 47]: U.swap(0,1) U.swap(1,2) U.swap(2,3) U.swap(3,4) U.swap(4,5) U.swap(0,1) U.swap(1,2) U.swap(2,3) U.swap(3,4) U.swap(4,5) U.swap(0,1) U.swap(1,2) U.swap(2,3) U.swap(3,4) U.swap(4,5) U.swap(0,1) U.swap(1,2) U.swap(2,3) U.swap(3,4) U.swap(4,5) # if a in [17, 46]: # if a in [19, 44]: if a in [20, 43]: U.swap(0,1) U.swap(1,2) U.swap(2,3) U.swap(3,4) U.swap(4,5) if a in [22, 41]: U.swap(0,5) U.swap(1,5) U.swap(2,5) U.swap(3,5) U.swap(4,5) if a in [23, 40]: U.swap(0,2) U.swap(1,3) U.swap(2,4) U.swap(3,5) if a in [25, 38]: U.swap(0,1) U.swap(1,2) U.swap(2,3) U.swap(3,4) U.swap(4,5) # if a in [26, 37]: if a in [29, 34]: U.swap(0,1) U.swap(1,2) U.swap(2,3) U.swap(3,4) U.swap(4,5) if a in [31, 32]: U.swap(0,5) U.swap(1,5) U.swap(2,5) U.swap(3,5) U.swap(4,5) if a in [62]: U.swap(0,3) U.swap(1,4) U.swap(2,5) if a in [5, 11, 13, 17, 19, 23, 25, 29, 31, 37, 41, 43, 47, 53, 55, 59, 61]: for q in range(6): U.x(q) U = U.to_gate() U.name = "%i^%i mod 63" % (a, power) c_U = U.control() return c_U # Specify variables n_count = 10 # number of counting qubits a = 13 def qft_dagger(n): """n-qubit QFTdagger the first n qubits in circ""" qc = QuantumCircuit(n) # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc.name = "QFT†" return qc # Create QuantumCircuit with n_count counting qubits # plus 4 qubits for U to act on qc = QuantumCircuit(n_count + 10, n_count) # Initialize counting qubits # in state |+> for q in range(n_count): qc.h(q) # And auxiliary register in state |1> qc.x(3+n_count) # Do controlled-U operations for q in range(n_count): qc.append(c_amod63(a, 2**q), [q] + [i+n_count for i in range(6)]) # Do inverse-QFT qc.append(qft_dagger(n_count), range(n_count)) # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(fold=-1) # -1 means 'do not fold' aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) qobj = assemble(t_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**n_count) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) Fraction(0.666) # Get fraction that most closely resembles 0.666 # with denominator < 63 Fraction(0.666).limit_denominator(63) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(63) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # the angles of rotations theta1 = pi/4 theta2 = pi/6 # the circuit with two qubits qreg = QuantumRegister(2) creg = ClassicalRegister(2) mycircuit = QuantumCircuit(qreg,creg) # when the second qubit is in |0>, the first qubit is rotated by theta1 mycircuit.x(qreg[1]) mycircuit.cu3(2*theta1,0,0,qreg[1],qreg[0]) mycircuit.x(qreg[1]) # when the second qubit is in |1>, the first qubit is rotated by theta2 mycircuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # we read the unitary matrix job = execute(mycircuit,Aer.get_backend('unitary_simulator'),optimization_level=0) u=job.result().get_unitary(mycircuit,decimals=3) # we print the unitary matrix in nice format for i in range(len(u)): s="" for j in range(len(u)): val = str(u[i][j].real) while(len(val)<8): val = " "+val s = s + val print(s) from math import pi, sin, cos theta1 = pi/4 theta2 = pi/6 print(round(cos(theta1),3),-round(sin(theta1),3),0,0) print(round(sin(theta1),3),-round(cos(theta1),3),0,0) print(0,0,round(cos(theta2),3),-round(sin(theta2),3)) print(0,0,round(sin(theta2),3),-round(cos(theta2),3)) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, sin, cos # the angle of rotation theta1 = pi/23 theta2 = 2*pi/23 theta3 = 4*pi/23 precision = 3 print("a1 = theta3 => sin(a1) = ",round(sin(theta3),precision)) print("a2 = theta2+theta3 => sin(a2) = ",round(sin(theta2+theta3),precision)) print("a3 = theta1 => sin(a3) = ",round(sin(theta1),precision)) print("a4 = theta1+theta2 => sin(a4) = ",round(sin(theta1+theta2),precision)) print() qreg = QuantumRegister(3) creg = ClassicalRegister(3) circuit = QuantumCircuit(qreg,creg) # controlled rotation when the third qubit is |1> circuit.cu3(2*theta1,0,0,qreg[2],qreg[0]) # controlled rotation when the second qubit is |1> circuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # controlled rotation when the third qubit is |0> circuit.x(qreg[2]) circuit.cu3(2*theta3,0,0,qreg[2],qreg[0]) circuit.x(qreg[2]) # read the corresponding unitary matrix job = execute(circuit,Aer.get_backend('unitary_simulator'),optimization_level=0) unitary_matrix=job.result().get_unitary(circuit,decimals=precision) for i in range(len(unitary_matrix)): s="" for j in range(len(unitary_matrix)): val = str(unitary_matrix[i][j].real) while(len(val)<precision+4): val = " "+val s = s + val print(s) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, sin, cos from random import randrange # the angle of rotation k1 = randrange(1,31) theta1 = k1*2*pi/31 k2 = randrange(1,31) theta2 = k2*2*pi/31 k3 = randrange(1,31) theta3 = k3*2*pi/31 max_percentange = 0 # for each stream of length from 1 to 31 for i in range(1,32): # initialize the circuit qreg = QuantumRegister(3) creg = ClassicalRegister(3) circuit = QuantumCircuit(qreg,creg) # Hadamard operators before reading the stream for m in range(3): circuit.h(qreg[m]) # read the stream of length i print("stream of length",i,"is being read") for j in range(i): # controlled rotation when the third qubit is |1> circuit.cu3(2*theta1,0,0,qreg[2],qreg[0]) # controlled rotation when the second qubit is |1> circuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # controlled rotation when the third qubit is |0> circuit.x(qreg[2]) circuit.cu3(2*theta3,0,0,qreg[2],qreg[0]) circuit.x(qreg[2]) # Hadamard operators after reading the stream for m in range(3): circuit.h(qreg[m]) # we measure after reading the whole stream circuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(circuit) print(counts) if '000' in counts.keys(): c = counts['000'] else: c = 0 print('000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange and i != 31: max_percentange = percentange print("the ration of 000 is ",percentange,"%") print() print("maximum percentage of observing unwanted '000' is",max_percentange) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # initialize the circuit qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) # we use the fourth qubit as the auxiliary # apply a rotation to the first qubit when the third and second qubits are in states |0> and |1> # change the state of the third qubit to |1> circuit.x(qreg[2]) # if both the third and second qubits are in states |1>, the state of auxiliary qubit is changed to |1> circuit.ccx(qreg[2],qreg[1],qreg[3]) # the rotation is applied to the first qubit if the state of auxiliary qubit is |1> circuit.cu3(2*pi/6,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[2]) circuit.draw() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi,sin # the angles of rotations theta1 = pi/10 theta2 = 2*pi/10 theta3 = 3*pi/10 theta4 = 4*pi/10 # for verification, print sin(theta)'s print("sin(theta1) = ",round(sin(theta1),3)) print("sin(theta2) = ",round(sin(theta2),3)) print("sin(theta3) = ",round(sin(theta3),3)) print("sin(theta4) = ",round(sin(theta4),3)) print() qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) # the third qubit is in |0> # the second qubit is in |0> circuit.x(qreg[2]) circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta1,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) circuit.x(qreg[2]) # the third qubit is in |0> # the second qubit is in |1> circuit.x(qreg[2]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta2,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[2]) # the third qubit is in |1> # the second qubit is in |0> circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta3,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) # the third qubit is in |1> # the second qubit is in |1> circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta4,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) # read the corresponding unitary matrix job = execute(circuit,Aer.get_backend('unitary_simulator'),optimization_level=0) unitary_matrix=job.result().get_unitary(circuit,decimals=3) for i in range(len(unitary_matrix)): s="" for j in range(len(unitary_matrix)): val = str(unitary_matrix[i][j].real) while(len(val)<7): val = " "+val s = s + val print(s) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi,sin from random import randrange # the angle of rotation k1 = randrange(1,61) theta1 = k1*2*pi/61 k2 = randrange(1,61) theta2 = k2*2*pi/61 k3 = randrange(1,61) theta3 = k3*2*pi/61 k4 = randrange(1,61) theta4 = k4*2*pi/61 max_percentange = 0 # for each stream of length of 1, 11, 21, 31, 41, 51, and 61 for i in [1,11,21,31,41,51,61]: #for i in range(1,62): # initialize the circuit qreg = QuantumRegister(4) creg = ClassicalRegister(4) circuit = QuantumCircuit(qreg,creg) # Hadamard operators before reading the stream for m in range(3): circuit.h(qreg[m]) # read the stream of length i print("stream of length",i,"is being read") for j in range(i): # the third qubit is in |0> # the second qubit is in |0> circuit.x(qreg[2]) circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta1,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) circuit.x(qreg[2]) # the third qubit is in |0> # the second qubit is in |1> circuit.x(qreg[2]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta2,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[2]) # the third qubit is in |1> # the second qubit is in |0> circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta3,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) # the third qubit is in |1> # the second qubit is in |1> circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta4,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) # Hadamard operators after reading the stream for m in range(3): circuit.h(qreg[m]) # we measure after reading the whole stream circuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(circuit) print(counts) if '0000' in counts.keys(): c = counts['0000'] else: c = 0 print('0000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange and i != 61: max_percentange = percentange print("the ration of 0000 is ",percentange,"%") print() print("maximum percentage of observing unwanted '0000' is",max_percentange) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi qreg11 = QuantumRegister(4) creg11 = ClassicalRegister(4) theta = pi/4 # define our quantum circuit mycircuit11 = QuantumCircuit(qreg11,creg11) def ccc_ry(angle,q1,q2,q3,q4): mycircuit11.cu3(angle/2,0,0,q3,q4) mycircuit11.ccx(q1,q2,q4) mycircuit11.cu3(-angle/2,0,0,q3,q4) mycircuit11.ccx(q1,q2,q4) ccc_ry(2*theta,qreg11[3],qreg11[2],qreg11[1],qreg11[0]) mycircuit11.draw(output='mpl') from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi qreg12 = QuantumRegister(4) creg12 = ClassicalRegister(4) theta1 = pi/16 theta2 = 2*pi/16 theta3 = 3*pi/16 theta4 = 4*pi/16 theta5 = 5*pi/16 theta6 = 6*pi/16 theta7 = 7*pi/16 theta8 = 8*pi/16 # define our quantum circuit mycircuit12 = QuantumCircuit(qreg12,creg12) def ccc_ry(angle,q1,q2,q3,q4): mycircuit12.cu3(angle/2,0,0,q3,q4) mycircuit12.ccx(q1,q2,q4) mycircuit12.cu3(-angle/2,0,0,q3,q4) mycircuit12.ccx(q1,q2,q4) mycircuit12.x(qreg12[3]) mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[1]) ccc_ry(2*theta1,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) mycircuit12.x(qreg12[1]) mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[3]) mycircuit12.x(qreg12[3]) mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[1]) ccc_ry(2*theta2,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) #mycircuit12.x(qreg12[1]) mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[3]) mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[1]) ccc_ry(2*theta3,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) mycircuit12.x(qreg12[1]) #mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[3]) mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[1]) ccc_ry(2*theta4,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) #mycircuit12.x(qreg12[1]) #mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[3]) mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[1]) ccc_ry(2*theta5,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) mycircuit12.x(qreg12[1]) mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[3]) mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[1]) ccc_ry(2*theta6,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) #mycircuit12.x(qreg12[1]) mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[2]) mycircuit12.x(qreg12[1]) ccc_ry(2*theta7,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) mycircuit12.x(qreg12[1]) #mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[3]) #mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[1]) ccc_ry(2*theta8,qreg12[3],qreg12[2],qreg12[1],qreg12[0]) #mycircuit12.x(qreg12[1]) #mycircuit12.x(qreg12[2]) #mycircuit12.x(qreg12[3]) job = execute(mycircuit12,Aer.get_backend('unitary_simulator'),optimization_level=0) u=job.result().get_unitary(mycircuit12,decimals=3) for i in range(len(u)): s="" for j in range(len(u)): val = str(u[i][j].real) while(len(val)<7): val = " "+val s = s + val print(s)
https://github.com/qclib/qclib
qclib
# 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. """Isometry tests.""" import unittest import numpy as np from ddt import ddt, data from qiskit.quantum_info.random import random_unitary from qiskit import BasicAer from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit import execute from qiskit.test import QiskitTestCase from qiskit.compiler import transpile from qiskit.quantum_info import Operator from qiskit.extensions.quantum_initializer.isometry import Isometry @ddt class TestIsometry(QiskitTestCase): """Qiskit isometry tests.""" @data( np.eye(2, 2), random_unitary(2, seed=868540).data, np.eye(4, 4), random_unitary(4, seed=16785).data[:, 0], np.eye(4, 4)[:, 0:2], random_unitary(4, seed=660477).data, np.eye(4, 4)[:, np.random.RandomState(seed=719010).permutation(4)][:, 0:2], np.eye(8, 8)[:, np.random.RandomState(seed=544326).permutation(8)], random_unitary(8, seed=247924).data[:, 0:4], random_unitary(8, seed=765720).data, random_unitary(16, seed=278663).data, random_unitary(16, seed=406498).data[:, 0:8], ) def test_isometry(self, iso): """Tests for the decomposition of isometries from m to n qubits""" if len(iso.shape) == 1: iso = iso.reshape((len(iso), 1)) num_q_output = int(np.log2(iso.shape[0])) num_q_input = int(np.log2(iso.shape[1])) q = QuantumRegister(num_q_output) qc = QuantumCircuit(q) qc.isometry(iso, q[:num_q_input], q[num_q_input:]) # Verify the circuit can be decomposed self.assertIsInstance(qc.decompose(), QuantumCircuit) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"]) # Simulate the decomposed gate simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) iso_from_circuit = unitary[::, 0 : 2**num_q_input] iso_desired = iso self.assertTrue(np.allclose(iso_from_circuit, iso_desired)) @data( np.eye(2, 2), random_unitary(2, seed=99506).data, np.eye(4, 4), random_unitary(4, seed=673459).data[:, 0], np.eye(4, 4)[:, 0:2], random_unitary(4, seed=124090).data, np.eye(4, 4)[:, np.random.RandomState(seed=889848).permutation(4)][:, 0:2], np.eye(8, 8)[:, np.random.RandomState(seed=94795).permutation(8)], random_unitary(8, seed=986292).data[:, 0:4], random_unitary(8, seed=632121).data, random_unitary(16, seed=623107).data, random_unitary(16, seed=889326).data[:, 0:8], ) def test_isometry_tolerance(self, iso): """Tests for the decomposition of isometries from m to n qubits with a custom tolerance""" if len(iso.shape) == 1: iso = iso.reshape((len(iso), 1)) num_q_output = int(np.log2(iso.shape[0])) num_q_input = int(np.log2(iso.shape[1])) q = QuantumRegister(num_q_output) qc = QuantumCircuit(q) # Compute isometry with custom tolerance qc.isometry(iso, q[:num_q_input], q[num_q_input:], epsilon=1e-3) # Verify the circuit can be decomposed self.assertIsInstance(qc.decompose(), QuantumCircuit) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"]) # Simulate the decomposed gate simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) iso_from_circuit = unitary[::, 0 : 2**num_q_input] self.assertTrue(np.allclose(iso_from_circuit, iso)) @data( np.eye(2, 2), random_unitary(2, seed=272225).data, np.eye(4, 4), random_unitary(4, seed=592640).data[:, 0], np.eye(4, 4)[:, 0:2], random_unitary(4, seed=714210).data, np.eye(4, 4)[:, np.random.RandomState(seed=719934).permutation(4)][:, 0:2], np.eye(8, 8)[:, np.random.RandomState(seed=284469).permutation(8)], random_unitary(8, seed=656745).data[:, 0:4], random_unitary(8, seed=583813).data, random_unitary(16, seed=101363).data, random_unitary(16, seed=583429).data[:, 0:8], ) def test_isometry_inverse(self, iso): """Tests for the inverse of isometries from m to n qubits""" if len(iso.shape) == 1: iso = iso.reshape((len(iso), 1)) num_q_output = int(np.log2(iso.shape[0])) q = QuantumRegister(num_q_output) qc = QuantumCircuit(q) qc.append(Isometry(iso, 0, 0), q) qc.append(Isometry(iso, 0, 0).inverse(), q) result = Operator(qc) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/sarthag/Quantum-Algos-using-Qiskit
sarthag
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import IBMQ, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector from qiskit.extensions import Initialize from qiskit_textbook.tools import random_state, array_to_latex import matplotlib.pyplot %pylab inline #Defining srtucture of the circuit qr = QuantumRegister(3, name="q") crz = ClassicalRegister(1, name="crz") crx = ClassicalRegister(1, name="crx") circuit = QuantumCircuit(qr, crz, crx) #Creating a qubit in random state psi = random_state(1) # Display it nicely array_to_latex(psi, pretext="|\\psi\\rangle =") # Show it on a Bloch sphere plot_bloch_multivector(psi) init_gate = Initialize(psi) init_gate.label = "init" #append inti gate to the qc circuit.append(init_gate, [0]) circuit.barrier() #Creating entanglement in q1 and q2 circuit.h(1) circuit.cx(1,2) circuit.barrier() #Defining gates for sender circuit.cx(0,1) circuit.h(0) circuit.barrier() #Measuring the bits and sending it to classical bits circuit.measure((0,1), (0,1)) #reciever gates circuit.x(2).c_if(crx, 1) circuit.z(2).c_if(crz, 1) circuit.draw('mpl') #Using Statevector simuator sv_sim = Aer.get_backend('statevector_simulator') qobj = assemble(circuit) out_vector = sv_sim.run(qobj).result().get_statevector() plot_bloch_multivector(out_vector) #To check the gates followed in order to confirm teleportation circuit.barrier() inverse_init_gate = init_gate.gates_to_uncompute() circuit.append(inverse_init_gate, [2]) #To measure the third qubit result_cb = ClassicalRegister(1) circuit.add_register(result_cb) circuit.measure(2,2) circuit.draw('mpl') #Using Quasm Simulator qasm_sim = Aer.get_backend('qasm_simulator') t_qc = transpile(circuit, qasm_sim) qobj = assemble(t_qc) counts = qasm_sim.run(qobj).result().get_counts() plot_histogram(counts)
https://github.com/pedroripper/qiskit_tutoriais
pedroripper
from qiskit import * import numpy as np # Podemos aplicar uma matriz unitária em um circuito matriz = [[1,0], [0,1]] circuito = QuantumCircuit(1) circuito.unitary(matriz,[0]) circuito.draw(output='mpl') # É possivel dar nome para essas operações circuito = QuantumCircuit(1) circuito.unitary(matriz,[0],label='minha porta') circuito.draw(output='mpl')
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """Test calling passes (passmanager-less)""" from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import ZGate from qiskit.transpiler.passes import Unroller from qiskit.test import QiskitTestCase from qiskit.exceptions import QiskitError from qiskit.transpiler import PropertySet from ._dummy_passes import PassD_TP_NR_NP, PassE_AP_NR_NP, PassN_AP_NR_NP class TestPassCall(QiskitTestCase): """Test calling passes (passmanager-less).""" def assertMessageLog(self, context, messages): """Checks the log messages""" self.assertEqual([record.message for record in context.records], messages) def test_transformation_pass(self): """Call a transformation pass without a scheduler""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr, name="MyCircuit") pass_d = PassD_TP_NR_NP(argument1=[1, 2]) with self.assertLogs("LocalLogger", level="INFO") as cm: result = pass_d(circuit) self.assertMessageLog(cm, ["run transformation pass PassD_TP_NR_NP", "argument [1, 2]"]) self.assertEqual(circuit, result) def test_analysis_pass_dict(self): """Call an analysis pass without a scheduler (property_set dict)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr, name="MyCircuit") property_set = {"another_property": "another_value"} pass_e = PassE_AP_NR_NP("value") with self.assertLogs("LocalLogger", level="INFO") as cm: result = pass_e(circuit, property_set) self.assertMessageLog(cm, ["run analysis pass PassE_AP_NR_NP", "set property as value"]) self.assertEqual(property_set, {"another_property": "another_value", "property": "value"}) self.assertIsInstance(property_set, dict) self.assertEqual(circuit, result) def test_analysis_pass_property_set(self): """Call an analysis pass without a scheduler (PropertySet dict)""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr, name="MyCircuit") property_set = PropertySet({"another_property": "another_value"}) pass_e = PassE_AP_NR_NP("value") with self.assertLogs("LocalLogger", level="INFO") as cm: result = pass_e(circuit, property_set) self.assertMessageLog(cm, ["run analysis pass PassE_AP_NR_NP", "set property as value"]) self.assertEqual( property_set, PropertySet({"another_property": "another_value", "property": "value"}) ) self.assertIsInstance(property_set, PropertySet) self.assertEqual(circuit, result) def test_analysis_pass_remove_property(self): """Call an analysis pass that removes a property without a scheduler""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr, name="MyCircuit") property_set = {"to remove": "value to remove", "to none": "value to none"} pass_e = PassN_AP_NR_NP("to remove", "to none") with self.assertLogs("LocalLogger", level="INFO") as cm: result = pass_e(circuit, property_set) self.assertMessageLog( cm, [ "run analysis pass PassN_AP_NR_NP", "property to remove deleted", "property to none noned", ], ) self.assertEqual(property_set, PropertySet({"to none": None})) self.assertIsInstance(property_set, dict) self.assertEqual(circuit, result) def test_error_unknown_defn_unroller_pass(self): """Check for proper error message when unroller cannot find the definition of a gate.""" circuit = ZGate().control(2).definition basis = ["u1", "u2", "u3", "cx"] unroller = Unroller(basis) with self.assertRaises(QiskitError) as cm: unroller(circuit) exp_msg = ( "Error decomposing node of instruction 'p': 'NoneType' object has no" " attribute 'global_phase'. Unable to define instruction 'u' in the basis." ) self.assertEqual(exp_msg, cm.exception.message)
https://github.com/qBraid/qBraid
qBraid
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # 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. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/arian-code/nptel_quantum_assignments
arian-code
import numpy as np from qiskit import * # Create a Quantum Circuit acting on a quantum register of three qubits circ = QuantumCircuit(3) # Add a H gate on qubit 0, putting this qubit in superposition. circ.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. circ.cx(0, 1) # Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting # the qubits in a GHZ state. circ.cx(0, 2) circ.draw('mpl') # Import Aer from qiskit import Aer # Run the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') # Create a Quantum Program for execution job = backend.run(circ) result = job.result() outputstate = result.get_statevector(circ, decimals=3) print(outputstate) from qiskit.visualization import plot_state_city plot_state_city(outputstate) from qiskit.visualization import plot_state_qsphere %matplotlib inline plot_state_qsphere(outputstate)
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
Qiskit-Extensions
from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp from circuit_knitting.cutting import ( partition_problem, generate_cutting_experiments, ) circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) observable = SparsePauliOp(["ZZ"]) partitioned_problem = partition_problem( circuit=circuit, partition_labels="AB", observables=observable.paulis ) subcircuits = partitioned_problem.subcircuits subobservables = partitioned_problem.subobservables subexperiments, coefficients = generate_cutting_experiments( circuits=subcircuits, observables=subobservables, num_samples=1000, ) from circuit_knitting.utils.simulation import ExactSampler exact_sampler = ExactSampler() results = { label: exact_sampler.run(subexperiment).result() for label, subexperiment in subexperiments.items() }
https://github.com/QuantumVic/discrete-time-quantum-walks
QuantumVic
from qiskit import * import numpy as np import matplotlib as mpl from qiskit.tools.visualization import plot_histogram, plot_state_city from qiskit.tools.monitor import job_monitor state_sim = Aer.get_backend('statevector_simulator') qasm_sim = Aer.get_backend('qasm_simulator') unitary_sim = Aer.get_backend('unitary_simulator') qiskit.__qiskit_version__ ## developed in q0.14.0, q-terra0.11.0 ## Definition of c_Increment, c_Decrement gates def increment(qc,qr): """controlled-increment gate, cf. PhysRevA.72.032329""" for i in range(num_qubits - 1): qc.mct(qr[0:num_qubits - 1 - i], qr[num_qubits - 1 - i], qr_aux) def decrement(qc,qr): """controlled-decrement gate, cf. PhysRevA.72.032329""" for i in range(num_qubits - 1): qc.mct(qr[0:i+1], qr[i+1], qr_aux) ## Definition of QW step def quantum_walk(qc,qr,n): """implement DTQW on a previously defined circuit and register cf. PhysRevA.72.032329""" for i in range(n): ## coin operator qc.h(qr[0]) ## shift right increment(qc,qr) ## shift left qc.x(qr[0]) decrement(qc,qr) ## back to original state qc.x(qr[0]) qc.barrier() ## PARAMETERS : number of qubits and steps num_qubits = 4 num_steps = 1 ## Define qRegister and cRegister qr = QuantumRegister(num_qubits, 'qr') cr = ClassicalRegister(num_qubits - 1, 'cr') ## Define qCircuit ## We need aux qubits for the mct gates: (num_qubits - 3) if num_qubits > 3: qr_aux = QuantumRegister(num_qubits - 3, 'aux') qc = QuantumCircuit(qr, qr_aux, cr) else: qr_aux = None qc = QuantumCircuit(qr, cr) ## Initialization of the nodes qc.x(qr[num_qubits-1]) # Initial state = 1000000...0000 qc.barrier() ## Initialization of the coin (symmetrical) qc.h(qr[0]) qc.s(qr[0]) qc.barrier() ## Repeat the quantum walk for num_steps quantum_walk(qc, qr, num_steps) ## Measure the node qubits qc.measure(qr[1:num_qubits], cr) qc.draw(output='mpl') qc.depth() job = execute(qc, backend = qasm_sim) shots = job.result().get_counts() plot_histogram(shots)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) with pulse.build() as hahn_echo: with pulse.align_equispaced(duration=100): pulse.play(x90, d0) pulse.play(x180, d0) pulse.play(x90, d0) hahn_echo.draw()
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### added y gate ### qc.cx(0, 1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) ### added h gate ### qc.h(0) return qc