repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.result import QuasiDistribution from qiskit_aer.primitives import Sampler from qiskit_finance.applications.optimization import PortfolioOptimization from qiskit_finance.data_providers import RandomDataProvider from qiskit_optimization.algorithms import MinimumEigenOptimizer import numpy as np import matplotlib.pyplot as plt import datetime # set number of assets (= number of qubits) num_assets = 4 seed = 123 # Generate expected return and covariance matrix from (random) time-series stocks = [("TICKER%s" % i) for i in range(num_assets)] data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() mu = data.get_period_return_mean_vector() sigma = data.get_period_return_covariance_matrix() # plot sigma plt.imshow(sigma, interpolation="nearest") plt.show() q = 0.5 # set risk factor budget = num_assets // 2 # set budget penalty = num_assets # set parameter to scale the budget penalty term portfolio = PortfolioOptimization( expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget ) qp = portfolio.to_quadratic_program() qp def print_result(result): selection = result.x value = result.fval print("Optimal: selection {}, value {:.4f}".format(selection, value)) eigenstate = result.min_eigen_solver_result.eigenstate probabilities = ( eigenstate.binary_probabilities() if isinstance(eigenstate, QuasiDistribution) else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()} ) print("\n----------------- Full result ---------------------") print("selection\tvalue\t\tprobability") print("---------------------------------------------------") probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True) for k, v in probabilities: x = np.array([int(i) for i in list(reversed(k))]) value = portfolio.to_quadratic_program().objective.evaluate(x) print("%10s\t%.4f\t\t%.4f" % (x, value, v)) exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print_result(result) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=500) ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qp) print_result(result) algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(qp) print_result(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/AlphaMiyaL/Qiskit-Quantum-Journey
AlphaMiyaL
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ from qiskit.visualization import plot_histogram, plot_bloch_multivector ### Creating 3 qubit and 2 classical bits in each separate register qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(1) teleportation_circuit = QuantumCircuit(qr, crz, crx) ### A third party eve helps to create an entangled state def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a, b) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, a, b): qc.cx(a, b) qc.h(a) teleportation_circuit.barrier() alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() def measure_and_send(qc, a, b): qc.barrier() qc.measure(a,0) qc.measure(b,1) teleportation_circuit.barrier() measure_and_send(teleportation_circuit, 0, 1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) qc.z(qubit).c_if(crz, 1) teleportation_circuit.barrier() bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() from qiskit.extensions import Initialize import math qc = QuantumCircuit(1) initial_state = [0,1] init_gate = Initialize(initial_state) # qc.append(initialize_qubit, [0]) qr = QuantumRegister(3) # Protocol uses 3 qubits crz = ClassicalRegister(1) # and 2 classical registers crx = ClassicalRegister(1) qc = QuantumCircuit(qr, crz, crx) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) # Bob decodes qubits bob_gates(qc, 2, crz, crx) qc.draw() backend = BasicAer.get_backend('statevector_simulator') out_vector = execute(qc, backend).result().get_statevector() plot_bloch_multivector(out_vector) inverse_init_gate = init_gate.gates_to_uncompute() qc.append(inverse_init_gate, [2]) qc.draw() cr_result = ClassicalRegister(1) qc.add_register(cr_result) qc.measure(2,2) qc.draw() backend = BasicAer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1024).result().get_counts() plot_histogram(counts) def bob_gates(qc, a, b, c): qc.cz(a, c) qc.cx(b, c) qc = QuantumCircuit(3,1) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) qc.barrier() # Alice sends classical bits to Bob bob_gates(qc, 0, 1, 2) # We undo the initialisation process qc.append(inverse_init_gate, [2]) # See the results, we only care about the state of qubit 2 qc.measure(2,0) # View the results: qc.draw() from qiskit import IBMQ IBMQ.save_account('### IMB TOKEN ') IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() from qiskit.providers.ibmq import least_busy backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and not b.configuration().simulator and b.status().operational==True)) job_exp = execute(qc, backend=backend, shots=8192) exp_result = job_exp.result() exp_measurement_result = exp_result.get_counts(qc) print(exp_measurement_result) plot_histogram(exp_measurement_result) error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \ * 100./ sum(list(exp_measurement_result.values())) print("The experimental error rate : ", error_rate_percent, "%")
https://github.com/WhenTheyCry96/qiskitHackathon2022
WhenTheyCry96
%load_ext autoreload %autoreload 2 import os import warnings import numpy as np import pyEPR as epr import qiskit_metal as metal from collections import OrderedDict import scqubits as scq from scipy.constants import c, h, pi, hbar, e from qiskit_metal import designs, draw, MetalGUI, Dict, Headings from qiskit_metal.qlibrary.tlines.meandered import RouteMeander from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors from qiskit_metal.analyses.quantization import LOManalysis, EPRanalysis from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL from qiskit_metal.qlibrary.lumped.cap_3_interdigital import Cap3Interdigital from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem, QuantumSystemRegistry ws_path = os.getcwd() warnings.filterwarnings("ignore") design = designs.DesignPlanar() design.overwrite_enabled = True #constants: phi0 = h/(2*e) varphi0 = phi0/(2*pi) # project target parameters f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz f_rList = f_qList + 1.8 # GHz L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH # initial CPW readout lengths def find_resonator_length(frequency, line_width, line_gap, N): #frequency in GHz #line_width/line_gap in um #N -> 2 for lambda/2, 4 for lambda/4 [lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6, line_gap*10**-6, 750*10**-6, 200*10**-9) return str(lambdaG/N*10**3)+" mm" find_resonator_length(f_rList, 10, 6, 2) design.chips.main.size_x = '12mm' design.chips.main.size_y = '10mm' gui = MetalGUI(design) design.delete_all_components() design_span_x = 5 design_span_y = 3 half_chip_width = design_span_x / 2 half_chip_height = design_span_y / 2 connection_pads_options = dict( a = dict(loc_W=1, loc_H=-1), b = dict(loc_W=1, loc_H=1), c = dict(loc_W=-1, loc_H=-1) ) connection23_pads_options = dict( a = dict(loc_W=1, loc_H=-1), c = dict(loc_W=-1, loc_H=-1) ) transmons = [] transmons.append(TransmonPocketCL(design, 'Q1', options=dict(pos_x=f'-{half_chip_width}mm', pos_y=f'{-half_chip_height}mm', connection_pads=dict(**connection_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q2', options=dict(pos_x=f'0mm', pos_y=f'{half_chip_height}mm', orientation=-90, connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q3', options=dict(pos_x=f'0mm', pos_y=f'{-half_chip_height}mm', orientation=90, connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options)))) transmons.append(TransmonPocketCL(design, 'Q4', options=dict(pos_x=f'{half_chip_width}mm', pos_y=f'{half_chip_height}mm', orientation=180, connection_pads=dict(**connection_pads_options)))) gui.rebuild() gui.autoscale() fillet='99.99um' options = Dict( meander=Dict( lead_start='0.1mm', lead_end='0.1mm', asymmetry='0 um') ) def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str, length: str, asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False): """Connect two pins with a CPW.""" myoptions = Dict( pin_inputs=Dict( start_pin=Dict( component=component1, pin=pin1), end_pin=Dict( component=component2, pin=pin2)), lead=Dict( start_straight=start_strght, end_straight=end_strght ), total_length=length, fillet = '99.9um') myoptions.update(options) myoptions.meander.asymmetry = asymmetry myoptions.meander.lead_direction_inverted = 'true' if flip else 'false' return RouteMeander(design, component_name, myoptions) asym_h = 100 asym_v = 100 cpw = [] cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm')) gui.rebuild() gui.autoscale() readouts_lwc = [] control_lwc = [] offset_x = 0 offset_y = 1 #Readouts readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1', options = dict( pos_x = '-5mm', pos_y = f'-{half_chip_height+offset_y}mm', lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2', options = dict( pos_x = '-1mm', pos_y = '4mm', orientation = -90, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3', options = dict( pos_x = '1mm', pos_y = '-4mm', orientation = 90, lead_length = '30um'))) readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4', options = dict( pos_x = '5mm', pos_y = f'{half_chip_height+offset_y}mm', orientation = 180, lead_length = '30um'))) #Controls control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1', options = dict( pos_x = '-5mm', pos_y = '2mm', lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2', options = dict( pos_x = '4mm', pos_y = '4mm', orientation = -90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3', options = dict( pos_x = '-4mm', pos_y = '-4mm', orientation = 90, lead_length = '30um'))) control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4', options = dict( pos_x = '5mm', pos_y = '-2mm', orientation = 180, lead_length = '30um'))) gui.rebuild() gui.autoscale() readout_lines = [] asym_14 = 700 asym_23 = 700 options = Dict( lead=Dict( start_straight='330um', end_straight='0um'), fillet='99.99um') readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um')) options = Dict( lead=Dict( start_straight='430um', end_straight='0um'), fillet='99.99um') readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um')) readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um')) readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um')) gui.rebuild() gui.autoscale() control_lines = [] def connectRouteAnchor(name: str, component1: str, pin1: str, component2: str, pin2: str, anchor_points: OrderedDict) -> RouteAnchors: options_line_cl = dict( pin_inputs = dict(start_pin = dict(component = component1, pin = pin1), end_pin = dict(component = component2, pin = pin2)), anchors = anchor_points, lead = dict(start_straight = '200um', end_straight = '225um'), fillet = fillet ) return RouteAnchors(design, name, options_line_cl) anchors1c = OrderedDict() anchors1c[0] = np.array([-4, -1.42]) anchors1c[1] = np.array([-4, 2]) control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c)) anchors2c = OrderedDict() anchors2c[0] = np.array([0.08, 3.25]) anchors2c[1] = np.array([4, 3.25]) control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c)) anchors3c = OrderedDict() anchors3c[0] = np.array([-0.08, -3.25]) anchors3c[1] = np.array([-4, -3.25]) control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c)) anchors4c = OrderedDict() anchors4c[0] = np.array([4, 1.42]) anchors4c[1] = np.array([4, -2]) control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c)) gui.rebuild() gui.autoscale() gui.screenshot(name="full_design.png") # constants: phi0 = h/(2*e) varphi0 = phi0/(2*pi) # project target parameters f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz f_rList = f_qList + 1.8 # GHz L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH # initial CPW readout lengths def find_resonator_length(frequency, line_width, line_gap, N): #frequency in GHz #line_width/line_gap in um #N -> 2 for lambda/2, 4 for lambda/4 [lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6, line_gap*10**-6, 750*10**-6, 200*10**-9) return str(lambdaG/N*10**3)+" mm" find_resonator_length(f_rList, 10, 6, 2) # CPW busline length is determined to be 7 mm cpw[0].options.total_length = '7.0mm' cpw[1].options.total_length = '7.0mm' cpw[2].options.total_length = '7.0mm' cpw[3].options.total_length = '7.0mm' gui.rebuild() gui.autoscale() # qubit 1 design target f: 5.25 GHz # readout resonator target f: 7.05 GHz transmons[0].options.pad_gap = '40um' transmons[0].options.pad_width = '550um' # 405 transmons[0].options.pad_height = '120um' readout_lines[3].options.total_length = '11.2mm' # qubit 2 design target f: 5.42 GHz # readout resonator target f: 7.22 GHz transmons[1].options.pad_gap = '40um' transmons[1].options.pad_width = '390um' # 405 transmons[1].options.pad_height = '120um' transmons[1].options.connection_pads.d.pad_gap='8um' transmons[1].options.connection_pads.a.pad_gap='8um' transmons[1].options.connection_pads.c.pad_gap='8um' transmons[1].options.connection_pads.d.pad_width='140um' transmons[1].options.connection_pads.a.pad_width='140um' transmons[1].options.connection_pads.c.pad_width='150um' from qiskit_metal.analyses.quantization import EPRanalysis, LOManalysis c1 = LOManalysis(design, "q3d") q3d1 = c1.sim.renderer q3d1.start() q3d1.activate_ansys_design("Q2only_busopen", 'capacitive') q3d1.render_design(['Q2', 'R2', 'cpw1', 'cpw5', 'ol2', 'line_cl2', 'CL2'], [('cpw5', 'end'),('cpw1', 'start')]) q3d1.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05) q3d1.analyze_setup("Setup") c1.sim.capacitance_matrix, c1.sim.units = q3d1.get_capacitance_matrix() c1.sim.capacitance_all_passes, _ = q3d1.get_capacitance_all_passes() c1.sim.capacitance_matrix import scqubits as scq from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem, QuantumSystemRegistry from scipy.constants import speed_of_light as c_light import matplotlib.pyplot as plt %matplotlib inline # Cell 2: Transmon-2 opt2 = dict( cap_mat = c1.sim.capacitance_matrix, ind_dict = {('pad_top_Q2', 'pad_bot_Q2'): 12}, # junction inductance in nH jj_dict = {('pad_top_Q2', 'pad_bot_Q2'): 'j2'}, cj_dict = {('pad_top_Q2', 'pad_bot_Q2'): 1}, # junction capacitance in fF ) cell_2 = Cell(opt2) # subsystem 1: Transmon-2 transmon2 = Subsystem(name='transmon2', sys_type='TRANSMON', nodes=['j2']) # Resonator Subsystems q_opts = dict( Z0 = 50, # characteristic impedance in Ohm vp = 0.404314 * c_light # phase velocity ) ro2 = Subsystem(name='c_connector_pad_Q2', sys_type='TL_RESONATOR', nodes=['c_connector_pad_Q2'], q_opts=dict(f_res = 7.22, **q_opts)) coup12 = Subsystem(name='a_connector_pad_Q2', sys_type='TL_RESONATOR', nodes=['a_connector_pad_Q2'], q_opts=dict(f_res = 7.5, **q_opts)) coup24 = Subsystem(name='d_connector_pad_Q2', sys_type='TL_RESONATOR', nodes=['d_connector_pad_Q2'], q_opts=dict(f_res = 7.5, **q_opts)) composite_sys = CompositeSystem( subsystems=[transmon2, ro2, coup12, coup24], cells=[cell_2], grd_node='ground_main_plane', nodes_force_keep=['c_connector_pad_Q2', 'a_connector_pad_Q2', 'd_connector_pad_Q2'] ) cg = composite_sys.circuitGraph() print(cg) hilbertspace = composite_sys.create_hilbertspace() print(hilbertspace) hilbertspace = composite_sys.add_interaction() hilbertspace.hamiltonian() hamiltonian_results = composite_sys.hamiltonian_results(hilbertspace, evals_count=30) composite_sys.compute_gs() transmons[1].options.connection_pads.d.pad_gap # qubit 3 design target f: 5.58 GHz # readout resonator target f: 7.38 GHz transmons[2].options.pad_gap = '40um' transmons[2].options.pad_width = '370um' # 405 transmons[2].options.pad_height = '120um' transmons[2].options.connection_pads.d.pad_gap='10um' transmons[2].options.connection_pads.a.pad_gap='10um' transmons[2].options.connection_pads.c.pad_gap='10um' from qiskit_metal.analyses.quantization import EPRanalysis, LOManalysis from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem, QuantumSystemRegistry c1 = LOManalysis(design, "q3d") q3d1 = c1.sim.renderer q3d1.start() q3d1.activate_ansys_design("Q3only_busopen_370_gap_reduced", 'capacitive') q3d1.render_design(['Q3', 'R3', 'cpw3', 'cpw4', 'ol3', 'line_cl3', 'CL3'], [('cpw3', 'start'),('cpw4', 'end')]) q3d1.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5,percent_error=0.05) q3d1.analyze_setup("Setup") c1.sim.capacitance_matrix, c1.sim.units = q3d1.get_capacitance_matrix() c1.sim.capacitance_all_passes, _ = q3d1.get_capacitance_all_passes() c1.sim.capacitance_matrix path3 = "./capacitance_matrices/Project19_Q3only_busopen_460.txt" t3_mat, _, _, _ = load_q3d_capacitance_matrix(path3) t3_mat opt3 = dict( cap_mat = t3_mat, ind_dict = {('pad_top_Q3', 'pad_bot_Q3'): 12}, # junction inductance in nH jj_dict = {('pad_top_Q3', 'pad_bot_Q3'): 'j3'}, cj_dict = {('pad_top_Q3', 'pad_bot_Q3'): 1}, # junction capacitance in fF ) cell_3 = Cell(opt3) transmon3 = Subsystem(name='transmon3', sys_type='TRANSMON', nodes=['j3']) # Resonator Subsystems from scipy.constants import speed_of_light as c_light q_opts = dict( Z0 = 50, # characteristic impedance in Ohm vp = 0.404314 * c_light # phase velocity ) ro3 = Subsystem(name='c_connector_pad_Q3', sys_type='TL_RESONATOR', nodes=['c_connector_pad_Q3'], q_opts=dict(f_res = 7.38, **q_opts)) coup34 = Subsystem(name='a_connector_pad_Q3', sys_type='TL_RESONATOR', nodes=['a_connector_pad_Q3'], q_opts=dict(f_res = 7.5, **q_opts)) coup31 = Subsystem(name='d_connector_pad_Q3', sys_type='TL_RESONATOR', nodes=['d_connector_pad_Q3'], q_opts=dict(f_res = 7.5, **q_opts)) composite_sys = CompositeSystem( subsystems=[transmon3, ro3, coup34, coup31], cells=[cell_3], grd_node='ground_main_plane', nodes_force_keep=['c_connector_pad_Q3', 'a_connector_pad_Q3', 'd_connector_pad_Q3'] ) cg = composite_sys.circuitGraph() print(cg) hilbertspace = composite_sys.create_hilbertspace() print(hilbertspace) # Convert the hilbert space into # "Interaction Picture" hilbertspace = composite_sys.add_interaction() hilbertspace.hamiltonian() t3_mat = c1.sim.capacitance_matrix # qubit 4 design target f: 5.75 GHz # readout resonator target f: 7.55 GHz # tuning parameters C_JJ4f = 2 L_JJ4f = 9.8 C_JJ4 = str(C_JJ4f)+' fF' L_JJ4 = str(L_JJ4f)+' nH' transmons[3].options.pad_gap = '35um' transmons[3].options.pad_width = '510um' transmons[3].options.pad_height = '125um' transmons[3].options.connection_pads.c.pad_gap = '30um' transmons[3].options.connection_pads.a.pad_gap = '15um' # cpw5 transmons[3].options.connection_pads.a.pad_width = '40um' # cpw5 transmons[3].options.connection_pads.b.pad_gap = '15um' # cpw3 transmons[3].options.connection_pads.b.pad_width = '40um' # cpw3 readout_lines[3].options.total_length = '7.5mm' gui.rebuild() gui.autoscale() # EPR analysis eig_q4 = EPRanalysis(design, "hfss") hfss4 = eig_q4.sim.renderer hfss4.start() hfss4.activate_ansys_design("TransmonQ4", 'eigenmode') hfss4.render_design(['Q4', 'ol4', 'cpw3', 'cpw5'], [('cpw3', 'end'), ('cpw5', 'start'), ('ol4', 'end')]) # Analysis properties setup4 = hfss4.pinfo.setup setup4.n_modes = 6 setup4.passes = 10 setup4.min_freq_ghz = 4 print(f""" Number of eigenmodes to find = {setup4.n_modes} Number of simulation passes = {setup4.passes} Convergence freq max delta percent diff = {setup4.delta_f} """) pinfo4 = hfss4.pinfo pinfo4.design.set_variable('Lj4', L_JJ4) pinfo4.design.set_variable('Cj4', C_JJ4) setup4.analyze() eig_q4.sim.convergence_t, eig_q4.sim.convergence_f, _ = hfss4.get_convergences() eig_q4.sim.plot_convergences() pinfo4.junctions['jj'] = {'Lj_variable': 'Lj4', 'rect': 'JJ_rect_Lj_Q4_rect_jj', 'line': 'JJ_Lj_Q4_rect_jj_', 'Cj_variable': 'Cj4'} pinfo4.validate_junction_info() pinfo4.dissipative['dielectrics_bulk'] = ['main'] hfss4.set_mode(1, "Setup") hfss4.modeler._modeler.ShowWindow() hfss4.plot_fields('main') eprd4 = epr.DistributedAnalysis(pinfo4) ℰ_elec = eprd4.calc_energy_electric() ℰ_elec_substrate = eprd4.calc_energy_electric(None, 'main') ℰ_mag = eprd4.calc_energy_magnetic() print(f""" ℰ_elec_all = {ℰ_elec} ℰ_elec_substrate = {ℰ_elec_substrate} EPR of substrate = {ℰ_elec_substrate / ℰ_elec * 100 :.1f}% ℰ_mag_all = {ℰ_mag} ℰ_mag % of ℰ_elec_all = {ℰ_mag / ℰ_elec * 100 :.1f}% """) eprd4.do_EPR_analysis() #epra4 = epr.QuantumAnalysis(eprd4.data_filename) #epra4.analyze_all_variations(cos_trunc = 8, fock_trunc = 7) c4 = LOManalysis(design, "q3d") q3d4 = c4.sim.renderer q3d4.start() q3d4.activate_ansys_design("TransmonQ4_q3d", 'capacitive') q3d4.render_design(['Q4'], [('Q4', 'a'),('Q4', 'b'),('Q4', 'c')]) q3d4.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5, percent_error=0.1) q3d4.analyze_setup("Setup") c4.sim.capacitance_matrix, c4.sim.units = q3d4.get_capacitance_matrix() c4.sim.capacitance_all_passes, _ = q3d4.get_capacitance_all_passes() c4.sim.capacitance_matrix c4.setup.junctions = Dict({'Lj':L_JJ4f, 'Cj':C_JJ4f}) c4.setup.freq_readout = 7.45 c4.setup.freq_bus = [8.25, 8.25, 15] c4.run_lom() c4.lumped_oscillator_all QuantumSystemRegistry.registry() # Q4 path4= ws_path+"/Project71_TransmonQ4_q3d.txt" t4_mat, _, _, _ = load_q3d_capacitance_matrix(path4) # Cell 4 Transmon-4 opt4 = dict( node_rename = {'a_connector_pad_Q4': 'cpw5', 'b_connector_pad_Q4': 'cpw3', 'c_connector_pad_Q4': 'readout4'}, cap_mat = t4_mat, ind_dict = {('pad_top_Q4', 'pad_bot_Q4'): L_JJ4f}, # junction inductance in nH jj_dict = {('pad_top_Q4', 'pad_bot_Q4'): 'j4'}, cj_dict = {('pad_top_Q4', 'pad_bot_Q4'): C_JJ4f} # junction capacitance in fF ) cell_4 = Cell(opt4) # subsystem 1: Transmon-4 transmon4 = Subsystem(name='transmon4', sys_type='TRANSMON', nodes=['j4']) # Resonator Subsystems q_opts = dict( Z0 = 50, # characteristic impedance in Ohm vp = 0.404314 * 3e8 # phase velocity ) # subsystem 3: Q2 readout resonator ro4 = Subsystem(name='readout4', sys_type='TL_RESONATOR', nodes=['readout4'], q_opts=dict(f_res = 7.57, **q_opts)) # subsystem 4: bus3 resonator cpw3 = Subsystem(name='cpw3', sys_type='TL_RESONATOR', nodes=['cpw3'], q_opts=dict(f_res = 8.2, **q_opts)) # subsystem 15: bus5 resonator cpw5 = Subsystem(name='cpw5', sys_type='TL_RESONATOR', nodes=['cpw5'], q_opts=dict(f_res = 8.29, **q_opts)) composite_sys = CompositeSystem( subsystems=[transmon4, ro4, cpw3, cpw5], cells=[cell_4], grd_node='ground_main_plane', nodes_force_keep=['readout4', 'cpw3', 'cpw5'] ) cg = composite_sys.circuitGraph() print(cg) hilbertspace = composite_sys.create_hilbertspace() print(hilbertspace) # Convert the hilbert space into # "Interaction Picture" hilbertspace = composite_sys.add_interaction() hilbertspace.hamiltonian() hamiltonian_results = composite_sys.hamiltonian_results(hilbertspace, evals_count=30) composite_sys.compute_gs()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw 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)
https://github.com/hugoecarl/TSP-Problem-Study
hugoecarl
with open('in-exemplo.txt', 'r') as f: print(f.read()) with open('out-exemplo.txt', 'r') as f: print(f.read()) import time import matplotlib.pyplot as plt import pandas as pd import os import subprocess %matplotlib inline #Roda entradas def roda_com_entrada(executavel, arquivo_in, envs = '1', deb = '0'): with open(arquivo_in) as f: start = time.perf_counter() a = f.read() proc = subprocess.run([executavel], input=a, text=True, capture_output=True, env=dict(OMP_NUM_THREADS=envs, DEBUG=deb, **os.environ)) end = time.perf_counter() f.close() ret = '' for i in a: if i == "\n": break ret += i return (proc.stdout, end - start, int(ret)) v #retorna tamanho do tour apartir do stdout buf = '' for i in out: if i == " ": return float(buf) buf += i #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] tempos_2 = [] resultados1 = [] resultados2 = [] resultados3 = [] #Usando as mesmas entradas for i in range(8): print("Rodando entrada: "+str(i)) a = roda_com_entrada('./busca_local_antigo','busca-exaustiva/in-'+str(i)+'.txt') b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt') c = roda_com_entrada('./heuristico/heuristico','busca-exaustiva/in-'+str(i)+'.txt') tempos.append(a[1]) tempos_1.append(b[1]) tempos_2.append(c[1]) tamanho_entradas.append(a[2]) resultados1.append(tamanho_tour(a[0])) resultados2.append(tamanho_tour(b[0])) resultados3.append(tamanho_tour(c[0])) #Teste com entrada um pouco maior print("Rodando entrada: 8") tempos.append(roda_com_entrada('./busca_local_antigo','maior.txt')[1]) tempos_1.append(roda_com_entrada('./busca-exaustiva/busca-exaustiva','maior.txt')[1]) tempos_2.append(roda_com_entrada('./heuristico/heuristico','maior.txt')[1]) tamanho_entradas.append(roda_com_entrada('./busca-local/busca-local','maior.txt')[2]) resultados1.append(tamanho_tour(roda_com_entrada('./busca_local_antigo','maior.txt')[0])) resultados2.append(tamanho_tour(roda_com_entrada('./busca-exaustiva/busca-exaustiva','maior.txt')[0])) resultados3.append(tamanho_tour(roda_com_entrada('./heuristico/heuristico','maior.txt')[0])) plt.title("Comparacao Desempenho") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos_1) plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_2) plt.legend(["busca-exaustiva", "busca-local","heuristico"]) plt.show() plt.title("Comparacao Desempenho") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_2) plt.legend(["busca-local","heuristico"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-local-tempo"] = pd.Series(tempos) df["busca-exaustiva-tempo"] = pd.Series(tempos_1) df["heuristica-tempo"] = pd.Series(tempos_2) df["busca-local-resultado"] = pd.Series(resultados1) df["busca-exaustiva-resultado"] = pd.Series(resultados2) df["heuristica-resultado"] = pd.Series(resultados3) df df.describe() #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] tempos_2 = [] tempos_3 = [] tempos_4 = [] tempos_5 = [] #Usando as mesmas entradas for i in range(7): print("Rodando entrada: "+str(i)) a = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt') b = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','2') c = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','3') d = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','4') e = roda_com_entrada('./busca_local_antigo','busca-local/in-'+str(i)+'.txt') f = roda_com_entrada('./busca-local/busca-local-gpu','busca-local/in-'+str(i)+'.txt') tempos.append(a[1]) tempos_1.append(b[1]) tempos_2.append(c[1]) tempos_3.append(d[1]) tempos_4.append(e[1]) tempos_5.append(f[1]) tamanho_entradas.append(a[2]) plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_1) plt.plot(tamanho_entradas, tempos_2) plt.plot(tamanho_entradas, tempos_3) plt.legend(["1 thread otimizado", "2 threads otimizado","3 threads otimizado", "4 threads otimizado", "Sem otimizações"]) plt.show() plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos_3) plt.plot(tamanho_entradas, tempos_5) plt.legend(["4 thread otimizado", "GPU"]) plt.show() plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_4) plt.legend(["1 thread otimizado", "Sem otimizações"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-local-1-thread"] = pd.Series(tempos) df["busca-local-2-threads"] = pd.Series(tempos_1) df["busca-local-3-threads"] = pd.Series(tempos_2) df["busca-local-4-threads"] = pd.Series(tempos_3) df["busca-local-gpu"] = pd.Series(tempos_5) df["busca-local-semopt"] = pd.Series(tempos_4) df #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] tempos_2 = [] #Usando as mesmas entradas for i in range(8): print("Rodando entrada: "+str(i)) if i != 7: a = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '1', '1') tempos.append(a[1]) b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '8', '0') c = roda_com_entrada('./busca-exaustiva-apenasbb','busca-exaustiva/in-'+str(i)+'.txt', '1', '0') tempos_1.append(b[1]) tempos_2.append(c[1]) tamanho_entradas.append(a[2]) plt.title("Comparacao Desempenho Busca Exaustiva") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas[:-1], tempos) plt.plot(tamanho_entradas[:-1], tempos_2[:-1]) plt.legend(["Exaustivo Simples", "Exaustivo Branch and Bound"]) plt.show() plt.title("Comparacao Desempenho Busca Exaustiva") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos_1) plt.plot(tamanho_entradas, tempos_2) plt.legend(["Branch and Bound Paralelo", "Branch and Bound Simples"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-exaustiva-simples"] = pd.Series(tempos) df["busca-exaustiva-branchnbound"] = pd.Series(tempos_2) df["busca-exaustiva-branchnbound-par"] = pd.Series(tempos_1) df
https://github.com/sathayen/qiskit-docker
sathayen
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer, IBMQ from qiskit.tools.visualization import plot_histogram , circuit_drawer qr = QuantumRegister(16) cr = ClassicalRegister(16) qc = QuantumCircuit(qr, cr) import bitarray s1 = ";)" s2 = "8)" b1 = bitarray.bitarray() b1.fromstring(s1) b2 = bitarray.bitarray() b2.fromstring(s2) # print the bit sequences print("b1 =", b1) print("b2 =", b2) # qr[0] ----> qr[15] # 0011 1011 0010 1001" # s1 bit sequence # 0011 1000 0010 1001" #s2 bit sequence # Notice the difference between s1 and s2 -- bits 7 (qr[6]) and 8 (qr[7]) are different. # 11 (s1) # 00 (s2) # All other bits are identical # First take care of all other qubits -- APPLY x gates for appropriate qubits # YOUR CODE HERE: # We want both qr[6],qr[7] as 00 or 11 to get either 8 or ; respectively. # Apply a controlled-NOT gate between 6 and 7 , so that when qubit 6 is "1", 7 also becomes 1 # YOUR CODE HERE: # MEASURE: # DRAW Circuit # SET THE API: # EXECUTE ON REMOTE BACKEND: # Results: result.status() stats = result.result().get_counts() plot_histogram(stats)
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram qc = QuantumCircuit(3) c1 = 0 c2 = 1 t=2 qc.x(c1) qc.x(c2) qc.x(t) qc.ccx(c1,c2,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/HayleySummer/Qiskit_Hackathon_Europe
HayleySummer
import numpy from PIL import Image from IPython.display import Image as dispImage #Generate initial image data = numpy.zeros((8, 8, 3), dtype=numpy.uint8) white = [255, 255, 255] grey = [128, 128, 128] black = [0,0,0] boardRows = 8 boardColumns = 8 for i in range(boardRows): for j in range(boardColumns): if (i == 3 and j == 3) or (i == 4 and j == 4): data[i, j] = white elif (i == 3 and j == 4) or (i == 4 and j == 3): data[i, j] = black else: data[i, j] = grey image = Image.fromarray(data) image.show() image = image.save("prueba.jpg") dispImage("prueba.jpg", width=100, height=100) #Path to the file 15x10_w.txt with open('/content/drive/MyDrive/Colab Notebooks/Hackathon/Board_To_Image/Data/Training Set/15x10_w.txt') as f: lines = f.readlines() f.close() auxParams = lines[0].split("\n") params = auxParams[0].split(" ") print(params) #0 5 4 ==> #First 0 == black - 1 == white #Second parameter column index (from 0 to 7) #Third parameter row index (from 0 to 7) #Print first movement #FROM THIS POINTS, THE FIRST PARAMETER "i" IS THE ROW AND THE SECOND "j" THE COLUMN if params[0] == "0": color = black else: color = white i = int(params[2]) j = int(params[1]) data[i,j] = color print(i,j) #Print all movements (WITHOUT FLIPPLIG SPOTS) """ for line in lines: auxParams = line.split("\n") params = auxParams[0].split(" ") if params[0] == "0": color = black else: color = white i = int(params[2]) #rows j = int(params[1]) #colummns data[i,j] = color print(data) """ #Save image with movement image = Image.fromarray(data) image.show() image = image.save("prueba.jpg") dispImage("prueba.jpg", width=100, height=100)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np # Import Qiskit from qiskit import QuantumCircuit, transpile from qiskit_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, using the matrix_product_state method tcirc = transpile(circ, simulator) result = simulator.run(tcirc).result() counts = result.get_counts(0) counts 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 the result data data num_qubits = 50 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("Time taken: {} sec".format(result.time_taken)) result.get_counts() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.opflow import I, X, Y, Z print(I, X, Y, Z) print(1.5 * I) print(2.5 * X) print(X + 2.0 * Y) print(X^Y^Z) print(X @ Y @ Z) print((X + Y) @ (Y + Z)) print((X + Y) ^ (Y + Z)) (I, X) 2.0 * X^Y^Z print(1.1 * ((1.2 * X)^(Y + (1.3 * Z)))) from qiskit.opflow import (StateFn, Zero, One, Plus, Minus, H, DictStateFn, VectorStateFn, CircuitStateFn, OperatorStateFn) print(Zero, One) print(Plus, Minus) print(Zero.eval('0')) print(Zero.eval('1')) print(One.eval('1')) print(Plus.eval('0')) print(Minus.eval('1')) One.adjoint() ~One (2.0 + 3.0j) * Zero print(Zero + One) import math v_zero_one = (Zero + One) / math.sqrt(2) print(v_zero_one) print(Plus + Minus) print(~One @ One) (~One @ One).eval() (~v_zero_one @ v_zero_one).eval() (~Minus @ One).eval() print((~One).compose(One)) (~One).eval(One) print(Zero^Plus) print((Zero^Plus).to_circuit_op()) print(600 * ((One^5) + (Zero^5))) print((One^Zero)^3) print(((Plus^Minus)^2).to_matrix_op()) print(((Plus^One)^2).to_circuit_op()) print(((Plus^One)^2).to_matrix_op().sample()) print(StateFn({'0':1})) print(StateFn({'0':1}) == Zero) print(StateFn([0,1,1,0])) from qiskit.circuit.library import RealAmplitudes print(StateFn(RealAmplitudes(2))) from qiskit.opflow import X, Y, Z, I, CX, T, H, S, PrimitiveOp X print(X.eval('0')) X.eval('0').eval('1') print(CX) print(CX.to_matrix().real) # The imaginary part vanishes. CX.eval('01') # 01 is the one in decimal. We get the first column. CX.eval('01').eval('11') # This returns element with (zero-based) index (1, 3) print(X @ One) (X @ One).eval() X.eval(One) print(((~One^2) @ (CX.eval('01'))).eval()) print(((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2) print((((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2) @ (Minus^5)) print(((H^I^I)@(X^I^I)@Zero)) print(~One @ Minus) from qiskit.opflow import ListOp print((~ListOp([One, Zero]) @ ListOp([One, Zero]))) print((~ListOp([One, Zero]) @ ListOp([One, Zero])).reduce()) print(StateFn(Z).adjoint()) StateFn(Z).adjoint() print(StateFn(Z).adjoint().eval(Zero)) print(StateFn(Z).adjoint().eval(One)) print(StateFn(Z).adjoint().eval(Plus)) import numpy as np from qiskit.opflow import I, X, Y, Z, H, CX, Zero, ListOp, PauliExpectation, PauliTrotterEvolution, CircuitSampler, MatrixEvolution, Suzuki from qiskit.circuit import Parameter from qiskit import Aer two_qubit_H2 = (-1.0523732 * I^I) + \ (0.39793742 * I^Z) + \ (-0.3979374 * Z^I) + \ (-0.0112801 * Z^Z) + \ (0.18093119 * X^X) print(two_qubit_H2) evo_time = Parameter('θ') evolution_op = (evo_time*two_qubit_H2).exp_i() print(evolution_op) # Note, EvolvedOps print as exponentiations print(repr(evolution_op)) h2_measurement = StateFn(two_qubit_H2).adjoint() print(h2_measurement) bell = CX @ (I ^ H) @ Zero print(bell) evo_and_meas = h2_measurement @ evolution_op @ bell print(evo_and_meas) trotterized_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=1)).convert(evo_and_meas) # We can also set trotter_mode='suzuki' or leave it empty to default to first order Trotterization. print(trotterized_op) bound = trotterized_op.bind_parameters({evo_time: .5}) bound[1].to_circuit().draw() # Note that XX was the only non-diagonal measurement in our H2 Observable print(PauliExpectation(group_paulis=False).convert(h2_measurement)) print(PauliExpectation().convert(h2_measurement)) diagonalized_meas_op = PauliExpectation().convert(trotterized_op) print(diagonalized_meas_op) evo_time_points = list(range(8)) h2_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: evo_time_points}) h2_trotter_expectations.eval() sampler = CircuitSampler(backend=Aer.get_backend('aer_simulator')) # sampler.quantum_instance.run_config.shots = 1000 sampled_trotter_exp_op = sampler.convert(h2_trotter_expectations) sampled_trotter_energies = sampled_trotter_exp_op.eval() print('Sampled Trotterized energies:\n {}'.format(np.real(sampled_trotter_energies))) print('Before:\n') print(h2_trotter_expectations.reduce()[0][0]) print('\nAfter:\n') print(sampled_trotter_exp_op[0][0]) 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 digit_A = 5.25 digit_B = 7.5 print(digit_A,'+',digit_B,'=',digit_A+digit_B) nint = qt.get_nint([digit_A+digit_B,digit_A,digit_B]) npres = qt.get_npres([digit_A+digit_B,digit_A,digit_B]) n = nint + npres + 1 phase = True binary_A = qt.my_binary_repr(digit_A, n, nint=nint, phase=phase) binary_B = qt.my_binary_repr(digit_B, n, nint=nint, phase=phase) print(binary_A,binary_B) qregA = QuantumRegister(n, 'A') qregB = QuantumRegister(n, 'B') out_reg = ClassicalRegister(n, 'A+B') circ = QuantumCircuit(qregA, qregB, out_reg) A_gate = qt.input_bits_to_qubits(binary_A, circ, reg=qregA, wrap=True) B_gate = qt.input_bits_to_qubits(binary_B, circ, reg=qregB, wrap=True) circ.append(A_gate, qregA); circ.append(B_gate, qregB); add_gate = qt.QFTAddition(circ, qregA, qregB, wrap=True) circ.append(add_gate, [*qregA, *qregB]); circ.measure(qregB, out_reg); circ.draw(output="latex") shots=20 emulator = Aer.get_backend('qasm_simulator') job = execute(circ, emulator, shots=shots ) hist = job.result().get_counts() print('Target:') print(digit_B,'+',digit_A,'=',digit_B+digit_A,'->',qt.my_binary_repr(digit_B+digit_A, n, nint=nint, phase=phase)) print('Result:') for label in hist.keys(): print(digit_B,'+',digit_A,'=',qt.bin_to_dec(label, nint=nint, phase=phase),'->',label,'with probability',float(hist[label])/shots) digit_A = 5.25 digit_B = -7.5 print(digit_A,'+',digit_B,'=',digit_A+digit_B) nint = qt.get_nint([digit_A+digit_B,digit_A,digit_B]) npres = qt.get_npres([digit_A+digit_B,digit_A,digit_B]) n = nint + npres + 1 phase = True binary_A = qt.my_binary_repr(digit_A, n, nint=nint, phase=phase) binary_B = qt.my_binary_repr(digit_B, n, nint=nint, phase=phase) print(binary_A,binary_B) qregA = QuantumRegister(n, 'A') qregB = QuantumRegister(n, 'B') out_reg = ClassicalRegister(n, 'A+B') circ = QuantumCircuit(qregA, qregB, out_reg) A_gate = qt.input_bits_to_qubits(binary_A, circ, reg=qregA, wrap=True) B_gate = qt.input_bits_to_qubits(binary_B, circ, reg=qregB, wrap=True) circ.append(A_gate, qregA); circ.append(B_gate, qregB); add_gate = qt.QFTAddition(circ, qregA, qregB, wrap=True) circ.append(add_gate, [*qregA, *qregB]); circ.measure(qregB, out_reg); circ.draw(output="latex") shots=20 emulator = Aer.get_backend('qasm_simulator') job = execute(circ, emulator, shots=shots ) hist = job.result().get_counts() print('Target:') print(digit_B,'+',digit_A,'=',digit_B+digit_A,'->',qt.my_binary_repr(digit_B+digit_A, n, nint=nint, phase=phase)) print('Result:') for label in hist.keys(): print(digit_B,'+',digit_A,'=',qt.bin_to_dec(label, nint=nint, phase=phase),'->',label,'with probability',float(hist[label])/shots) digit_A = 5.25 digit_B = 7.5 nint = qt.get_nint([digit_A-digit_B,digit_A,digit_B]) npres = qt.get_npres([digit_A-digit_B,digit_A,digit_B]) n = nint + npres + 1 phase = True binary_A = qt.my_binary_repr(digit_A, n, nint=nint, phase=phase) binary_B = qt.my_binary_repr(digit_B, n, nint=nint, phase=phase) print(binary_A,binary_B) qregA = QuantumRegister(n, 'A') qregB = QuantumRegister(n, 'B') out_reg = ClassicalRegister(n, 'A+B') circ = QuantumCircuit(qregA, qregB, out_reg) A_gate = qt.input_bits_to_qubits(binary_A, circ, reg=qregA, wrap=True) B_gate = qt.input_bits_to_qubits(binary_B, circ, reg=qregB, wrap=True) circ.append(A_gate, qregA); circ.append(B_gate, qregB); tc_gate = qt.TwosCompliment(circ, qregB, wrap=True) circ.append(tc_gate, qregB); add_gate = qt.QFTAddition(circ, qregA, qregB, wrap=True) circ.append(add_gate, [*qregA, *qregB]); circ.measure(qregB, out_reg); circ.draw(output="latex") shots=20 emulator = Aer.get_backend('qasm_simulator') job = execute(circ, emulator, shots=shots ) hist = job.result().get_counts() print('Target:') print(digit_B,'-',digit_A,'=',digit_B-digit_A,'->',qt.my_binary_repr(digit_A-digit_B, n, nint=nint, phase=phase)) print('Result:') for label in hist.keys(): print(digit_B,'-',digit_A,'=',qt.bin_to_dec(label, nint=nint, phase=phase),'->',label,'with probability',float(hist[label])/shots) digit_A = -5.5 digit_B = 7.25 nintA = qt.get_nint([digit_A]) npresA = qt.get_npres([digit_A]) nA = nintA + npresA + 1 nintB = qt.get_nint([digit_B,digit_A+digit_B]) npresB = qt.get_npres([digit_B,digit_A+digit_B]) nB = nintB + npresB + 1 phase = True binary_A = qt.my_binary_repr(digit_A, nA, nint=nintA, phase=phase) binary_B = qt.my_binary_repr(digit_B, nB, nint=nintB, phase=phase) print(binary_A,binary_B) qregA = QuantumRegister(nA, 'A') qregB = QuantumRegister(nB, 'B') out_reg = ClassicalRegister(nB, 'A+B') circ = QuantumCircuit(qregA, qregB, out_reg) A_gate = qt.input_bits_to_qubits(binary_A, circ, reg=qregA, wrap=True) B_gate = qt.input_bits_to_qubits(binary_B, circ, reg=qregB, wrap=True) circ.append(A_gate, qregA); circ.append(B_gate, qregB); circ = qt.QFTAddition(circ, qregA, qregB, nint1=nintA, nint2=nintB, phase=phase) circ.measure(qregB, out_reg); shots=20 emulator = Aer.get_backend('qasm_simulator') job = execute(circ, emulator, shots=shots ) hist = job.result().get_counts() print('Target:') print(digit_B,'+',digit_A,'=',digit_B+digit_A,'->',qt.my_binary_repr(digit_A+digit_B, nB, nint=nintB, phase=phase)) print('Result:') for label in hist.keys(): print(digit_B,'+',digit_A,'=',qt.bin_to_dec(label, nint=nintB, phase=phase),'->',label,'with probability',float(hist[label])/shots)
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
alejomonbar
https://arxiv.org/pdf/2010.07335.pdf https://arxiv.org/pdf/2105.10162.pdf https://arxiv.org/pdf/2203.01340.pdf maria https://arxiv.org/pdf/1810.03787.pdf MERA https://arxiv.org/pdf/1905.01426.pdf MERA 2 https://pennylane.ai/qml/demos/tutorial_tn_circuits.html
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] for _ in range(100): depths.append( transpile( ghz, backend, layout_method='trivial' # Fixed layout mapped in circuit order ).depth() ) plt.figure(figsize=(8, 6)) plt.hist(depths, align='left', color='#AC557C') plt.xlabel('Depth', fontsize=14) plt.ylabel('Counts', fontsize=14);
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, execute from qiskit.visualization import plot_error_map from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() plot_error_map(backend)
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from crypto.e91.receiver import Receiver from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from numpy.random import uniform ## The Eveasdropper entity in the E91 implementation ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class Eveasdropper(Receiver): ## Constructor def __init__(self, name='', original_bits_size=0, qr=QuantumRegister(2, name="qr"), cr=ClassicalRegister(4, name="cr")): super().__init__(name, original_bits_size, qr, cr) ## Chosen measurements setter def set_axes(self, axes=None, density=0.0): self._calculate_measurements() if axes == None: self.axes = [] for _ in range(self.original_bits_size): if uniform(0, 1) <= density: if uniform(0, 1) <= 0.5: # in 50% of cases perform the WW measurement self.axes.append(['ea2', 'eb1']) else: # in 50% of cases perform the ZZ measurement self.axes.append(['ea3', 'eb2']) else: self.axes.append(None) else: self.axes = axes def _calculate_measurements(self): self.measurements = {} qr = self.qr cr = self.cr # Measurement of the spin projection of Alice's qubit onto the a_2 direction (W basis) self.measurements['ea2'] = QuantumCircuit(qr, cr, name='measureEA2') self.measurements['ea2'].s(qr[0]) self.measurements['ea2'].h(qr[0]) self.measurements['ea2'].t(qr[0]) self.measurements['ea2'].h(qr[0]) self.measurements['ea2'].measure(qr[0], cr[2]) # Measurement of the spin projection of Allice's qubit onto the a_3 direction (standard Z basis) self.measurements['ea3'] = QuantumCircuit(qr, cr, name='measureEA3') self.measurements['ea3'].measure(qr[0], cr[2]) # Measurement of the spin projection of Bob's qubit onto the b_1 direction (W basis) self.measurements['eb1'] = QuantumCircuit(qr, cr, name='measureEB1') self.measurements['eb1'].s(qr[1]) self.measurements['eb1'].h(qr[1]) self.measurements['eb1'].t(qr[1]) self.measurements['eb1'].h(qr[1]) self.measurements['eb1'].measure(qr[1], cr[3]) # Measurement of the spin projection of Bob's qubit onto the b_2 direction (standard Z measurement) self.measurements['eb2'] = QuantumCircuit(qr, cr, name='measureEB2') self.measurements['eb2'].measure(qr[1], cr[3]) # Create the key with the circuit measurement results def create_values(self, result, circuits): for i in range(self.original_bits_size): if self.axes[i] != None: res = list(result.get_counts(circuits[i]).keys())[0] self.values.append([int(res[0]), int(res[1])]) else: self.values.append([None, None])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import transpile, QuantumCircuit import qiskit.quantum_info as qi from qiskit_aer import AerSimulator from qiskit_aer.noise import NoiseModel, amplitude_damping_error from qiskit.tools.visualization import plot_histogram # CNOT matrix operator with qubit-0 as control and qubit-1 as target cx_op = qi.Operator([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]) # iSWAP matrix operator iswap_op = qi.Operator([[1, 0, 0, 0], [0, 0, 1j, 0], [0, 1j, 0, 0], [0, 0, 0, 1]]) # CNOT in terms of iSWAP and single-qubit gates cx_circ = QuantumCircuit(2, name='cx<iSWAP>') # Add gates cx_circ.sdg(1) cx_circ.h(1) cx_circ.sdg(0) cx_circ.unitary(iswap_op, [0, 1], label='iswap') cx_circ.sdg(0) cx_circ.h(0) cx_circ.sdg(0) cx_circ.unitary(iswap_op, [0, 1], label='iswap') cx_circ.s(1) print(cx_circ) # Simulate the unitary for the circuit using Operator: unitary = qi.Operator(cx_circ) print(unitary) f_ave = qi.average_gate_fidelity(cx_op, unitary) print("Average Gate Fidelity: F = {:f}".format(f_ave)) 'unitary' in AerSimulator().configuration().basis_gates # Error parameters param_q0 = 0.05 # damping parameter for qubit-0 param_q1 = 0.1 # damping parameter for qubit-1 # Construct the error qerror_q0 = amplitude_damping_error(param_q0) qerror_q1 = amplitude_damping_error(param_q1) iswap_error = qerror_q1.tensor(qerror_q0) # Build the noise model by adding the error to the "iswap" gate noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(iswap_error, 'iswap') noise_model.add_basis_gates(['unitary']) print(noise_model.basis_gates) # Bell state circuit where iSWAPS should be inserted at barrier locations bell_circ = QuantumCircuit(2, 2, name='bell') bell_circ.h(0) bell_circ.append(cx_circ, [0, 1]) bell_circ.measure([0,1], [0,1]) print(bell_circ) # Create ideal simulator backend and transpile circuit sim_ideal = AerSimulator() tbell_circ = transpile(bell_circ, sim_ideal) ideal_result = sim_ideal.run(tbell_circ).result() ideal_counts = ideal_result.get_counts(0) plot_histogram(ideal_counts, title='Ideal output for iSWAP bell-state preparation') # Create noisy simulator and transpile circuit sim_noise = AerSimulator(noise_model=noise_model) tbell_circ_noise = transpile(bell_circ, sim_noise) # Run on the simulator without noise noise_result = sim_noise.run(tbell_circ_noise).result() noise_counts = noise_result.get_counts(bell_circ) plot_histogram(noise_counts, title='Noisy output for iSWAP bell-state preparation') import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/deveshq/QC-with-qiskit
deveshq
import numpy as np #Importing standard Qiskit libraries from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.providers import * from qiskit.circuit import Parameter import matplotlib.pyplot as plt #Loading IBM Quantum account(s) provider = IBMQ.load_account() q = QuantumRegister(1,'q') #System register e = QuantumRegister(1,'e') #Environment register c = ClassicalRegister(1,'c') def dephasing_M(steps): qc = QuantumCircuit(q,e,c) theta = np.pi/5 qc.h(0) qc.barrier() for i in range(steps): if (i>0): qc.reset(e) qc.ry(theta,1) qc.cz(0,1) qc.measure(e,c) qc.barrier() qc.h(q) qc.measure(q,c) sim = Aer.get_backend('qasm_simulator') job = execute(qc, sim, shots=1024) res = job.result() counts = res.get_counts()['0']/1024 return counts qc = dephasing_M(1) qc.draw('mpl') steps = np.linspace(0,100,21) prob0 = [] for st in steps: prob0.append(dephasing_M(int(st))) fig = plt.figure(figsize=(8,5)) plt.scatter(steps,prob0) plt.plot(steps,prob0) plt.xticks(size=12) plt.yticks(size=12) plt.title('\nDephasing of a qubit', size=14) plt.xlabel(r'Steps $\longrightarrow$', size=13) plt.ylabel(r'Population in Hadamard basis $\longrightarrow$', size=13) plt.show() q = QuantumRegister(1,'q') #System register e = QuantumRegister(3,'e') #Environment register c = ClassicalRegister(1,'c') def dephasingNM(steps): qc = QuantumCircuit(q,e,c) t1 = np.pi/5 t2 = np.pi/4 t3 = np.pi/2 qc.h(0) qc.barrier() for i in range(steps): qc.ry(t1,e[0]) qc.ry(t2,e[1]) qc.ry(t3,e[2]) qc.cz(q[0],e[0]) qc.measure(e[0],c) qc.reset(e[0]) qc.swap(e[0],e[1]) qc.swap(e[1],e[2]) qc.barrier() qc.h(q) qc.measure(q,c) sim = Aer.get_backend('qasm_simulator') job = execute(qc, sim, shots=1024) res = job.result() counts = res.get_counts()['0']/1024 return counts qc = dephasingNM(1) qc.draw('mpl') steps = np.linspace(0,100,21) prob0_NM = [] for st in steps: prob0_NM.append(dephasingNM(int(st))) fig = plt.figure(figsize=(8,5)) plt.scatter(steps,prob0_NM) plt.plot(steps,prob0_NM) plt.xticks(size=12) plt.yticks(size=12) plt.title('\nDephasing of a qubit', size=14) plt.xlabel(r'Steps $\longrightarrow$', size=13) plt.ylabel(r'Population in Hadamard basis $\longrightarrow$', size=13) plt.show() fig = plt.figure(figsize=(8,5)) plt.plot(steps,prob0) plt.plot(steps,prob0_NM) plt.xticks(size=12) plt.yticks(size=12) plt.legend(['Markovian','Non-Markovian']) plt.title('\nDephasing of a qubit', size=14) plt.xlabel(r'Steps $\longrightarrow$', size=13) plt.ylabel(r'Population in Hadamard basis $\longrightarrow$', size=13) plt.show()
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.circuit.library import MCXGate gate = MCXGate(4) from qiskit import QuantumCircuit circuit = QuantumCircuit(5) circuit.append(gate, [0, 1, 4, 2, 3]) circuit.draw('mpl')
https://github.com/jhlee29/quantum-meets-hangul
jhlee29
# from PIL import Image from PIL import Image, ImageOps import os, glob import numpy as np from sklearn import model_selection #cross_validation # General imports import os import gzip import numpy as np import matplotlib.pyplot as plt from pylab import cm import warnings # input classes = ["bul", "pul", "ppul"] # image size of 28 x 28 image_size = 28 # Maximum number of sheets to read max_read = 60 num_classes = len(classes) # load the image X = [] Y = [] T = [] for index, classlabel in enumerate(classes): images_dir = "./triple/" + classlabel files = glob.glob(images_dir + "/*.jpg") for i, file in enumerate(files): # Stop if you read more than max_read to make the number of sheets for each class if i >= max_read: break # open the file, read as data, add to X # Repeatedly add labels with the same index to Y image = Image.open(file) image = ImageOps.invert(image) image = image.convert("L") image = image.resize((image_size, image_size)) data = np.asarray(image) X.append(data) Y.append(index) images_dir = "./triple" files = glob.glob(images_dir + "/*.jpg") for i, file in enumerate(files): # open the file, read as data, add to X # Repeatedly add labels with the same index to Y if i >= 36: break image = Image.open(file) image = ImageOps.invert(image) image = image.convert("L") image = image.resize((image_size, image_size)) data = np.asarray(image) T.append(data) X = np.array(X) Y = np.array(Y) T = np.array(T) print(X.shape,T.shape) X_train, X_test, y_train, y_test = model_selection.train_test_split(X, Y, test_size=0.2, random_state=42) X_train = X_train.reshape(len(X_train), -1).astype(np.float64) X_test = X_test.reshape(len(X_test), -1).astype(np.float64) T = T.reshape(len(T), -1).astype(np.float64) fig = plt.figure() LABELS = [0, 1, 2] num_labels = len(LABELS) for i in range(num_labels): ax = fig.add_subplot(1, num_labels, i+1) img = X[Y==LABELS[i]][0].reshape((28,28)) ax.imshow(img, cmap="Greys") print(Y) print(X_train[0]) warnings.filterwarnings("ignore") # scikit-learn imports from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA from sklearn.svm import SVC from sklearn.metrics import accuracy_score # Qiskit imports from qiskit import Aer, execute from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2 from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate from qiskit_machine_learning.kernels import QuantumKernel # Standardize ss = StandardScaler() X_train = ss.fit_transform(X_train) X_test = ss.transform(X_test) sample_test = ss.transform(T) print(sample_test) # Reduce dimensions N_DIM = 5 pca = PCA(n_components=N_DIM) X_train = pca.fit_transform(X_train) X_test = pca.transform(X_test) sample_test = pca.transform(sample_test) # Normalize mms = MinMaxScaler((-1, 1)) X_train = mms.fit_transform(X_train) X_test = mms.transform(X_test) sample_test = mms.transform(sample_test) # label 0 labels_train_0 = np.where(y_train==0, 1, 0) labels_val_0 = np.where(y_test==0, 1, 0) print(f'Original validation labels: {y_test}') print(f'Validation labels for 0 vs Rest: {labels_val_0}') pauli_map_0 = PauliFeatureMap(feature_dimension=N_DIM, reps=2, paulis = ['X', 'Y', 'ZZ']) pauli_kernel_0 = QuantumKernel(feature_map=pauli_map_0, quantum_instance=Aer.get_backend('statevector_simulator')) pauli_svc_0 = SVC(kernel='precomputed', probability=True) matrix_train_0 = pauli_kernel_0.evaluate(x_vec=X_train) pauli_svc_0.fit(matrix_train_0, labels_train_0) matrix_val_0 = pauli_kernel_0.evaluate(x_vec=sample_test, y_vec=X_train) pauli_score_0 = pauli_svc_0.score(matrix_val_0, labels_val_0) print(f'Accuracy of discriminating between label 0 and others: {pauli_score_0*100}%') matrix_test_0 = pauli_kernel_0.evaluate(x_vec=sample_test, y_vec=X_train) pred_0 = pauli_svc_0.predict_proba(matrix_test_0)[:, 1] print(f'Probability of label 0: {np.round(pred_0, 2)}') # label 1 labels_train_1 = np.where(y_train==1, 1, 0) labels_val_1 = np.where(y_test==1, 1, 0) print(f'Original validation labels: {y_test}') print(f'Validation labels for 0 vs Rest: {labels_val_1}') zz_map_1 = ZZFeatureMap(feature_dimension=N_DIM, reps=2, entanglement='linear', insert_barriers=True) zz_kernel_1 = QuantumKernel(feature_map=zz_map_1, quantum_instance=Aer.get_backend('statevector_simulator')) zzpc_svc_1 = SVC(kernel='precomputed', probability=True) matrix_train_1 = zz_kernel_1.evaluate(x_vec=X_train) zzpc_svc_1.fit(matrix_train_1, labels_train_1) matrix_val_1 = zz_kernel_1.evaluate(x_vec=X_test, y_vec=X_train) zzpc_score_1 = zzpc_svc_1.score(matrix_val_1, labels_val_1) print(f'Accuracy for validation dataset: {zzpc_score_1}') matrix_test_1 = zz_kernel_1.evaluate(x_vec=sample_test, y_vec=X_train) pred_1 = zzpc_svc_1.predict_proba(matrix_test_1)[:, 1] print(pred_1) # label 2 labels_train_2 = np.where(y_train==2, 1, 0) labels_val_2 = np.where(y_test==2, 1, 0) print(f'Original validation labels: {y_test}') print(f'Validation labels for 0 vs Rest: {labels_val_2}') zz_map_2 = ZZFeatureMap(feature_dimension=N_DIM, reps=2, entanglement='linear', insert_barriers=True) zz_kernel_2 = QuantumKernel(feature_map=zz_map_2, quantum_instance=Aer.get_backend('statevector_simulator')) zzpc_svc_2 = SVC(kernel='precomputed', probability=True) matrix_train_2 = zz_kernel_2.evaluate(x_vec=X_train) zzpc_svc_2.fit(matrix_train_2, labels_train_2) matrix_val_2 = zz_kernel_2.evaluate(x_vec=X_test, y_vec=X_train) zzpc_score_2 = zzpc_svc_2.score(matrix_val_2, labels_val_2) print(f'Accuracy for validation dataset: {zzpc_score_2}') matrix_test_2 = zz_kernel_2.evaluate(x_vec=sample_test, y_vec=X_train) pred_2 = zzpc_svc_2.predict_proba(matrix_test_2)[:, 1] print(pred_2) # prediction pred_test = np.where((pred_0 > pred_1) & (pred_0 > pred_2), 0, np.where(pred_1 > pred_2, 1, 2)) print(f'Prediction: {pred_test}')
https://github.com/yonahirakawa/qiskit-iniciantes
yonahirakawa
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qc = QuantumCircuit(1) qc.x(0) qc.draw(output='mpl') qc1 = QuantumCircuit(1) qc1.y(0) qc1.draw(output='mpl') qc2 = QuantumCircuit(1) qc2.z(0) qc2.draw(output='mpl') qc3 = QuantumCircuit(1) qc3.h(0) qc3.draw(output='mpl') from cmath import pi # Para aplicar este operador, precisamos especificar o ângulo para o qubit # Aqui vamos considerar a = 2*pi qc4 = QuantumCircuit(1) qc4.ry(2*pi,0) qc4.draw(output='mpl') qc5 = QuantumCircuit(2) qc5.cx(0,1) qc5.draw(output='mpl')
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2022. # # 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. """Utility functions for handling linear reversible circuits.""" import copy from typing import Callable import numpy as np from qiskit import QuantumCircuit from qiskit.exceptions import QiskitError from qiskit.circuit.exceptions import CircuitError from . import calc_inverse_matrix, check_invertible_binary_matrix def transpose_cx_circ(qc: QuantumCircuit): """Takes a circuit having only CX gates, and calculates its transpose. This is done by recursively replacing CX(i, j) with CX(j, i) in all instructions. Args: qc: a QuantumCircuit containing only CX gates. Returns: QuantumCircuit: the transposed circuit. Raises: CircuitError: if qc has a non-CX gate. """ transposed_circ = QuantumCircuit(qc.qubits, qc.clbits, name=qc.name + "_transpose") for instruction in reversed(qc.data): if instruction.operation.name != "cx": raise CircuitError("The circuit contains non-CX gates.") transposed_circ._append(instruction.replace(qubits=reversed(instruction.qubits))) return transposed_circ def optimize_cx_4_options(function: Callable, mat: np.ndarray, optimize_count: bool = True): """Get the best implementation of a circuit implementing a binary invertible matrix M, by considering all four options: M,M^(-1),M^T,M^(-1)^T. Optimizing either the CX count or the depth. Args: function: the synthesis function. mat: a binary invertible matrix. optimize_count: True if the number of CX gates in optimize, False if the depth is optimized. Returns: QuantumCircuit: an optimized QuantumCircuit, has the best depth or CX count of the four options. Raises: QiskitError: if mat is not an invertible matrix. """ if not check_invertible_binary_matrix(mat): raise QiskitError("The matrix is not invertible.") qc = function(mat) best_qc = qc best_depth = qc.depth() best_count = qc.count_ops()["cx"] for i in range(1, 4): mat_cpy = copy.deepcopy(mat) # i=1 inverse, i=2 transpose, i=3 transpose and inverse if i == 1: mat_cpy = calc_inverse_matrix(mat_cpy) qc = function(mat_cpy) qc = qc.inverse() elif i == 2: mat_cpy = np.transpose(mat_cpy) qc = function(mat_cpy) qc = transpose_cx_circ(qc) elif i == 3: mat_cpy = calc_inverse_matrix(np.transpose(mat_cpy)) qc = function(mat_cpy) qc = transpose_cx_circ(qc) qc = qc.inverse() new_depth = qc.depth() new_count = qc.count_ops()["cx"] # Prioritize count, and if it has the same count, then also consider depth better_count = (optimize_count and best_count > new_count) or ( not optimize_count and best_depth == new_depth and best_count > new_count ) # Prioritize depth, and if it has the same depth, then also consider count better_depth = (not optimize_count and best_depth > new_depth) or ( optimize_count and best_count == new_count and best_depth > new_depth ) if better_count or better_depth: best_count = new_count best_depth = new_depth best_qc = qc return best_qc def check_lnn_connectivity(qc: QuantumCircuit) -> bool: """Check that the synthesized circuit qc fits linear nearest neighbor connectivity. Args: qc: a QuantumCircuit containing only CX and single qubit gates. Returns: bool: True if the circuit has linear nearest neighbor connectivity. Raises: CircuitError: if qc has a non-CX two-qubit gate. """ for instruction in qc.data: if instruction.operation.num_qubits > 1: if instruction.operation.name == "cx": q0 = qc.find_bit(instruction.qubits[0]).index q1 = qc.find_bit(instruction.qubits[1]).index dist = abs(q0 - q1) if dist != 1: return False else: raise CircuitError("The circuit has two-qubits gates different than CX.") return True
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can choose different colors for the real and imaginary parts of the density matrix. 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) state = DensityMatrix(qc) plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
https://github.com/JayRGopal/Quantum-Error-Correction
JayRGopal
from qiskit import * from qiskit.providers.ibmq import least_busy import numpy as np from error_matrix import Minv, diags from circuits import get_bin def fix_to_full_hist(hist, ORACLE_SIZE=5): for i in range(2**(ORACLE_SIZE-1)): b_str = get_bin(i,ORACLE_SIZE-1) # print(b_str) if b_str not in hist: hist[b_str] = 0 return hist def correct_results(res, ORACLE_SIZE=5): fixed_hist = fix_to_full_hist(res.get_counts()) # print(fixed_hist) hist_vert = np.vstack(list(fixed_hist.values())) # print(hist_vert) error_corrected = np.matmul(Minv,hist_vert) corrected_hist = {} for i in range(len(error_corrected)): cur_val = error_corrected[i] cur_bin = get_bin(i,ORACLE_SIZE-1) corrected_hist[cur_bin] = cur_val[0] return fixed_hist, corrected_hist def get_avg(accs): return sum(accs) / len(accs) def get_job_by_tag(TARGET_TAG, ibm_computer = ""): if not account_loaded: load_account() provider = IBMQ.get_provider(hub = 'ibm-q') # print(provider.backends()) small_devices = provider.backends(filters=lambda x: not x.configuration().simulator) device = least_busy(small_devices) if ibm_computer != "": device = provider.get_backend(ibm_computer) jobs = device.jobs(limit=100) print(jobs) for job in jobs: # print(job.tags()) if len(job.tags()) > 0 and job.tags()[0] == TARGET_TAG: return job return None
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import matplotlib.pyplot as plt import qiskit from qiskit.providers.aer.noise.errors.standard_errors import coherent_unitary_error from qiskit.providers.aer.noise import NoiseModel from qiskit.ignis.characterization.hamiltonian import ZZFitter, zz_circuits from qiskit.ignis.characterization.gates import (AmpCalFitter, ampcal_1Q_circuits, AngleCalFitter, anglecal_1Q_circuits, AmpCalCXFitter, ampcal_cx_circuits, AngleCalCXFitter, anglecal_cx_circuits) # ZZ rates are typically ~ 100kHz so we want Ramsey oscillations around 1MHz # 12 numbers ranging from 10 to 1000, logarithmically spaced # extra point at 1500 num_of_gates = np.arange(0,150,5) gate_time = 0.1 # Select the qubits whose ZZ will be measured qubits = [0] spectators = [1] # Generate experiments circs, xdata, osc_freq = zz_circuits(num_of_gates, gate_time, qubits, spectators, nosc=2) # Set the simulator with ZZ zz_unitary = np.eye(4,dtype=complex) zz_unitary[3,3] = np.exp(1j*2*np.pi*0.02*gate_time) error = coherent_unitary_error(zz_unitary) noise_model = NoiseModel() noise_model.add_nonlocal_quantum_error(error, 'id', [0], [0,1]) # Run the simulator backend = qiskit.Aer.get_backend('qasm_simulator') shots = 500 # For demonstration purposes split the execution into two jobs print("Running the first 20 circuits") backend_result1 = qiskit.execute(circs[0:20], backend, shots=shots, noise_model=noise_model).result() print("Running the rest of the circuits") backend_result2 = qiskit.execute(circs[20:], backend, shots=shots, noise_model=noise_model).result() %matplotlib inline # Fit the data to an oscillation plt.figure(figsize=(10, 6)) initial_a = 1 initial_c = 0 initial_f = osc_freq initial_phi = -np.pi/20 # Instantiate the fitter # pass the 2 results in as a list of results fit = ZZFitter([backend_result1, backend_result2], xdata, qubits, spectators, fit_p0=[initial_a, initial_f, initial_phi, initial_c], fit_bounds=([-0.5, 0, -np.pi, -0.5], [1.5, 2*osc_freq, np.pi, 1.5])) fit.plot_ZZ(0, ax=plt.gca()) print("ZZ Rate: %f kHz"%(fit.ZZ_rate()[0]*1e3)) plt.show() qubits = [4,2] circs, xdata = ampcal_1Q_circuits(10, qubits) print(circs[2]) # Set the simulator # Add a rotation error err_unitary = np.zeros([2,2],dtype=complex) angle_err = 0.1 for i in range(2): err_unitary[i,i] = np.cos(angle_err) err_unitary[i,(i+1) % 2] = np.sin(angle_err) err_unitary[0,1] *= -1.0 error = coherent_unitary_error(err_unitary) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, 'u2') # Run the simulator backend = qiskit.Aer.get_backend('qasm_simulator') shots = 500 backend_result1 = qiskit.execute(circs, backend, shots=shots, noise_model=noise_model).result() %matplotlib inline # Fit the data to an oscillation plt.figure(figsize=(10, 6)) initial_theta = 0.02 initial_c = 0.5 initial_phi = 0.1 fit = AmpCalFitter(backend_result1, xdata, qubits, fit_p0=[initial_theta, initial_c], fit_bounds=([-np.pi, -1], [np.pi, 1])) # plot the result for the number 1 indexed qubit. # In this case that refers to Q2 since we passed in as [4, 2]) fit.plot(1, ax=plt.gca()) print("Rotation Error on U2: %f rads"%(fit.angle_err()[0])) plt.show() qubits = [0,1] circs, xdata = anglecal_1Q_circuits(10, qubits, angleerr=0.1) #The U1 gates are added errors to test the procedure print(circs[2]) # Set the simulator # Run the simulator backend = qiskit.Aer.get_backend('qasm_simulator') shots = 1000 backend_result1 = qiskit.execute(circs, backend, shots=shots).result() %matplotlib inline # Fit the data to an oscillation plt.figure(figsize=(10, 6)) initial_theta = 0.02 initial_c = 0.5 initial_phi = 0.01 fit = AngleCalFitter(backend_result1, xdata, qubits, fit_p0=[initial_theta, initial_c], fit_bounds=([-np.pi, -1], [np.pi, 1])) fit.plot(0, ax=plt.gca()) print("Angle error between X and Y: %f rads"%(fit.angle_err()[0])) plt.show() # We can specify more than one CX gate to calibrate in parallel # but these lists must be the same length and not contain # any duplicate elements qubits = [0,2] controls = [1,3] circs, xdata = ampcal_cx_circuits(15, qubits, controls) print(circs[2]) # Set the simulator # Add a rotation error on CX # only if the control is in the excited state err_unitary = np.eye(4,dtype=complex) angle_err = 0.15 for i in range(2): err_unitary[2+i,2+i] = np.cos(angle_err) err_unitary[2+i,2+(i+1) % 2] = -1j*np.sin(angle_err) error = coherent_unitary_error(err_unitary) noise_model = NoiseModel() noise_model.add_nonlocal_quantum_error(error, 'cx', [1,0], [0,1]) # Run the simulator backend = qiskit.Aer.get_backend('qasm_simulator') shots = 1500 backend_result1 = qiskit.execute(circs, backend, shots=shots, noise_model=noise_model).result() %matplotlib inline # Fit the data to an oscillation plt.figure(figsize=(10, 6)) initial_theta = 0.02 initial_c = 0.5 initial_phi = 0.01 fit = AmpCalCXFitter(backend_result1, xdata, qubits, fit_p0=[initial_theta, initial_c], fit_bounds=([-np.pi, -1], [np.pi, 1])) fit.plot(0, ax=plt.gca()) print("Rotation Error on CX: %f rads"%(fit.angle_err()[0])) plt.show() qubits = [0,2] controls = [1,3] circs, xdata = anglecal_cx_circuits(15, qubits, controls, angleerr=0.1) print(circs[2]) # Set the simulator # Run the simulator backend = qiskit.Aer.get_backend('qasm_simulator') shots = 1000 backend_result1 = qiskit.execute(circs, backend, shots=shots).result() %matplotlib inline # Fit the data to an oscillation plt.figure(figsize=(10, 6)) initial_theta = 0.02 initial_c = 0.5 initial_phi = 0.01 fit = AngleCalCXFitter(backend_result1, xdata, qubits, fit_p0=[initial_theta, initial_c], fit_bounds=([-np.pi, -1], [np.pi, 1])) fit.plot(0, ax=plt.gca()) print("Rotation Error on CX: %f rads"%(fit.angle_err()[0])) plt.show()
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 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. """ Integration Tests for Parameterized Qobj execution, testing qasm_simulator, statevector_simulator, and expectation value snapshots. """ import unittest import numpy as np from test.terra import common from qiskit import assemble from test.terra.reference.ref_snapshot_expval import ( snapshot_expval_circuits, snapshot_expval_counts, snapshot_expval_labels, snapshot_expval_pre_meas_values, snapshot_expval_circuit_parameterized, snapshot_expval_final_statevecs) from qiskit.providers.qrack import QasmSimulator class TestParameterizedQobj(common.QiskitAerTestCase): """Parameterized Qobj extension tests""" BACKEND_OPTS = { "seed_simulator": 2113 } @staticmethod def expval_snapshots(data, labels): """Format snapshots as nested dicts""" # Check snapshot entry exists in data output = {} for label in labels: snaps = data.get("snapshots", {}).get("expectation_value", {}).get(label, []) # Convert list into dict inner = {} for snap_dict in snaps: inner[snap_dict['memory']] = snap_dict['value'] output[label] = inner return output @staticmethod def parameterized_qobj(backend, shots=1000, measure=True, snapshot=False): """Return ParameterizedQobj for settings.""" single_shot = shots == 1 pcirc1, param1 = snapshot_expval_circuit_parameterized(single_shot=single_shot, measure=measure, snapshot=snapshot) circuits2to4 = snapshot_expval_circuits(pauli=True, skip_measure=(not measure), single_shot=single_shot) pcirc2, param2 = snapshot_expval_circuit_parameterized(single_shot=single_shot, measure=measure, snapshot=snapshot) circuits = [pcirc1] + circuits2to4 + [pcirc2] params = [param1, [], [], [], param2] qobj = assemble(circuits, backend=backend, shots=shots, parameterizations=params) return qobj #def test_parameterized_qobj_qasm_snapshot_expval(self): # """Test parameterized qobj with Expectation Value snapshot and qasm simulator.""" # shots = 1000 # labels = snapshot_expval_labels() * 3 # counts_targets = snapshot_expval_counts(shots) * 3 # value_targets = snapshot_expval_pre_meas_values() * 3 # # backend = QasmSimulator() # qobj = self.parameterized_qobj(backend=backend, # shots=1000, # measure=True, # snapshot=True) # self.assertIn('parameterizations', qobj.to_dict()['config']) # job = backend.run(qobj, self.BACKEND_OPTS) # result = job.result() # success = getattr(result, 'success', False) # num_circs = len(result.to_dict()['results']) # self.assertTrue(success) # self.compare_counts(result, # range(num_circs), # counts_targets, # delta=0.1 * shots) # # Check snapshots # for j in range(num_circs): # data = result.data(j) # all_snapshots = self.expval_snapshots(data, labels) # for label in labels: # snaps = all_snapshots.get(label, {}) # self.assertTrue(len(snaps), 1) # for memory, value in snaps.items(): # target = value_targets[j].get(label, # {}).get(memory, {}) # self.assertAlmostEqual(value, target, delta=1e-7) #def test_parameterized_qobj_statevector(self): # """Test parameterized qobj with Expectation Value snapshot and qasm simulator.""" # statevec_targets = snapshot_expval_final_statevecs() * 3 # # backend = StatevectorSimulator() # qobj = self.parameterized_qobj(backend=backend, # measure=False, # snapshot=False) # self.assertIn('parameterizations', qobj.to_dict()['config']) # job = backend.run(qobj, self.BACKEND_OPTS) # result = job.result() # success = getattr(result, 'success', False) # num_circs = len(result.to_dict()['results']) # self.assertTrue(success) # # for j in range(num_circs): # statevector = result.get_statevector(j) # np.testing.assert_array_almost_equal(statevector, statevec_targets[j].data, decimal=7) if __name__ == '__main__': unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# External imports from pylab import cm from sklearn import metrics import numpy as np import matplotlib.pyplot as plt # Qiskit imports from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector from qiskit.visualization import circuit_drawer from qiskit.algorithms.optimizers import SPSA from qiskit.circuit.library import ZZFeatureMap from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel from qiskit_machine_learning.kernels.algorithms import QuantumKernelTrainer from qiskit_machine_learning.algorithms import QSVC from qiskit_machine_learning.datasets import ad_hoc_data class QKTCallback: """Callback wrapper class.""" def __init__(self) -> None: self._data = [[] for i in range(5)] def callback(self, x0, x1=None, x2=None, x3=None, x4=None): """ Args: x0: number of function evaluations x1: the parameters x2: the function value x3: the stepsize x4: whether the step was accepted """ self._data[0].append(x0) self._data[1].append(x1) self._data[2].append(x2) self._data[3].append(x3) self._data[4].append(x4) def get_callback_data(self): return self._data def clear_callback_data(self): self._data = [[] for i in range(5)] adhoc_dimension = 2 X_train, y_train, X_test, y_test, adhoc_total = ad_hoc_data( training_size=20, test_size=5, n=adhoc_dimension, gap=0.3, plot_data=False, one_hot=False, include_sample_total=True, ) plt.figure(figsize=(5, 5)) plt.ylim(0, 2 * np.pi) plt.xlim(0, 2 * np.pi) plt.imshow( np.asmatrix(adhoc_total).T, interpolation="nearest", origin="lower", cmap="RdBu", extent=[0, 2 * np.pi, 0, 2 * np.pi], ) plt.scatter( X_train[np.where(y_train[:] == 0), 0], X_train[np.where(y_train[:] == 0), 1], marker="s", facecolors="w", edgecolors="b", label="A train", ) plt.scatter( X_train[np.where(y_train[:] == 1), 0], X_train[np.where(y_train[:] == 1), 1], marker="o", facecolors="w", edgecolors="r", label="B train", ) plt.scatter( X_test[np.where(y_test[:] == 0), 0], X_test[np.where(y_test[:] == 0), 1], marker="s", facecolors="b", edgecolors="w", label="A test", ) plt.scatter( X_test[np.where(y_test[:] == 1), 0], X_test[np.where(y_test[:] == 1), 1], marker="o", facecolors="r", edgecolors="w", label="B test", ) plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.title("Ad hoc dataset for classification") plt.show() # Create a rotational layer to train. We will rotate each qubit the same amount. training_params = ParameterVector("θ", 1) fm0 = QuantumCircuit(2) fm0.ry(training_params[0], 0) fm0.ry(training_params[0], 1) # Use ZZFeatureMap to represent input data fm1 = ZZFeatureMap(2) # Create the feature map, composed of our two circuits fm = fm0.compose(fm1) print(circuit_drawer(fm)) print(f"Trainable parameters: {training_params}") # Instantiate quantum kernel quant_kernel = TrainableFidelityQuantumKernel(feature_map=fm, training_parameters=training_params) # Set up the optimizer cb_qkt = QKTCallback() spsa_opt = SPSA(maxiter=10, callback=cb_qkt.callback, learning_rate=0.05, perturbation=0.05) # Instantiate a quantum kernel trainer. qkt = QuantumKernelTrainer( quantum_kernel=quant_kernel, loss="svc_loss", optimizer=spsa_opt, initial_point=[np.pi / 2] ) # Train the kernel using QKT directly qka_results = qkt.fit(X_train, y_train) optimized_kernel = qka_results.quantum_kernel print(qka_results) # Use QSVC for classification qsvc = QSVC(quantum_kernel=optimized_kernel) # Fit the QSVC qsvc.fit(X_train, y_train) # Predict the labels labels_test = qsvc.predict(X_test) # Evalaute the test accuracy accuracy_test = metrics.balanced_accuracy_score(y_true=y_test, y_pred=labels_test) print(f"accuracy test: {accuracy_test}") plot_data = cb_qkt.get_callback_data() # callback data K = optimized_kernel.evaluate(X_train) # kernel matrix evaluated on the training samples plt.rcParams["font.size"] = 20 fig, ax = plt.subplots(1, 2, figsize=(14, 5)) ax[0].plot([i + 1 for i in range(len(plot_data[0]))], np.array(plot_data[2]), c="k", marker="o") ax[0].set_xlabel("Iterations") ax[0].set_ylabel("Loss") ax[1].imshow(K, cmap=cm.get_cmap("bwr", 20)) fig.tight_layout() plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_circuit_layout from qiskit.tools.monitor import job_monitor from qiskit.providers.fake_provider import FakeVigoV2 import matplotlib.pyplot as plt ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) backend = FakeVigoV2() new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
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/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(2) #Applying the CNOT gate qc.h(0) qc.h(1) qc.cx(0,1) qc.h(0) qc.h(1) #Draw the circuit # qc.draw() 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 statevector 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/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(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) ### replaced x gate ### qc.x(1) return qc
https://github.com/PaulaGarciaMolina/QNLP_Qiskit_Hackathon
PaulaGarciaMolina
import numpy as np import pickle from discopy import Ty, Word # Import the classes for the type of word and for the word s, n = Ty('s'), Ty('n') # Define the types s and n nphr, adj, tv, iv, vphr = Ty('NP'), Ty('ADJ'), Ty('TV'), Ty('IV'), Ty('VP') # Define the words (notice that we include both meaning and grammar) # nouns man, woman, kid = Word('man', n), Word('woman', n), Word('kid', n) # adjectives morose, irascible = Word('morose', n @ n.l), Word('irascible', n @ n.l) frightened, cheerful = Word('frightened', n @ n.l), Word('cheerful', n @ n.l) gloomy, furious = Word('gloomy', n @ n.l), Word('furious', n @ n.l) terrified, joyful = Word('terrified', n @ n.l), Word('joyful', n @ n.l) downcast, miserable = Word('downcast', n @ n.l), Word('miserable', n @ n.l) old, young = Word('old', n @ n.l), Word('young', n @ n.l) # Intransitive verbs cries, shouts = Word('cries', n.r @ s), Word('shouts', n.r @ s) laughs, snaps = Word('laughs', n.r @ s), Word('snaps', n.r @ s) # Transitive verbs grieves, startles = Word('grieves', n.r @ s @ n.l), Word('startles', n.r @ s @ n.l) entertains, irritates = Word('entertains', n.r @ s @ n.l), Word('irritates', n.r @ s @ n.l) nouns = [man, woman, kid] adjectives = [morose, irascible, frightened, cheerful, gloomy, furious, terrified, joyful, downcast, miserable, old, young] int_verbs = [cries, shouts, laughs, snaps] t_verbs = [grieves, startles, entertains, irritates] vocab = nouns + int_verbs + t_verbs + adjectives from discopy import Cup, Id, pregroup # Store the grammatical structures in a dictionary grammar_dict = { 'ADJ_N_IV' : Id(n) @ Cup(n.l, n) @ Id(n.r @ s) >> Cup(n, n.r) @ Id(s) >> Id(s), 'N_TV_N': Cup(n, n.r) @ Id(s) @ Cup(n.l, n), 'ADJ_N_TV_N': Id(n) @ Cup(n.l, n) @ Id(n.r @ s) @ Cup(n.l, n) >> Cup(n, n.r) @ Id(s) >> Id(s), 'N_TV_ADJ_N': Cup(n, n.r) @ Id(s) @ Cup(n.l, n) @ Cup(n.l, n) >> Id(s)} # Create parsing (grammatical analysis) dictionary where the grammatical sentences # are the keys and the associated values are the diagrams (words + grammar) data_psr = {} # Intransitive sentences parsing_int = {"{} {} {}.".format(adj, noun, int_verb): adj @ noun @ int_verb >> grammar_dict['ADJ_N_IV'] for adj in adjectives for noun in nouns for int_verb in int_verbs} sentences_int = list(parsing_int.keys()) for sentence in sentences_int: diagram = parsing_int[sentence] data_psr[sentence] = parsing_int[sentence] # Transitive sentences (without adjective) parsing_tra = {"{} {} {}.".format(subj, t_verb, obj): subj @ t_verb @ obj >> grammar_dict['N_TV_N'] for subj in nouns for t_verb in t_verbs for obj in nouns} # Transitive sentences (with adjective) parsing_tra_ladj = {"{} {} {} {}.".format(adj, subj, t_verb, obj): adj @ subj @ t_verb @ obj >> grammar_dict['ADJ_N_TV_N'] for adj in adjectives for subj in nouns for t_verb in t_verbs for obj in nouns} parsing_tra_radj = {"{} {} {} {}.".format(subj, t_verb, adj, obj): subj @ t_verb @ adj @ obj >> grammar_dict['N_TV_ADJ_N'] for subj in nouns for t_verb in t_verbs for adj in adjectives for obj in nouns} parsing_tra.update(parsing_tra_ladj) #merges transitive adjectives into original dict parsing_tra.update(parsing_tra_radj) sentences_tra = list(parsing_tra.keys()) for sentence in sentences_tra: diagram = parsing_tra[sentence] data_psr[sentence] = parsing_tra[sentence] with open('../sentiment_analysis_dataset.txt') as f: data = f.readlines() from sklearn.model_selection import train_test_split labels_dict = {} data_psr_dict = {} sent_type = {} adjective_words = [a.name for a in adjectives] for sentence in data: sentstr = sentence[:-7] if sentence[-6:-3] == 'int': diagram = parsing_int[sentstr] data_psr_dict[sentstr] = diagram labels_dict[sentstr] = sentence[-2] sent_type[sentstr] = 'int' elif sentence[-6:-3] == 'tra': diagram = parsing_tra[sentstr] data_psr_dict[sentstr] = diagram labels_dict[sentstr] = sentence[-2] if len(sentstr.split()) == 4: if sentstr.split()[0] in adjective_words: sent_type[sentstr] = 'tra_' + 'l' else: sent_type[sentstr] = 'tra_' + 'r' else: sent_type[sentstr] = 'tra' # Code of this cell addapted from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources from discopy import Cap, Box data_new_psr_dict = {} for sentstr in data_psr_dict.keys(): num_words = len(sentstr.split(' ')) words = data_psr_dict[sentstr].boxes[:num_words] if sent_type[sentstr] == 'int': noun = Box(words[1].name, n.l, Ty()) words_new = (Cap(n, n.l)) >> (words[0] @ Id(n) @ noun @ words[2]) sentence = words_new >> grammar_dict['ADJ_N_IV'] data_new_psr_dict[sentstr] = sentence.normal_form() elif 'tra' in sent_type[sentstr]: if sent_type[sentstr] == 'tra': noun1 = Box(words[0].name, n.r, Ty()) noun2 = Box(words[2].name, n.l, Ty()) words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (noun1 @ Id(n) @ words[1] @ Id(n) @ noun2) sentence = words_new >> grammar_dict['N_TV_N'] data_new_psr_dict[sentstr] = sentence.normal_form() elif sent_type[sentstr] == 'tra_l': #adjective at beginning noun1 = Box(words[1].name, n.l, Ty()) noun2 = Box(words[3].name, n.l, Ty()) words_new = (Cap(n, n.l) @ Cap(n, n.l)) >> (words[0] @ Id(n) @ noun1 @ words[2] @ Id(n) @ noun2) sentence = words_new >> grammar_dict['ADJ_N_TV_N'] data_new_psr_dict[sentstr] = sentence.normal_form() elif sent_type[sentstr] == 'tra_r': #adjective on second noun noun1 = Box(words[0].name, n.r, Ty()) noun2 = Box(words[3].name, n.l, Ty()) words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (noun1 @ Id(n) @ words[1] @ words[2] @ Id(n) @ noun2) sentence = words_new >> grammar_dict['N_TV_ADJ_N'] data_new_psr_dict[sentstr] = sentence.normal_form() # Code of this cell from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources vocab_psr = [] for word in vocab: if word.cod == Ty('n'): vocab_psr.append(Box(word.name, n.r, Ty())) # n.l case is dealt with in definition of quantum functor else: vocab_psr.append(word) # Code of this cell from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources #***************************************************** # Translation to quantum circuits #***************************************************** from discopy.quantum import Ket, IQPansatz, Bra, qubit from discopy.quantum.circuit import Functor, Id from discopy.quantum.circuit import Circuit from functools import reduce, partial from discopy.quantum.gates import Rx, Rz q_s = 1 # number of qubits for type s (sentence) q_n = 1 # number of qubits for type n (noun) depth = 1 # depth of the IQPansatz p_n = 3 # number of parameters for the single qubit iqp ansatz # Define the dimensions of the objects of the circuit functor ob = {s: q_s, n: q_n} ob_cqmap = {s: qubit ** q_s, n: qubit ** q_n} #----------------------------------------- # parametrised part of ansaetze #----------------------------------------- def single_qubit_iqp_ansatz(params): if len(params) == 1: return Rx(params[0]) if len(params) == 2: return Rx(params[0]) >> Rz(params[1]) if len(params) == 3: return IQPansatz(1, params) def ansatz_state(state, params): arity = sum(ob[Ty(factor.name)] for factor in state.cod) if arity == 1: return Ket(0) >> single_qubit_iqp_ansatz(params) return Ket(*tuple([0 for i in range(arity)])) >> IQPansatz(arity, params) def ansatz_effect(effect, params): arity = sum(ob[Ty(factor.name)] for factor in effect.dom) if arity == 1: return single_qubit_iqp_ansatz(params) >> Bra(0) return IQPansatz(arity, params) >> Bra(*tuple([0 for i in range(arity)])) def ansatz(box,params): dom_type = box.dom cod_type = box.cod if len(dom_type) == 0 and len(cod_type) != 0: return ansatz_state(box, params) if len(dom_type) != 0 and len(cod_type) == 0: return ansatz_effect(box, params) #---------------------------------------------------------- # Define parametrised functor to quantum circuits #----------------------------------------------------------def F(params): def F(params): ar = dict() for i in range(len(vocab_psr)): pgbox = vocab_psr[i] qbox = ansatz(vocab_psr[i], params[i]) ar.update({pgbox: qbox}) if pgbox.cod == Ty(): ar.update({Box(pgbox.name, n.l, Ty()): qbox}) # send the effect with n.l to same quantum effect return Functor(ob_cqmap, ar) # Code of this cell from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources #***************************************************** # Functions to deal with the parametrisation #***************************************************** def paramshapes(vocab_psr): parshapes = [] for box in vocab_psr: dom_type = box.dom cod_type = box.cod dom_arity = sum(ob[Ty(factor.name)] for factor in box.dom) cod_arity = sum(ob[Ty(factor.name)] for factor in box.cod) if dom_arity == 0 or cod_arity == 0: # states and effects arity = max(dom_arity, cod_arity) assert arity != 0 parshapes.append((depth, arity-1)) return parshapes def paramshapes(vocab_psr): parshapes = [] for box in vocab_psr: dom_type = box.dom cod_type = box.cod dom_arity = sum(ob[Ty(factor.name)] for factor in box.dom) cod_arity = sum(ob[Ty(factor.name)] for factor in box.cod) if dom_arity == 0 or cod_arity == 0: # states and effects arity = max(dom_arity, cod_arity) assert arity != 0 if arity == 1: parshapes.append((p_n,)) if arity != 1: parshapes.append((depth, arity-1)) return parshapes def randparams(par_shapes): params = np.array([]) for i in range(len(par_shapes)): params = np.concatenate((params, np.ravel(np.random.rand(*par_shapes[i])))) # np.ravel flattens an array return params def reshape_params(unshaped_pars, par_shapes): pars_reshaped = [[] for ii in range(len(par_shapes))] shift = 0 for ss, s in enumerate(par_shapes): idx0 = 0 + shift if len(s) == 1: idx1 = s[0] + shift elif len(s) == 2: idx1 = s[0] * s[1] + shift pars_reshaped[ss] = np.reshape(unshaped_pars[idx0:idx1], s) if len(s) == 1: shift += s[0] elif len(s) == 2: shift += s[0] * s[1] return pars_reshaped # Code of this cell from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources #**************************************** # Parameters of the current model #**************************************** par_shapes = paramshapes(vocab_psr) rand_unshaped_pars = randparams(par_shapes) rand_shaped_pars = reshape_params(rand_unshaped_pars, par_shapes) print('Number of parameters: ', len(rand_unshaped_pars)) from sklearn.model_selection import train_test_split psr_diagrams = [] psr_diagrams_dict = {} psr_labels = [] sentences = [] for sentstr in data_new_psr_dict.keys(): sentences.append(sentstr) diagram = data_new_psr_dict[sentstr] psr_diagrams.append(diagram) psr_diagrams_dict[sentstr] = diagram if labels_dict[sentstr] == '0': label = np.array([1,0,0,0]) elif labels_dict[sentstr] == '1': label = np.array([0,1,0,0]) elif labels_dict[sentstr] == '2': label = np.array([0,0,1,0]) elif labels_dict[sentstr] == '3': label = np.array([0,0,0,1]) psr_labels.append(label) train_data_psr, test_data_psr, train_labels, test_labels = \ train_test_split(psr_diagrams, psr_labels, test_size=0.25, random_state=42) train_sent, test_sent, train_labels_sent, test_labels_sent = \ train_test_split(sentences, psr_labels, test_size=0.25, random_state=42) from qiskit import BasicAer, Aer, execute, ClassicalRegister from pytket.extensions.qiskit import tk_to_qiskit from qiskit.quantum_info import Statevector import matplotlib.pyplot as plt def process_dataset(dataset): """ Process a QNLP dataset. Args: dataset: txt dataset to be processed. Returns: psr_diagrams: parsing diagrams. psr_labels: labels. sentences: sentences. sent_type: dictionary with the sentence type for each sentence. """ with open(dataset) as f: data = f.readlines() labels_dict = {} # Dictionary with the labels for each sentence data_psr_dict = {} # Dictionary with the parsing for each sentence sent_type = {} # Dictionary with the sentence type for each sentence # Create the previous dictionaries from the given dataset adjective_words = [a.name for a in adjectives] for sentence in data: sentstr = sentence[:-7] if sentence[-6:-3] == 'int': diagram = parsing_int[sentstr] data_psr_dict[sentstr] = diagram labels_dict[sentstr] = sentence[-2] sent_type[sentstr] = 'int' elif sentence[-6:-3] == 'tra': diagram = parsing_tra[sentstr] data_psr_dict[sentstr] = diagram labels_dict[sentstr] = sentence[-2] if len(sentstr.split()) == 4: if sentstr.split()[0] in adjective_words: sent_type[sentstr] = 'tra_' + 'l' else: sent_type[sentstr] = 'tra_' + 'r' else: sent_type[sentstr] = 'tra' # Rearrange the parsing of the diagrams data_new_psr_dict = {} for sentstr in data_psr_dict.keys(): num_words = len(sentstr.split(' ')) words = data_psr_dict[sentstr].boxes[:num_words] if sent_type[sentstr] == 'int': noun = Box(words[1].name, n.l, Ty()) words_new = (Cap(n, n.l)) >> (words[0] @ Id(n) @ noun @ words[2]) # Rearranged words sentence = words_new >> grammar_dict['ADJ_N_IV'] # Apply grammar on rearranged words data_new_psr_dict[sentstr] = sentence.normal_form() # Store sentece with optimum diagram elif 'tra' in sent_type[sentstr]: if sent_type[sentstr] == 'tra': noun1 = Box(words[0].name, n.r, Ty()) noun2 = Box(words[2].name, n.l, Ty()) words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (noun1 @ Id(n) @ words[1] @ Id(n) @ noun2) sentence = words_new >> grammar_dict['N_TV_N'] data_new_psr_dict[sentstr] = sentence.normal_form() elif sent_type[sentstr] == 'tra_l': #adjective at beginning noun1 = Box(words[1].name, n.l, Ty()) noun2 = Box(words[3].name, n.l, Ty()) words_new = (Cap(n, n.l) @ Cap(n, n.l)) >> (words[0] @ Id(n) @ noun1 @ words[2] @ Id(n) @ noun2) sentence = words_new >> grammar_dict['ADJ_N_TV_N'] data_new_psr_dict[sentstr] = sentence.normal_form() elif sent_type[sentstr] == 'tra_r': #adjective on second noun noun1 = Box(words[0].name, n.r, Ty()) noun2 = Box(words[3].name, n.l, Ty()) words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (noun1 @ Id(n) @ words[1] @ words[2] @ Id(n) @ noun2) sentence = words_new >> grammar_dict['N_TV_ADJ_N'] data_new_psr_dict[sentstr] = sentence.normal_form() # Store the diagrams, labels and sentences for the classification psr_diagrams = [] psr_diagrams_dict = {} psr_labels = [] sentences = [] for sentstr in data_new_psr_dict.keys(): sentences.append(sentstr) diagram = data_new_psr_dict[sentstr] psr_diagrams.append(diagram) psr_diagrams_dict[sentstr] = diagram if labels_dict[sentstr] == '0': label = np.array([1,0]) elif labels_dict[sentstr] == '1': label = np.array([0,1]) psr_labels.append(label) return psr_diagrams, psr_labels, sentences, sent_type def get_cost_and_final_params(file): """ Get cost and finals params of a simulation file. Args: file = pickle simulation file. Returns: cost = cost of the training. final_params = final parameters. """ # Load file with the results with open(file, "rb") as fp: data = pickle.load(fp) # Store final params final_params = data[0][0] # Process stored cost cost_data = data[1][:-1] cost_save_plus = [] cost_save_minus = [] for j in range(0,len(cost_data)): if j % 2: cost_save_plus.append(cost_data[j]) else: cost_save_minus.append(cost_data[j]) cost_save_plus = np.asarray(cost_save_plus) cost_save_minus = np.asarray(cost_save_minus) cost = 0.5 * (cost_save_plus+cost_save_minus) return cost[25:], final_params def get_qiskit_results(circ, s_type, retries=10, qasm=False, noise_model=None, basis_gates=None, coupling_map=None, max_shots=8192): """Function to get the Qiskit's results from a DisCoPy circuit. Args: circ = DisCoPy circuit. s_type = sentence type for the sentence associated to the circuit. retries = number of retries before assigning a random result if the postselection leads to zero values (Default is 10). qasm = if True qasm_simulator is used, if not statevector_simulator (Default is False). noise_model = Qiskit's noise model object (Default is None). basis_gates = basis gates of the device (Default is None). coupling_map = coupling_map of the device (Default is None). max_shots = number of shots (Default is 8192). Returns: array: results from the postselection measurement. """ # Select qubits for postselection according to the sentence type if s_type == 'int': n_qubits = 4 post = 2 elif s_type == 'tra': n_qubits = 3 post = 1 elif s_type == 'tra_l': n_qubits = 5 post = 2 else: assert s_type == 'tra_r' n_qubits = 5 post = 1 # From DisCoPy to Qiskit circuit qc = tk_to_qiskit(circ.to_tk()) if qasm == True: #qasm_simulator out_reg = ClassicalRegister(1) qc.add_register(out_reg) qc.measure(post, out_reg[0]) if noise_model is not None: backend = Aer.get_backend('qasm_simulator') # Include noise model results = execute(qc, backend, shots=max_shots, noise_model=noise_model, coupling_map=coupling_map,basis_gates=basis_gates).result().get_counts() else: backend = BasicAer.get_backend('qasm_simulator') results = execute(qc, backend, shots=max_shots).result().get_counts() zeros = '0' * (n_qubits - 1) if '0 ' + zeros not in results and '1 ' + zeros not in results: if retries == 0: return np.random.rand(2) return get_qiskit_results(circ, s_type, retries=retries-1, qasm = qasm, noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates, max_shots=max_shots) return parse_results(results, eff=zeros) else: # statevector_simulator qc.remove_final_measurements() state_dict = Statevector(qc).to_dict() post0, post1 = '0' * n_qubits, '0' * n_qubits post1 = post1[:post] + '1' + post1[post + 1:] return [np.abs(state_dict[post0])**2, np.abs(state_dict[post1])**2] def parse_results(results, eff='0'): """Parse results of qasm_simulator. Args: results: counts from quantum circuit's measurement. eff: digits for splitting the results for post selection. Returns: array: post selected results. """ ks = [k for k in results.keys() if k.split()[1] == eff] post_selected_results = {k.split()[0]:v for (k,v) in results.items() if k in ks} if '0' not in post_selected_results: post_selected_results['0'] = 0 if '1' not in post_selected_results: post_selected_results['1'] = 0 total = post_selected_results['0'] + post_selected_results['1'] assert total > 0, 'total was 0 after postselection - try running with more shots' return [post_selected_results['0']/total, post_selected_results['1']/total] def obtain_train_predictions(final_params,train_data_cla, train_labels_cla, train_sent_cla, sent_type, qasm=False, noise_model=None, basis_gates=None, coupling_map=None, max_shots=8192): """ Obtain train set predictions from the binary training classifiers for 1vs1 classification. Args: final_params = final params for the optimization for each classifier. train_data_cla = list of the training circuits for each classifier. train_labels_cla = list of the training labels for each classifier. train_sent_cla = list of the training sentences for each classifier. sent_type = dictionary sentences to sentence type. qasm = if True qasm_simulator is used, if not statevector_simulator (Default is False). noise_model = Qiskit's noise model object (Default is None). basis_gates = basis gates of the device (Default is None). coupling_map = coupling_map of the device (Default is None). max_shots = number of shots (Default is 8192). Returns: final_pred_test_results = test set predicted labels. """ # Create list for train predictions of each classifier train_results_cla = [] for j in range(len(train_data_cla)): train_pred = [] # Obtain train predicted results func = F(reshape_params(final_params[j], par_shapes)) train_data_psr = train_data_cla[j] train_labels_psr = train_labels_cla[j] train_sent = train_sent_cla[j] final_train_circuits = [func(diag) for diag in train_data_psr] train_results = [get_qiskit_results(final_train_circuits[i], sent_type[train_sent[i]], qasm=qasm, noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates, max_shots=max_shots) for i in range(len(train_sent))] train_results_tweaked = [np.abs(np.array(res) - 1e-9) for res in train_results] pred_train_results = [res.flatten() / np.sum(res) for res in train_results_tweaked] for i, res in enumerate(pred_train_results): res = np.argmax(res) train_pred.append(res) train_results_cla.append(train_pred) return train_results_cla def obtain_test_predictions(final_params, sent_type, test_data_psr, test_sent, qasm=False, noise_model=None, basis_gates=None, coupling_map=None, max_shots=8192): """ Obtain test set predictions from the binary training classifiers for 1vs1 classification. Args: final_params = final params for the optimization for each classifier. train_data_cla = list of the training circuits for each classifier. train_labels_cla = list of the training labels for each classifier. train_sent_cla = list of the training sentences for each classifier. sent_type = dictionary sentences to sentence type. test_data_psr = test data. test_sent = test_sentences. qasm = if True qasm_simulator is used, if not statevector_simulator (Default is False). noise_model = Qiskit's noise model object (Default is None). basis_gates = basis gates of the device (Default is None). coupling_map = coupling_map of the device (Default is None). max_shots = number of shots (Default is 8192). Returns: train_pred_results_cla = train set predicted labels for each classifier. final_pred_test_results = test set predicted labels. """ # Create list for test predictions of each classifier test_pred = [None]*len(test_data_psr) for i in range(len(test_data_psr)): test_pred[i] = np.zeros(4) for j in range(len(train_data_cla)): func = F(reshape_params(final_params[j], par_shapes)) # Obtain test predicted results final_test_circuits = [func(diag) for diag in test_data_psr] test_results = [get_qiskit_results(final_test_circuits[i], sent_type[test_sent[i]], qasm=qasm, noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates, max_shots=max_shots) for i in range(len(test_sent))] test_results_tweaked = [np.abs(np.array(res) - 1e-9) for res in test_results] pred_test_results = [res.flatten() / np.sum(res) for res in test_results_tweaked] # For the test results, add one for the element of the list test_pred # whose index correspond to the resulting label. for i, res in enumerate(pred_test_results): res = np.argmax(res) if j == 0: if res == 0: test_pred[i][0] += 1 elif res == 1: test_pred[i][1] += 1 elif j == 1: if res == 0: test_pred[i][0] += 1 elif res == 1: test_pred[i][2] += 1 elif j == 2: if res == 0: test_pred[i][0] += 1 elif res == 1: test_pred[i][3] += 1 elif j == 3: if res == 0: test_pred[i][1] += 1 elif res == 1: test_pred[i][2] += 1 elif j == 4: if res == 0: test_pred[i][1] += 1 elif res == 1: test_pred[i][3] += 1 elif j == 5: if res == 0: test_pred[i][2] += 1 elif res == 1: test_pred[i][3] += 1 # Obtain the most common label as test result final_pred_test_results = [] for res in test_pred: final_pred_test_results.append(select_label(res)) return final_pred_test_results import random def select_label(res): """ Select label for test result. Args: res = test result for 1vs1 multi-class classification. Returns: int = test data predicted label""" indices = [] max_label = max(res) for i, r in enumerate(res): if r == max_label: indices.append(i) # Choose the result randomly among the most common ones if they # appear an equal number of times. if len(indices) > 1 : return random.choice(indices) else: return indices[0] def print_accuracy(y_true, y_pred): """ Print the final accuracy and the accuracy for each label for set of predicted and true labels. Args: y_true = true labels. y_pred = predicted labels. """ c_matrix = confusion_matrix(y_true, y_pred) labels = np.arange(c_matrix.shape[0]) print('Total accuracy: ', sum(np.diag(c_matrix))/len(y_true)) for label in labels: print(f'Accuracy label {label}: ', c_matrix[label,label]/sum(c_matrix[label,:])) import pickle import matplotlib.pyplot as plt import seaborn as sns import pandas as pd from sklearn.metrics import confusion_matrix # Define the binary classifiers names classifiers = ['happy_vs_sad', 'happy_vs_angry', 'happy_vs_scared', 'sad_vs_angry', 'sad_vs_scared', 'angry_vs_scared'] # Define figure for cost plot fig, ax = plt.subplots(2,3, figsize=(25,10)) # Define figure for test confusion matrices fig3, ax3 = plt.subplots(1,2, figsize=(15,5)) colors = ['deepskyblue','rebeccapurple'] ax = ax.ravel() max_shots = 8192 # Obtain the results for the different simulators for s, simul in enumerate(['statevector', 'qasm']): if simul == 'statevector': qasm = False else: qasm = True # Store the training data final_params_cla = [] train_data_cla = [] train_labels_cla = [] train_sent_cla = [] ax = ax.ravel() for i, cla in enumerate(classifiers): results = f'./1vs1_results/sentiment_analysis_1vs1_train_{cla}_cost_train_niter2000_{simul}.pkl' cost, final_params = get_cost_and_final_params(results) final_params_cla.append(final_params) dataset = f'./1vs1_datasets/train_{cla}.txt' psr_diagrams, psr_labels, sentences, _ = process_dataset(dataset) ax[i].plot(cost, label = f'{simul}_simulator', color = colors[s]) ax[i].set_title(cla) ax[i].set_xlabel('Iterations') ax[i].set_ylabel('Cost') train_data_cla.append(psr_diagrams) train_labels_cla.append(psr_labels) train_sent_cla.append(sentences) ax[0].legend() train_results_cla = obtain_train_predictions(final_params_cla, train_data_cla, train_labels_cla, train_sent_cla, sent_type, qasm=qasm) final_pred_test_results = obtain_test_predictions(final_params_cla, sent_type, test_data_psr, test_sent, qasm=qasm) fig2, ax2 = plt.subplots(2,3, figsize=(25,10)) ax2 = ax2.ravel() fig2.suptitle(f'Confusion matrix training data {simul}_simulator') for k, train_pred in enumerate(train_results_cla): y_true = [np.argmax(train_label) for train_label in train_labels_cla[k]] y_pred = train_pred c_matrix = confusion_matrix(y_true, y_pred) print(f'Accuracy training set {classifiers[k]} ({simul}_simulator)') print_accuracy(y_true, y_pred) labels = [classifiers[k].split('_')[0], classifiers[k].split('_')[2]] df_cm = pd.DataFrame(c_matrix, labels, labels) df_cm.index.name = 'Actual' df_cm.columns.name = 'Predicted' sns.heatmap(df_cm, ax=ax2[k], annot=True, annot_kws={"size": 16},cmap='viridis', xticklabels=True, yticklabels=True) ax2[k].set_title(classifiers[k]) fig3.suptitle(f'Confusion matrix test data') y_true = [np.argmax(test_label) for test_label in test_labels] y_pred = final_pred_test_results c_matrix = confusion_matrix(y_true, y_pred) print(f'Accuracy test set ({simul}_simulator)') print_accuracy(y_true, y_pred) df_cm = pd.DataFrame(c_matrix, ['happy','sad','angry','scared'], ['happy','sad','angry','scared']) df_cm.index.name = 'Actual' df_cm.columns.name = 'Predicted' sns.heatmap(df_cm, ax=ax3[s], annot=True, annot_kws={"size": 16},cmap='viridis', xticklabels=True, yticklabels=True) ax3[s].set_title(f'{simul}_simulator') rep = 100 classifiers = ['happy_vs_sad', 'happy_vs_angry', 'happy_vs_scared', 'sad_vs_angry', 'sad_vs_scared', 'angry_vs_scared'] for s, simul in enumerate(['statevector', 'qasm']): if simul == 'statevector': qasm = False else: qasm = True final_params_cla = [] accuracy = 0 for i, cla in enumerate(classifiers): results = f'./1vs1_results/sentiment_analysis_1vs1_train_{cla}_cost_train_niter2000_{simul}.pkl' cost, final_params = get_cost_and_final_params(results) final_params_cla.append(final_params) for i in range(rep): final_pred_test_results = obtain_test_predictions(final_params_cla, sent_type, test_data_psr, test_sent, qasm=qasm) y_true = [np.argmax(test_label) for test_label in test_labels] y_pred = final_pred_test_results c_matrix = confusion_matrix(y_true, y_pred) accuracy += sum(np.diag(c_matrix))/len(y_true) print(f'Accuracy test set ({simul}_simulator) averaged over {rep} repetitions:', accuracy/rep) # Define the binary classifiers names classifiers = ['happy_vs_sad', 'happy_vs_angry', 'happy_vs_scared', 'sad_vs_angry', 'sad_vs_scared', 'angry_vs_scared'] # Define figure for cost plot fig, ax = plt.subplots(2,3, figsize=(25,10)) # Define figure for test confusion matrices fig3, ax3 = plt.subplots(1,3, figsize=(25,5)) colors = ['deepskyblue','rebeccapurple','yellowgreen'] ax = ax.ravel() noise_model = None coupling_map = None basis_gates= None max_shots = 8192 # Obtain the results for the different simulators for s, simul in enumerate(['statevector', 'qasm', 'qasm_noise']): if simul == 'statevector': niter = 2000 qasm = False elif simul == 'qasm': niter = 2000 qasm = True elif simul == 'qasm_noise': niter = 500 qasm = True with open(f'./noise_model_melbourne.pkl', "rb") as fp: data = pickle.load(fp) noise_model, coupling_map, basis_gates = data[0], data[1], data[2] # Store the training data final_params_cla = [] train_data_cla = [] train_labels_cla = [] train_sent_cla = [] ax = ax.ravel() for i, cla in enumerate(classifiers): results = f'./1vs1_results/sentiment_analysis_1vs1_train_{cla}_cost_entropy_niter{niter}_{simul}.pkl' if simul == 'qasm_noise': with open(results, "rb") as fp: data = pickle.load(fp) cost, final_params = data[1], data[0][0] else: cost, final_params = get_cost_and_final_params(results) final_params_cla.append(final_params) dataset = f'./1vs1_datasets/train_{cla}.txt' psr_diagrams, psr_labels, sentences, _ = process_dataset(dataset) ax[i].plot(cost, label = f'{simul}_simulator', color = colors[s]) ax[i].set_title(cla) ax[i].set_xlabel('Iterations') ax[i].set_ylabel('Cost') train_data_cla.append(psr_diagrams) train_labels_cla.append(psr_labels) train_sent_cla.append(sentences) ax[0].legend() train_results_cla = obtain_train_predictions(final_params_cla, train_data_cla, train_labels_cla, train_sent_cla, sent_type, qasm=qasm, noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates, max_shots=max_shots) final_pred_test_results = obtain_test_predictions(final_params_cla, sent_type, test_data_psr, test_sent, qasm=qasm, noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates, max_shots=max_shots) fig2, ax2 = plt.subplots(2,3, figsize=(25,10)) ax2 = ax2.ravel() fig2.suptitle(f'Confusion matrix training data {simul}_simulator') for k, train_pred in enumerate(train_results_cla): y_true = [np.argmax(train_label) for train_label in train_labels_cla[k]] y_pred = train_pred c_matrix = confusion_matrix(y_true, y_pred) print(f'Accuracy training set {classifiers[k]} ({simul}_simulator)') print_accuracy(y_true, y_pred) labels = [classifiers[k].split('_')[0], classifiers[k].split('_')[2]] df_cm = pd.DataFrame(c_matrix, labels, labels) df_cm.index.name = 'Actual' df_cm.columns.name = 'Predicted' sns.heatmap(df_cm, ax=ax2[k], annot=True, annot_kws={"size": 16},cmap='viridis', xticklabels=True, yticklabels=True) ax2[k].set_title(classifiers[k]) fig3.suptitle(f'Confusion matrix test data') y_true = [np.argmax(test_label) for test_label in test_labels] y_pred = final_pred_test_results c_matrix = confusion_matrix(y_true, y_pred) print(f'Accuracy test set ({simul}_simulator)') print_accuracy(y_true, y_pred) df_cm = pd.DataFrame(c_matrix, ['happy','sad','angry','scared'], ['happy','sad','angry','scared']) df_cm.index.name = 'Actual' df_cm.columns.name = 'Predicted' sns.heatmap(df_cm, ax=ax3[s], annot=True, annot_kws={"size": 16},cmap='viridis', xticklabels=True, yticklabels=True) ax3[s].set_title(f'{simul}_simulator') rep = 100 classifiers = ['happy_vs_sad', 'happy_vs_angry', 'happy_vs_scared', 'sad_vs_angry', 'sad_vs_scared', 'angry_vs_scared'] noise_model = None coupling_map = None basis_gates= None for s, simul in enumerate(['statevector', 'qasm', 'qasm_noise']): if simul == 'statevector': niter = 2000 qasm = False elif simul == 'qasm': niter = 2000 qasm = True elif simul == 'qasm_noise': niter = 500 qasm = True with open(f'./noise_model_melbourne.pkl', "rb") as fp: data = pickle.load(fp) noise_model, coupling_map, basis_gates = data[0], data[1], data[2] final_params_cla = [] accuracy = 0 for i, cla in enumerate(classifiers): results = f'./1vs1_results/sentiment_analysis_1vs1_train_{cla}_cost_entropy_niter{niter}_{simul}.pkl' if simul == 'qasm_noise': with open(results, "rb") as fp: data = pickle.load(fp) cost, final_params = data[1], data[0][0] else: cost, final_params = get_cost_and_final_params(results) final_params_cla.append(final_params) for i in range(rep): final_pred_test_results = obtain_test_predictions(final_params_cla, sent_type, test_data_psr, test_sent, qasm=qasm, noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates, max_shots=max_shots) y_true = [np.argmax(test_label) for test_label in test_labels] y_true = [np.argmax(test_label) for test_label in test_labels] y_pred = final_pred_test_results c_matrix = confusion_matrix(y_true, y_pred) accuracy += sum(np.diag(c_matrix))/len(y_true) print(f'Accuracy test set ({simul}_simulator) averaged over {rep} repetitions:', accuracy/rep) import qiskit qiskit.__qiskit_version__
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(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) ### replaced x gate ### qc.x(1) return qc
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
# General imports import os import gzip import numpy as np import matplotlib.pyplot as plt from pylab import cm import warnings warnings.filterwarnings("ignore") # scikit-learn imports from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA from sklearn.svm import SVC from sklearn.metrics import accuracy_score # Qiskit imports from qiskit import Aer, execute from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2 from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate from qiskit_machine_learning.kernels import QuantumKernel # Load MNIST dataset DATA_PATH = './resources/ch3_part1.npz' data = np.load(DATA_PATH) sample_train = data['sample_train'] labels_train = data['labels_train'] sample_test = data['sample_test'] # Split train data sample_train, sample_val, labels_train, labels_val = train_test_split( sample_train, labels_train, test_size=0.2, random_state=42) # Visualize samples fig = plt.figure() LABELS = [4, 9] num_labels = len(LABELS) for i in range(num_labels): ax = fig.add_subplot(1, num_labels, i+1) img = sample_train[labels_train==LABELS[i]][0].reshape((28, 28)) ax.imshow(img, cmap="Greys") # Standardize ss = StandardScaler() sample_train = ss.fit_transform(sample_train) sample_val = ss.transform(sample_val) sample_test = ss.transform(sample_test) # Reduce dimensions N_DIM = 5 pca = PCA(n_components=N_DIM) sample_train = pca.fit_transform(sample_train) sample_val = pca.transform(sample_val) sample_test = pca.transform(sample_test) # Normalize mms = MinMaxScaler((-1, 1)) sample_train = mms.fit_transform(sample_train) sample_val = mms.transform(sample_val) sample_test = mms.transform(sample_test) # 3 features, depth 2 map_z = ZFeatureMap(feature_dimension=3, reps=2) map_z.decompose().draw('mpl') # 3 features, depth 1, linear entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear') map_zz.decompose().draw('mpl') # 3 features, depth 1, circular entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular') map_zz.decompose().draw('mpl') # 3 features, depth 1 map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ']) map_pauli.decompose().draw('mpl') twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'], entanglement_blocks='cx', entanglement='circular', insert_barriers=True) twolocal.decompose().draw('mpl') twolocaln = NLocal(num_qubits=3, reps=2, rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))], entanglement_blocks=CXGate(), entanglement='circular', insert_barriers=True) twolocaln.decompose().draw('mpl') print(f'First training data: {sample_train[0]}') encode_map = PauliFeatureMap(feature_dimension=N_DIM, reps=1, paulis = ['X', 'Y', 'ZZ']) encode_circuit = encode_map.bind_parameters(sample_train[0]) encode_circuit.decompose().draw(output='mpl') ############################## # Provide your code here ex3a_fmap = ZZFeatureMap(feature_dimension=5, reps=3, entanglement='circular') ############################## # Check your answer and submit using the following code from qc_grader import grade_ex3a grade_ex3a(ex3a_fmap) pauli_map = PauliFeatureMap(feature_dimension=N_DIM, reps=1, paulis = ['X', 'Y', 'ZZ']) pauli_kernel = QuantumKernel(feature_map=pauli_map, quantum_instance=Aer.get_backend('statevector_simulator')) print(f'First training data : {sample_train[0]}') print(f'Second training data: {sample_train[1]}') pauli_circuit = pauli_kernel.construct_circuit(sample_train[0], sample_train[1]) pauli_circuit.decompose().decompose().draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(pauli_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(pauli_circuit) print(f"Transition amplitude: {counts['0'*N_DIM]/sum(counts.values())}") matrix_train = pauli_kernel.evaluate(x_vec=sample_train) matrix_val = pauli_kernel.evaluate(x_vec=sample_val, y_vec=sample_train) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(matrix_train), interpolation='nearest', origin='upper', cmap='Blues') axs[0].set_title("training kernel matrix") axs[1].imshow(np.asmatrix(matrix_val), interpolation='nearest', origin='upper', cmap='Reds') axs[1].set_title("validation kernel matrix") plt.show() x = [-0.5, -0.4, 0.3, 0, -0.9] y = [0, -0.7, -0.3, 0, -0.4] ############################## # Provide your code here zz = ZZFeatureMap(feature_dimension=N_DIM, reps=3, entanglement='circular') zz_kernel = QuantumKernel(feature_map=zz, quantum_instance=Aer.get_backend('statevector_simulator')) zz_circuit = zz_kernel.construct_circuit(x, y) backend = Aer.get_backend('qasm_simulator') job = execute(zz_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(zz_circuit) ex3b_amp = counts['0'*N_DIM]/sum(counts.values()) ############################## # Check your answer and submit using the following code from qc_grader import grade_ex3b grade_ex3b(ex3b_amp) pauli_svc = SVC(kernel='precomputed') pauli_svc.fit(matrix_train, labels_train) pauli_score = pauli_svc.score(matrix_val, labels_val) print(f'Precomputed kernel classification test score: {pauli_score*100}%') # Load MNIST dataset DATA_PATH = './resources/ch3_part2.npz' data = np.load(DATA_PATH) sample_train = data['sample_train'] labels_train = data['labels_train'] sample_test = data['sample_test'] # Split train data sample_train, sample_val, labels_train, labels_val = train_test_split( sample_train, labels_train, test_size=0.2, random_state=42) # Visualize samples fig = plt.figure() LABELS = [0, 2, 3] num_labels = len(LABELS) for i in range(num_labels): ax = fig.add_subplot(1, num_labels, i+1) img = sample_train[labels_train==LABELS[i]][0].reshape((28, 28)) ax.imshow(img, cmap="Greys") # Standardize standard_scaler = StandardScaler() sample_train = standard_scaler.fit_transform(sample_train) sample_val = standard_scaler.transform(sample_val) sample_test = standard_scaler.transform(sample_test) # Reduce dimensions N_DIM = 5 pca = PCA(n_components=N_DIM) sample_train = pca.fit_transform(sample_train) sample_val = pca.transform(sample_val) sample_test = pca.transform(sample_test) # Normalize min_max_scaler = MinMaxScaler((-1, 1)) sample_train = min_max_scaler.fit_transform(sample_train) sample_val = min_max_scaler.transform(sample_val) sample_test = min_max_scaler.transform(sample_test) labels_train_0 = np.where(labels_train==0, 1, 0) labels_val_0 = np.where(labels_val==0, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 0 vs Rest: {labels_val_0}') labels_train_2 = np.where(labels_train==2, 1, 0) labels_val_2 = np.where(labels_val==2, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 2 vs Rest: {labels_val_2}') labels_train_3 = np.where(labels_train==3, 1, 0) labels_val_3 = np.where(labels_val==3, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 2 vs Rest: {labels_val_3}') pauli_map_0 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement = 'linear') pauli_kernel_0 = QuantumKernel(feature_map=pauli_map_0, quantum_instance=Aer.get_backend('statevector_simulator')) pauli_svc_0 = SVC(kernel='precomputed', probability=True) matrix_train_0 = pauli_kernel_0.evaluate(x_vec=sample_train) pauli_svc_0.fit(matrix_train_0, labels_train_0) matrix_val_0 = pauli_kernel_0.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_0 = pauli_svc_0.score(matrix_val_0, labels_val_0) print(f'Accuracy of discriminating between label 0 and others: {pauli_score_0*100}%') pauli_map_2 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement='linear') pauli_kernel_2 = QuantumKernel(feature_map=pauli_map_2, quantum_instance=Aer.get_backend('statevector_simulator')) pauli_svc_2 = SVC(kernel='precomputed', probability=True) matrix_train_2 = pauli_kernel_2.evaluate(x_vec=sample_train) pauli_svc_2.fit(matrix_train_2, labels_train_2) matrix_val_2 = pauli_kernel_2.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_2 = pauli_svc_2.score(matrix_val_2, labels_val_2) print(f'Accuracy of discriminating between label 2 and others: {pauli_score_2*100}%') pauli_map_3 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement = 'linear') pauli_kernel_3 = QuantumKernel(feature_map=pauli_map_3, quantum_instance=Aer.get_backend('statevector_simulator')) pauli_svc_3 = SVC(kernel='precomputed', probability=True) matrix_train_3 = pauli_kernel_3.evaluate(x_vec=sample_train) pauli_svc_3.fit(matrix_train_3, labels_train_3) matrix_val_3 = pauli_kernel_3.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_3 = pauli_svc_3.score(matrix_val_3, labels_val_3) print(f'Accuracy of discriminating between label 3 and others: {pauli_score_3*100}%') matrix_test_0 = pauli_kernel_0.evaluate(x_vec=sample_test, y_vec=sample_train) pred_0 = pauli_svc_0.predict_proba(matrix_test_0)[:, 1] print(f'Probability of label 0: {np.round(pred_0, 2)}') matrix_test_2 = pauli_kernel_2.evaluate(x_vec=sample_test, y_vec=sample_train) pred_2 = pauli_svc_2.predict_proba(matrix_test_2)[:, 1] print(f'Probability of label 2: {np.round(pred_2, 2)}') matrix_test_3 = pauli_kernel_3.evaluate(x_vec=sample_test, y_vec=sample_train) pred_3 = pauli_svc_3.predict_proba(matrix_test_3)[:, 1] print(f'Probability of label 3: {np.round(pred_3, 2)}') ############################## # Provide your code here pred_2 = pauli_svc_2.predict_proba(matrix_test_2)[:, 1] ############################## ############################## # Provide your code here pred_3 = pauli_svc_3.predict_proba(matrix_test_3)[:, 1] ############################## sample_pred = np.load('./resources/ch3_part2_sub.npy') print(f'Sample prediction: {sample_pred}') pred_2_ex = np.array([0.7]) pred_3_ex = np.array([0.2]) pred_test_ex = np.where((pred_2_ex > pred_3_ex), 2, 3) print(f'Prediction: {pred_test_ex}') pred_2_ex = np.array([0.7, 0.1]) pred_3_ex = np.array([0.2, 0.6]) pred_test_ex = np.where((pred_2_ex > pred_3_ex), 2, 3) print(f'Prediction: {pred_test_ex}') ############################## # Provide your code here prob_0 = np.array(np.round(pred_0,2)) prob_2 = np.array(np.round(pred_2,2)) prob_3 = np.array(np.round(pred_3,2)) def pred(pred_0, pred_2, pred_3): prediction=[] for i in range(len(pred_0)): if pred_0[i]>pred_2[i] and pred_0[i]>pred_3[i]: prediction.append(0) elif pred_2[i]>pred_0[i] and pred_2[i]>pred_3[i]: prediction.append(2) else: prediction.append(3) return np.array(prediction) test = pred(prob_0, prob_2, prob_3) pred_test = np.array(test) print(pred_test) ############################## print(f'Sample prediction: {sample_pred}') # Check your answer and submit using the following code from qc_grader import grade_ex3c grade_ex3c(pred_test, sample_train, standard_scaler, pca, min_max_scaler, pauli_kernel_0, pauli_kernel_2, pauli_kernel_3, pauli_svc_0, pauli_svc_2, pauli_svc_3)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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. # pylint: disable=missing-docstring import unittest import os from unittest.mock import patch from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.test import QiskitTestCase from qiskit.utils import optionals from qiskit import visualization from qiskit.visualization.circuit import text from qiskit.visualization.exceptions import VisualizationError if optionals.HAS_MATPLOTLIB: from matplotlib import figure if optionals.HAS_PIL: from PIL import Image _latex_drawer_condition = unittest.skipUnless( all( ( optionals.HAS_PYLATEX, optionals.HAS_PIL, optionals.HAS_PDFLATEX, optionals.HAS_PDFTOCAIRO, ) ), "Skipped because not all of PIL, pylatex, pdflatex and pdftocairo are available", ) class TestCircuitDrawer(QiskitTestCase): def test_default_output(self): with patch("qiskit.user_config.get_config", return_value={}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, text.TextDrawing) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available") def test_user_config_default_output(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "mpl"}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, figure.Figure) def test_default_output_with_user_config_not_set(self): with patch("qiskit.user_config.get_config", return_value={"other_option": True}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, text.TextDrawing) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available") def test_kwarg_priority_over_user_config_default_output(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit, output="mpl") self.assertIsInstance(out, figure.Figure) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available") def test_default_backend_auto_output_with_mpl(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "auto"}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, figure.Figure) def test_default_backend_auto_output_without_mpl(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "auto"}): with optionals.HAS_MATPLOTLIB.disable_locally(): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, text.TextDrawing) @_latex_drawer_condition def test_latex_unsupported_image_format_error_message(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}): circuit = QuantumCircuit() with self.assertRaises(VisualizationError, msg="Pillow could not write the image file"): visualization.circuit_drawer(circuit, filename="file.spooky") @_latex_drawer_condition def test_latex_output_file_correct_format(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}): circuit = QuantumCircuit() filename = "file.gif" visualization.circuit_drawer(circuit, filename=filename) with Image.open(filename) as im: if filename.endswith("jpg"): self.assertIn(im.format.lower(), "jpeg") else: self.assertIn(im.format.lower(), filename.split(".")[-1]) os.remove(filename) def test_wire_order(self): """Test wire_order See: https://github.com/Qiskit/qiskit-terra/pull/9893""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") cr2 = ClassicalRegister(2, "ca") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(3) circuit.x(1) circuit.x(3).c_if(cr, 10) expected = "\n".join( [ " ", " q_2: ────────────", " ┌───┐ ┌───┐ ", " q_3: ┤ H ├─┤ X ├─", " ├───┤ └─╥─┘ ", " q_0: ┤ H ├───╫───", " ├───┤ ║ ", " q_1: ┤ X ├───╫───", " └───┘┌──╨──┐", " c: 4/═════╡ 0xa ╞", " └─────┘", "ca: 2/════════════", " ", ] ) result = visualization.circuit_drawer(circuit, wire_order=[2, 3, 0, 1]) self.assertEqual(result.__str__(), expected) def test_wire_order_cregbundle(self): """Test wire_order with cregbundle=True See: https://github.com/Qiskit/qiskit-terra/pull/9893""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") cr2 = ClassicalRegister(2, "ca") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(3) circuit.x(1) circuit.x(3).c_if(cr, 10) expected = "\n".join( [ " ", " q_2: ────────────", " ┌───┐ ┌───┐ ", " q_3: ┤ H ├─┤ X ├─", " ├───┤ └─╥─┘ ", " q_0: ┤ H ├───╫───", " ├───┤ ║ ", " q_1: ┤ X ├───╫───", " └───┘┌──╨──┐", " c: 4/═════╡ 0xa ╞", " └─────┘", "ca: 2/════════════", " ", ] ) result = visualization.circuit_drawer(circuit, wire_order=[2, 3, 0, 1], cregbundle=True) self.assertEqual(result.__str__(), expected) def test_wire_order_raises(self): """Verify we raise if using wire order incorrectly.""" circuit = QuantumCircuit(3, 3) circuit.x(1) with self.assertRaisesRegex(VisualizationError, "should not have repeated elements"): visualization.circuit_drawer(circuit, wire_order=[2, 1, 0, 3, 1, 5]) with self.assertRaisesRegex(VisualizationError, "cannot be set when the reverse_bits"): visualization.circuit_drawer(circuit, wire_order=[0, 1, 2, 5, 4, 3], reverse_bits=True) with self.assertWarnsRegex(RuntimeWarning, "cregbundle set"): visualization.circuit_drawer(circuit, cregbundle=True, wire_order=[0, 1, 2, 5, 4, 3]) def test_reverse_bits(self): """Test reverse_bits should not raise warnings when no classical qubits: See: https://github.com/Qiskit/qiskit-terra/pull/8689""" circuit = QuantumCircuit(3) circuit.x(1) expected = "\n".join( [ " ", "q_2: ─────", " ┌───┐", "q_1: ┤ X ├", " └───┘", "q_0: ─────", " ", ] ) result = visualization.circuit_drawer(circuit, output="text", reverse_bits=True) self.assertEqual(result.__str__(), expected) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc for LaTeX conversion") def test_no_explict_cregbundle(self): """Test no explicit cregbundle should not raise warnings about being disabled See: https://github.com/Qiskit/qiskit-terra/issues/8690""" inner = QuantumCircuit(1, 1, name="inner") inner.measure(0, 0) circuit = QuantumCircuit(2, 2) circuit.append(inner, [0], [0]) expected = "\n".join( [ " ┌────────┐", "q_0: ┤0 ├", " │ │", "q_1: ┤ inner ├", " │ │", "c_0: ╡0 ╞", " └────────┘", "c_1: ══════════", " ", ] ) result = circuit.draw("text") self.assertEqual(result.__str__(), expected) # Extra tests that no cregbundle (or any other) warning is raised with the default settings # for the other drawers, if they're available to test. circuit.draw("latex_source") if optionals.HAS_MATPLOTLIB and optionals.HAS_PYLATEX: circuit.draw("mpl")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
p = 0.2 import numpy as np from qiskit.circuit import QuantumCircuit class BernoulliA(QuantumCircuit): """A circuit representing the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(theta_p, 0) class BernoulliQ(QuantumCircuit): """A circuit representing the Bernoulli Q operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit self._theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self._theta_p, 0) def power(self, k): # implement the efficient power of Q q_k = QuantumCircuit(1) q_k.ry(2 * k * self._theta_p, 0) return q_k A = BernoulliA(p) Q = BernoulliQ(p) from qiskit.algorithms import EstimationProblem problem = EstimationProblem( state_preparation=A, # A operator grover_operator=Q, # Q operator objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) from qiskit.primitives import Sampler sampler = Sampler() from qiskit.algorithms import AmplitudeEstimation ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy sampler=sampler, ) ae_result = ae.estimate(problem) print(ae_result.estimation) import matplotlib.pyplot as plt # plot estimated values gridpoints = list(ae_result.samples.keys()) probabilities = list(ae_result.samples.values()) plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities)) plt.axvline(p, color="r", ls="--") plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title("Estimated Values", size=15) plt.ylabel("Probability", size=15) plt.xlabel(r"Amplitude $a$", size=15) plt.ylim((0, 1)) plt.grid() plt.show() print("Interpolated MLE estimator:", ae_result.mle) ae_circuit = ae.construct_circuit(problem) ae_circuit.decompose().draw( "mpl", style="iqx" ) # decompose 1 level: exposes the Phase estimation circuit! from qiskit import transpile basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"] transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx") from qiskit.algorithms import IterativeAmplitudeEstimation iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval sampler=sampler, ) iae_result = iae.estimate(problem) print("Estimate:", iae_result.estimation) iae_circuit = iae.construct_circuit(problem, k=3) iae_circuit.draw("mpl", style="iqx") from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation mlae = MaximumLikelihoodAmplitudeEstimation( evaluation_schedule=3, # log2 of the maximal Grover power sampler=sampler, ) mlae_result = mlae.estimate(problem) print("Estimate:", mlae_result.estimation) from qiskit.algorithms import FasterAmplitudeEstimation fae = FasterAmplitudeEstimation( delta=0.01, # target accuracy maxiter=3, # determines the maximal power of the Grover operator sampler=sampler, ) fae_result = fae.estimate(problem) print("Estimate:", fae_result.estimation) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/nickk124/quantumsearch
nickk124
# 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() from qiskit import * from qiskit.providers.ibmq import least_busy # imports import qiskit import math # imports import matplotlib.pyplot as plt import numpy as np %matplotlib inline %config InlineBackend.figure_format = 'svg' # Makes the images look nice # import qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.visualization import plot_histogram, plot_state_city # gates/operators from qiskit.quantum_info.operators import Operator qiskit.__qiskit_version__ # CONVERSION TOOLS def int_to_binary(i, length): # returns binary string of int with some length raw_str = "{0:b}".format(i) return raw_str.zfill(length) def get_binary_basis_vec(d, n): # returns vec e_d from equation 2, string form # d is direction, n is number of dimensions/qubits e_d = ''.zfill(n - 1 - d) + '1' + ''.zfill(d) return e_d def bitwise_xor(a, b): # get bitwise addition/xor of two strings, length preserved y = int(a, 2)^int(b,2) return bin(y)[2:].zfill(len(a)) # VISUALIZATION TOOLS def draw_circuit(self): return self.circuit.draw('mpl') def plot_states_hist(self): # plots by actually measuring the circuit self.circuit.measure_all() backend = Aer.get_backend('qasm_simulator') shots = 1024 # number of times circuit is run, for sampling results = execute(self.circuit, backend=backend, shots=shots).result() answer = results.get_counts() return plot_histogram(answer) def plot_states_3D(self): # plots current states in 3D backend = Aer.get_backend('statevector_simulator') # the device to run on results = execute(self.circuit, backend).result() answer = result.get_statevector(self.circuit) return plot_state_city(answer) # CIRCUIT TOOLS def get_n_qubits_coin(self): # number of qubits needed for the coin/ # number of bits needed to specify direction in n-cube return int(math.ceil(np.log2(self.n))) def initialize_circuit(self): # initializes quantum computer # need to initialize an equal superposition over all states self.n_qubits_coin = get_n_qubits_coin(self) # qubits needed for coin self.n_qubits_total = self.n + self.n_qubits_coin coin_register = QuantumRegister(self.n_qubits_coin, 'coin') cube_register = QuantumRegister(self.n, 'node') circuit = QuantumCircuit(coin_register, cube_register) for qubit in range(self.n_qubits_total): circuit.h(qubit) # perform hadamard on each qubit return circuit # OPERATORS/GATES def get_sC_matrix(self): # gets |s^C><s^C| matrix sC_matrix = np.ones((self.n, self.n)) / n return sC_matrix def get_sC_operator(self): sC_matrix = get_sC_matrix(self) return Operator(sC_matrix) def get_shift_matrix(self): # get matrix form of S operator S = np.zeros((self.dim_U, self.dim_U)) # following equation 2 of the paper for d in range(self.n): # sum over each cartesian direction for x in range(self.N): # loop over each position on hypercube d_str = int_to_binary(d, self.n_qubits_coin) x_str = int_to_binary(x, self.n) e_d_str = get_binary_basis_vec(d, self.n) # print(d_str,x_str,e_d_str) # binary string that shows row: row_str = d_str + bitwise_xor(x_str, e_d_str) # same, for col: col_str = d_str + x_str row_index = int(row_str, 2) col_index = int(col_str, 2) # print(row_index, col_index) S[row_index][col_index] = 1 return S def get_shift_operator(self): # S operator, from the paper # get matrix from of the operator S_matrix = get_shift_matrix(self) return Operator(S_matrix) def get_c_matrices(self): #C matrix grovers = np.full((self.n, self.n), 2/self.n) np.fill_diagonal(grovers, 2/self.n-1) coin_operator = np.kron(grovers, np.eye(self.N)) return grovers, coin_operator def get_coin_matrix(self): C_0, C = get_c_matrices(self) tens1 = -np.eye(self.n)- C_0 tens2 = np.zeros((self.N,self.N)) # |000…00><000…00| term tens2[0][0] = 1 right_term = np.kron(tens1, tens2) return C+right_term def get_perturbed_coin_operator(self): # C' operator, from the paper coin_matrix = get_coin_matrix(self) return Operator(coin_matrix) def get_perturbed_evolution_matrix(self): # U' matrix in the paper Cprime = get_coin_matrix(self) S = get_shift_matrix(self) return np.matmul(Cprime,S) def get_perturbed_evolution_operator(self): # U' operator in the paper S = get_shift_operator(self) Cprime = get_perturbed_coin_operator(self) Uprime = Cprime.compose(S) return Uprime class QRW: # INITIALIZATION HELPERS def __init__(self, num_qubits_cube): self.n = num_qubits_cube # total number of qubits in cube; n-cube will have N = 2^n nodes self.N = int(2**n) self.dim_U = self.n * int(2**n) # no. of rows/cols for U/S/C self.circuit = self.initialize_circuit() # CIRCUIT TOOLS initialize_circuit = initialize_circuit # VISUALIZATION TOOLS draw_circuit = draw_circuit plot_states_hist = plot_states_hist plot_states_3D = plot_states_3D n = 2 qrw = QRW(n) # initialize computer qrw.draw_circuit() #qrw_instance.plot_states_hist() fig, axes = plt.subplots(1,3,figsize=(10,10)) S = get_shift_matrix(qrw) sC = get_sC_matrix(qrw) axes[0].imshow(S) cprime = get_coin_matrix(qrw) axes[1].imshow(np.real(cprime.data)) Uprime = get_perturbed_evolution_operator(qrw) axes[2].imshow(np.real(Uprime.data)) plt.show() from qiskit.extensions import UnitaryGate uprime = get_perturbed_evolution_operator(qrw) uprime = UnitaryGate(uprime,label="U'") cx_circ = QuantumCircuit(3) cx_circ.unitary(uprime, [x for x in range(3)],label="U'") def is_unitary(m): return np.allclose(np.eye(m.shape[0]), m.H * m) uprime = get_perturbed_evolution_matrix(qrw) is_unitary(np.matrix(uprime)) shift = get_shift_matrix(qrw) is_unitary(np.matrix(shift)) n = 10 for d in range(n): print(get_binary_basis_vec(d, n)) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute n_steps = 1 #Number of steps #Defining the shift gate shift_q = QuantumRegister(3) #3 qubit register shift_circ = QuantumCircuit (shift_q, name='shift gate') #shift operator shift_circ.ccx (shift_q[0], shift_q[1], shift_q[2]) #Toffoli shift_circ.cx (shift_q[0], shift_q[1]) #CNOT shift_circ.x ( shift_q[0]) shift_circ.x ( shift_q[1] ) shift_circ.ccx (shift_q[0], shift_q[1], shift_q[2]) shift_circ.x ( shift_q[1] ) shift_circ.cx ( shift_q[0], shift_q[1] ) shift_gate = shift_circ.to_instruction() #Convert the circuit to a gate q = QuantumRegister (3, name='q') #3 qubit register c = ClassicalRegister (3, name='c') #3 bit classical register circ = QuantumCircuit (q,c) #Main circuit for i in range(n_steps): circ.h (q[0]) #Coin step circ.ccx (q[0], q[1], q[2]) #Toffoli circ.cx (q[0], q[1]) #CNOT circ.x ( q[0]) circ.x ( q[1] ) circ.ccx (q[0], q[1], q[2]) circ.x ( q[1] ) circ.cx ( q[0], q[1] ) circ.barrier() circ.measure ([q[0],q[1],q[2]], [c[0],c[1],c[2]]) circ.draw('mpl') from qiskit.visualization import plot_histogram, plot_state_city backend = Aer.get_backend('qasm_simulator') shots = 1024 # number of times circuit is run, for sampling results = execute(circ, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/pedroripper/qiskit_tutoriais
pedroripper
from qiskit import * import numpy as np circuito = QuantumCircuit(2,2) circuito.x(0) circuito.z(0) circuito.h(1) # circuito.measure([0,1],[0,1]) circuito.draw(output = 'mpl') # Podemos encontrar a matriz unitária que representa as operacoes no circuito backend = Aer.get_backend('unitary_simulator') job = execute(circuito, backend) resultado = job.result() unitaria = resultado.get_unitary() print(unitaria)
https://github.com/davidedellagiustina/qasp-solver
davidedellagiustina
'''Initialization algorithms for amplitude-related problems. ''' import math from qiskit import QuantumCircuit def alg_grover(n: int) -> QuantumCircuit: '''Return an instance of the Grover initialization algorithm. #### Arguments n (int): Number of search qubits. #### Return QuantumCircuit: Built circuit. ''' circ = QuantumCircuit(n) circ.name = 'WH' circ.h(circ.qubits) return circ def alg_from_weights(weights: list[float]) -> QuantumCircuit: '''Return an instance of the Rot initialization algorithm defined by Riguzzi and Mykhailova. #### Arguments weights(list[float]): Weight of each bit evaluating to 1. Complementary is computed \ assuming normalization constraint. #### Return QuantumCircuit: Built circuit. ''' n = len(weights) circ = QuantumCircuit(n) circ.name = 'Rot' for (i, weight) in zip(range(n), weights): theta = 2 * math.acos(math.sqrt(1 - weight)) circ.ry(theta, i) return circ
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. """Transpiler testing""" import io from logging import StreamHandler, getLogger import unittest.mock import sys from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import PassManager, TranspilerError from qiskit.transpiler.runningpassmanager import ( DoWhileController, ConditionalController, FlowController, ) from qiskit.test import QiskitTestCase from ._dummy_passes import ( PassA_TP_NR_NP, PassB_TP_RA_PA, PassC_TP_RA_PA, PassD_TP_NR_NP, PassE_AP_NR_NP, PassF_reduce_dag_property, PassI_Bad_AP, PassJ_Bad_NoReturn, PassK_check_fixed_point_property, PassM_AP_NR_NP, ) class SchedulerTestCase(QiskitTestCase): """Asserts for the scheduler.""" def assertScheduler(self, circuit, passmanager, expected): """ Run `transpile(circuit, passmanager)` and check if the passes run as expected. Args: circuit (QuantumCircuit): Circuit to transform via transpilation. passmanager (PassManager): pass manager instance for the transpilation process expected (list): List of things the passes are logging """ logger = "LocalLogger" with self.assertLogs(logger, level="INFO") as cm: out = passmanager.run(circuit) self.assertIsInstance(out, QuantumCircuit) self.assertEqual([record.message for record in cm.records], expected) def assertSchedulerRaises(self, circuit, passmanager, expected, exception_type): """ Run `transpile(circuit, passmanager)` and check if the passes run as expected until exception_type is raised. Args: circuit (QuantumCircuit): Circuit to transform via transpilation passmanager (PassManager): pass manager instance for the transpilation process expected (list): List of things the passes are logging exception_type (Exception): Exception that is expected to be raised. """ logger = "LocalLogger" with self.assertLogs(logger, level="INFO") as cm: self.assertRaises(exception_type, passmanager.run, circuit) self.assertEqual([record.message for record in cm.records], expected) class TestPassManagerInit(SchedulerTestCase): """The pass manager sets things at init time.""" def test_passes(self): """A single chain of passes, with Requests and Preserves, at __init__ time""" circuit = QuantumCircuit(QuantumRegister(1)) passmanager = PassManager( passes=[ PassC_TP_RA_PA(), # Request: PassA / Preserves: PassA PassB_TP_RA_PA(), # Request: PassA / Preserves: PassA PassD_TP_NR_NP(argument1=[1, 2]), # Requires: {}/ Preserves: {} PassB_TP_RA_PA(), ] ) self.assertScheduler( circuit, passmanager, [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassD_TP_NR_NP", "argument [1, 2]", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", ], ) class TestUseCases(SchedulerTestCase): """Combine passes in different ways and checks that passes are run in the right order.""" def setUp(self): super().setUp() self.circuit = QuantumCircuit(QuantumRegister(1)) self.passmanager = PassManager() def test_chain(self): """A single chain of passes, with Requires and Preserves.""" self.passmanager.append(PassC_TP_RA_PA()) # Requires: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Requires: PassA / Preserves: PassA self.passmanager.append(PassD_TP_NR_NP(argument1=[1, 2])) # Requires: {}/ Preserves: {} self.passmanager.append(PassB_TP_RA_PA()) self.assertScheduler( self.circuit, self.passmanager, [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassD_TP_NR_NP", "argument [1, 2]", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", ], ) def test_conditional_passes_true(self): """A pass set with a conditional parameter. The callable is True.""" self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", ], ) def test_conditional_passes_true_fc(self): """A pass set with a conditional parameter (with FlowController). The callable is True.""" self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( ConditionalController( [PassA_TP_NR_NP()], condition=lambda property_set: property_set["property"] ) ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", ], ) def test_conditional_passes_false(self): """A pass set with a conditional parameter. The callable is False.""" self.passmanager.append(PassE_AP_NR_NP(False)) self.passmanager.append( PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) self.assertScheduler( self.circuit, self.passmanager, ["run analysis pass PassE_AP_NR_NP", "set property as False"], ) def test_conditional_and_loop(self): """Run a conditional first, then a loop.""" self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], condition=lambda property_set: property_set["property"], ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ], ) def test_loop_and_conditional(self): """Run a loop first, then a conditional.""" FlowController.remove_flow_controller("condition") FlowController.add_flow_controller("condition", ConditionalController) self.passmanager.append(PassK_check_fixed_point_property()) self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], condition=lambda property_set: not property_set["property_fixed_point"], ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ], ) def test_do_not_repeat_based_on_preservation(self): """When a pass is still a valid pass (because the following passes preserved it), it should not run again.""" self.passmanager.append([PassB_TP_RA_PA(), PassA_TP_NR_NP(), PassB_TP_RA_PA()]) self.assertScheduler( self.circuit, self.passmanager, ["run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA"], ) def test_do_not_repeat_based_on_idempotence(self): """Repetition can be optimized to a single execution when the pass is idempotent.""" self.passmanager.append(PassA_TP_NR_NP()) self.passmanager.append([PassA_TP_NR_NP(), PassA_TP_NR_NP()]) self.passmanager.append(PassA_TP_NR_NP()) self.assertScheduler( self.circuit, self.passmanager, ["run transformation pass PassA_TP_NR_NP"] ) def test_non_idempotent_pass(self): """Two or more runs of a non-idempotent pass cannot be optimized.""" self.passmanager.append(PassF_reduce_dag_property()) self.passmanager.append([PassF_reduce_dag_property(), PassF_reduce_dag_property()]) self.passmanager.append(PassF_reduce_dag_property()) self.assertScheduler( self.circuit, self.passmanager, [ "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run transformation pass PassF_reduce_dag_property", "dag property = 3", ], ) def test_fenced_dag(self): """Analysis passes are not allowed to modified the DAG.""" qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.cx(qr[0], qr[1]) circ.cx(qr[0], qr[1]) circ.cx(qr[1], qr[0]) circ.cx(qr[1], qr[0]) self.passmanager.append(PassI_Bad_AP()) self.assertSchedulerRaises( circ, self.passmanager, ["run analysis pass PassI_Bad_AP", "cx_runs: {(4, 5, 6, 7)}"], TranspilerError, ) def test_analysis_pass_is_idempotent(self): """Analysis passes are idempotent.""" passmanager = PassManager() passmanager.append(PassE_AP_NR_NP(argument1=1)) passmanager.append(PassE_AP_NR_NP(argument1=1)) self.assertScheduler( self.circuit, passmanager, ["run analysis pass PassE_AP_NR_NP", "set property as 1"] ) def test_ap_before_and_after_a_tp(self): """A default transformation does not preserves anything and analysis passes need to be re-run""" passmanager = PassManager() passmanager.append(PassE_AP_NR_NP(argument1=1)) passmanager.append(PassA_TP_NR_NP()) passmanager.append(PassE_AP_NR_NP(argument1=1)) self.assertScheduler( self.circuit, passmanager, [ "run analysis pass PassE_AP_NR_NP", "set property as 1", "run transformation pass PassA_TP_NR_NP", "run analysis pass PassE_AP_NR_NP", "set property as 1", ], ) def test_pass_no_return(self): """Transformation passes that don't return a DAG raise error.""" self.passmanager.append(PassJ_Bad_NoReturn()) self.assertSchedulerRaises( self.circuit, self.passmanager, ["run transformation pass PassJ_Bad_NoReturn"], TranspilerError, ) def test_fixed_point_pass(self): """A pass set with a do_while parameter that checks for a fixed point.""" self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ], ) def test_fixed_point_fc(self): """A fixed point scheduler with flow control.""" self.passmanager.append( DoWhileController( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], ) ) expected = [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_fixed_point_pass_max_iteration(self): """A pass set with a do_while parameter that checks that the max_iteration is raised.""" self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], max_iteration=2, ) self.assertSchedulerRaises( self.circuit, self.passmanager, [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", ], TranspilerError, ) def test_fresh_initial_state(self): """New construction gives fresh instance.""" self.passmanager.append(PassM_AP_NR_NP(argument1=1)) self.passmanager.append(PassA_TP_NR_NP()) self.passmanager.append(PassM_AP_NR_NP(argument1=1)) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassM_AP_NR_NP", "self.argument1 = 2", "run transformation pass PassA_TP_NR_NP", "run analysis pass PassM_AP_NR_NP", "self.argument1 = 2", ], ) def test_nested_conditional_in_loop(self): """Run a loop with a nested conditional.""" nested_conditional = [ ConditionalController( [PassA_TP_NR_NP()], condition=lambda property_set: property_set["property"] >= 5 ) ] self.passmanager.append( [PassK_check_fixed_point_property()] + nested_conditional + [PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], ) expected = [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ] self.assertScheduler(self.circuit, self.passmanager, expected) class DoXTimesController(FlowController): """A control-flow plugin for running a set of passes an X amount of times.""" def __init__(self, passes, options, do_x_times=0, **_): self.do_x_times = do_x_times() super().__init__(passes, options) def __iter__(self): for _ in range(self.do_x_times): yield from self.passes class TestControlFlowPlugin(SchedulerTestCase): """Testing the control flow plugin system.""" def setUp(self): super().setUp() self.passmanager = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_control_flow_plugin(self): """Adds a control flow plugin with a single parameter and runs it.""" FlowController.add_flow_controller("do_x_times", DoXTimesController) self.passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3) self.assertScheduler( self.circuit, self.passmanager, [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ], ) def test_callable_control_flow_plugin(self): """Removes do_while, then adds it back. Checks max_iteration still working.""" controllers_length = len(FlowController.registered_controllers) FlowController.remove_flow_controller("do_while") self.assertEqual(controllers_length - 1, len(FlowController.registered_controllers)) FlowController.add_flow_controller("do_while", DoWhileController) self.assertEqual(controllers_length, len(FlowController.registered_controllers)) self.passmanager.append( [PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_while=lambda property_set: True, max_iteration=2, ) self.assertSchedulerRaises( self.circuit, self.passmanager, [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ], TranspilerError, ) def test_remove_nonexistent_plugin(self): """Tries to remove a plugin that does not exist.""" self.assertRaises(KeyError, FlowController.remove_flow_controller, "foo") def test_bad_conditional(self): """Flow controller are not allowed to modify the property set.""" def bad_condition(property_set): property_set["property"] = "forbidden write" self.passmanager.append(PassA_TP_NR_NP(), condition=bad_condition) self.assertRaises(TranspilerError, self.passmanager.run, self.circuit) class TestDumpPasses(SchedulerTestCase): """Testing the passes method.""" def test_passes(self): """Dump passes in different FlowControllerLinear""" passmanager = PassManager() passmanager.append(PassC_TP_RA_PA()) passmanager.append(PassB_TP_RA_PA()) expected = [ {"flow_controllers": {}, "passes": [PassC_TP_RA_PA()]}, {"flow_controllers": {}, "passes": [PassB_TP_RA_PA()]}, ] self.assertEqual(expected, passmanager.passes()) def test_passes_in_linear(self): """Dump passes in the same FlowControllerLinear""" passmanager = PassManager( passes=[ PassC_TP_RA_PA(), PassB_TP_RA_PA(), PassD_TP_NR_NP(argument1=[1, 2]), PassB_TP_RA_PA(), ] ) expected = [ { "flow_controllers": {}, "passes": [ PassC_TP_RA_PA(), PassB_TP_RA_PA(), PassD_TP_NR_NP(argument1=[1, 2]), PassB_TP_RA_PA(), ], } ] self.assertEqual(expected, passmanager.passes()) def test_control_flow_plugin(self): """Dump passes in a custom flow controller.""" passmanager = PassManager() FlowController.add_flow_controller("do_x_times", DoXTimesController) passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3) expected = [ {"passes": [PassB_TP_RA_PA(), PassC_TP_RA_PA()], "flow_controllers": {"do_x_times"}} ] self.assertEqual(expected, passmanager.passes()) def test_conditional_and_loop(self): """Dump passes with a conditional and a loop.""" passmanager = PassManager() passmanager.append(PassE_AP_NR_NP(True)) passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], condition=lambda property_set: property_set["property_fixed_point"], ) expected = [ {"passes": [PassE_AP_NR_NP(True)], "flow_controllers": {}}, { "passes": [ PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property(), ], "flow_controllers": {"condition", "do_while"}, }, ] self.assertEqual(expected, passmanager.passes()) class StreamHandlerRaiseException(StreamHandler): """Handler class that will raise an exception on formatting errors.""" def handleError(self, record): raise sys.exc_info() class TestLogPasses(QiskitTestCase): """Testing the log_passes option.""" def setUp(self): super().setUp() logger = getLogger() self.addCleanup(logger.setLevel, logger.level) logger.setLevel("DEBUG") self.output = io.StringIO() logger.addHandler(StreamHandlerRaiseException(self.output)) self.circuit = QuantumCircuit(QuantumRegister(1)) def assertPassLog(self, passmanager, list_of_passes): """Runs the passmanager and checks that the elements in passmanager.property_set['pass_log'] match list_of_passes (the names).""" passmanager.run(self.circuit) self.output.seek(0) # Filter unrelated log lines output_lines = self.output.readlines() pass_log_lines = [x for x in output_lines if x.startswith("Pass:")] for index, pass_name in enumerate(list_of_passes): self.assertTrue(pass_log_lines[index].startswith("Pass: %s -" % pass_name)) def test_passes(self): """Dump passes in different FlowControllerLinear""" passmanager = PassManager() passmanager.append(PassC_TP_RA_PA()) passmanager.append(PassB_TP_RA_PA()) self.assertPassLog(passmanager, ["PassA_TP_NR_NP", "PassC_TP_RA_PA", "PassB_TP_RA_PA"]) def test_passes_in_linear(self): """Dump passes in the same FlowControllerLinear""" passmanager = PassManager( passes=[ PassC_TP_RA_PA(), PassB_TP_RA_PA(), PassD_TP_NR_NP(argument1=[1, 2]), PassB_TP_RA_PA(), ] ) self.assertPassLog( passmanager, [ "PassA_TP_NR_NP", "PassC_TP_RA_PA", "PassB_TP_RA_PA", "PassD_TP_NR_NP", "PassA_TP_NR_NP", "PassB_TP_RA_PA", ], ) def test_control_flow_plugin(self): """Dump passes in a custom flow controller.""" passmanager = PassManager() FlowController.add_flow_controller("do_x_times", DoXTimesController) passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3) self.assertPassLog( passmanager, [ "PassA_TP_NR_NP", "PassB_TP_RA_PA", "PassC_TP_RA_PA", "PassB_TP_RA_PA", "PassC_TP_RA_PA", "PassB_TP_RA_PA", "PassC_TP_RA_PA", ], ) def test_conditional_and_loop(self): """Dump passes with a conditional and a loop""" passmanager = PassManager() passmanager.append(PassE_AP_NR_NP(True)) passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], condition=lambda property_set: property_set["property_fixed_point"], ) self.assertPassLog(passmanager, ["PassE_AP_NR_NP"]) class TestPassManagerReuse(SchedulerTestCase): """The PassManager instance should be reusable.""" def setUp(self): super().setUp() self.passmanager = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_chain_twice(self): """Run a chain twice.""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) self.assertScheduler(self.circuit, self.passmanager, expected) def test_conditional_twice(self): """Run a conditional twice.""" self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) expected = [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", ] self.assertScheduler(self.circuit, self.passmanager, expected) self.assertScheduler(self.circuit, self.passmanager, expected) def test_fixed_point_twice(self): """A fixed point scheduler, twice.""" self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], ) expected = [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ] self.assertScheduler(self.circuit, self.passmanager, expected) self.assertScheduler(self.circuit, self.passmanager, expected) class TestPassManagerChanges(SchedulerTestCase): """Test PassManager manipulation with changes""" def setUp(self): super().setUp() self.passmanager = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_replace0(self): """Test passmanager.replace(0, ...).""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.replace(0, PassB_TP_RA_PA()) expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_replace1(self): """Test passmanager.replace(1, ...).""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.replace(1, PassC_TP_RA_PA()) expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_remove0(self): """Test passmanager.remove(0).""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.remove(0) expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_remove1(self): """Test passmanager.remove(1).""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.remove(1) expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_remove_minus_1(self): """Test passmanager.remove(-1).""" self.passmanager.append(PassA_TP_NR_NP()) self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.remove(-1) expected = ["run transformation pass PassA_TP_NR_NP"] self.assertScheduler(self.circuit, self.passmanager, expected) def test_setitem(self): """Test passmanager[1] = ...""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager[1] = PassC_TP_RA_PA() expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_replace_with_conditional(self): """Replace a pass with a conditional pass.""" self.passmanager.append(PassE_AP_NR_NP(False)) self.passmanager.append(PassB_TP_RA_PA()) self.passmanager.replace( 1, PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) expected = ["run analysis pass PassE_AP_NR_NP", "set property as False"] self.assertScheduler(self.circuit, self.passmanager, expected) def test_replace_error(self): """Replace a non-existing index.""" self.passmanager.append(PassB_TP_RA_PA()) with self.assertRaises(TranspilerError): self.passmanager.replace(99, PassA_TP_NR_NP()) class TestPassManagerSlicing(SchedulerTestCase): """test PassManager slicing.""" def setUp(self): super().setUp() self.passmanager = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_empty_passmanager_length(self): """test len(PassManager) when PassManager is empty""" length = len(self.passmanager) expected_length = 0 self.assertEqual(length, expected_length) def test_passmanager_length(self): """test len(PassManager) when PassManager is not empty""" self.passmanager.append(PassA_TP_NR_NP()) self.passmanager.append(PassA_TP_NR_NP()) length = len(self.passmanager) expected_length = 2 self.assertEqual(length, expected_length) def test_accessing_passmanager_by_index(self): """test accessing PassManager's passes by index""" self.passmanager.append(PassB_TP_RA_PA()) self.passmanager.append(PassC_TP_RA_PA()) new_passmanager = self.passmanager[1] expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_accessing_passmanager_by_index_with_condition(self): """test accessing PassManager's conditioned passes by index""" self.passmanager.append(PassF_reduce_dag_property()) self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], condition=lambda property_set: True, do_while=lambda property_set: not property_set["property_fixed_point"], ) new_passmanager = self.passmanager[1] expected = [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_accessing_passmanager_by_range(self): """test accessing PassManager's passes by range""" self.passmanager.append(PassC_TP_RA_PA()) self.passmanager.append(PassB_TP_RA_PA()) self.passmanager.append(PassC_TP_RA_PA()) self.passmanager.append(PassD_TP_NR_NP()) new_passmanager = self.passmanager[1:3] expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_accessing_passmanager_by_range_with_condition(self): """test accessing PassManager's passes by range with condition""" self.passmanager.append(PassB_TP_RA_PA()) self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) self.passmanager.append(PassB_TP_RA_PA()) new_passmanager = self.passmanager[1:3] expected = [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_accessing_passmanager_error(self): """testing accessing a pass item not in list""" self.passmanager.append(PassB_TP_RA_PA()) with self.assertRaises(IndexError): self.passmanager = self.passmanager[99] class TestPassManagerConcatenation(SchedulerTestCase): """test PassManager concatenation by + operator.""" def setUp(self): super().setUp() self.passmanager1 = PassManager() self.passmanager2 = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_concatenating_passmanagers(self): """test adding two PassManagers together""" self.passmanager1.append(PassB_TP_RA_PA()) self.passmanager2.append(PassC_TP_RA_PA()) new_passmanager = self.passmanager1 + self.passmanager2 expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_concatenating_passmanagers_with_condition(self): """test adding two pass managers with condition""" self.passmanager1.append(PassE_AP_NR_NP(True)) self.passmanager1.append(PassB_TP_RA_PA()) self.passmanager2.append( PassC_TP_RA_PA(), condition=lambda property_set: property_set["property"] ) self.passmanager2.append(PassB_TP_RA_PA()) new_passmanager = self.passmanager1 + self.passmanager2 expected = [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_adding_pass_to_passmanager(self): """test adding a pass to PassManager""" self.passmanager1.append(PassE_AP_NR_NP(argument1=1)) self.passmanager1.append(PassB_TP_RA_PA()) self.passmanager1 += PassC_TP_RA_PA() expected = [ "run analysis pass PassE_AP_NR_NP", "set property as 1", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager1, expected) def test_adding_list_of_passes_to_passmanager(self): """test adding a list of passes to PassManager""" self.passmanager1.append(PassE_AP_NR_NP(argument1=1)) self.passmanager1.append(PassB_TP_RA_PA()) self.passmanager1 += [PassC_TP_RA_PA(), PassB_TP_RA_PA()] expected = [ "run analysis pass PassE_AP_NR_NP", "set property as 1", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager1, expected) def test_adding_list_of_passes_to_passmanager_with_condition(self): """test adding a list of passes to a PassManager that have conditions""" self.passmanager1.append(PassE_AP_NR_NP(False)) self.passmanager1.append( PassB_TP_RA_PA(), condition=lambda property_set: property_set["property"] ) self.passmanager1 += PassC_TP_RA_PA() expected = [ "run analysis pass PassE_AP_NR_NP", "set property as False", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager1, expected) def test_adding_pass_to_passmanager_error(self): """testing adding a non-pass item to PassManager""" with self.assertRaises(TypeError): self.passmanager1 += "not a pass" def test_adding_list_to_passmanager_error(self): """testing adding a list having a non-pass item to PassManager""" with self.assertRaises(TypeError): self.passmanager1 += [PassB_TP_RA_PA(), "not a pass"] if __name__ == "__main__": unittest.main()
https://github.com/sohamch08/Qiskit-Quantum-Algo
sohamch08
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, execute from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # qiskit-ibmq-provider has been deprecated. # Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail. from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options # Loading your IBM Quantum account(s) service = QiskitRuntimeService(channel="ibm_quantum") backend = Aer.get_backend('qasm_simulator') # Invoke a primitive. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html # result = Sampler("ibmq_qasm_simulator").run(circuits).result() from qiskit.providers.fake_provider import FakeGuadalupe, FakeKolkata from qiskit_aer import AerSimulator from qiskit_aer.noise import NoiseModel not_gate=QuantumCircuit(1,1) # Create a quantum circuit with 1 qubit and 1 classical bit not_gate.x(0) not_gate.measure(0,0) not_gate.draw(output='mpl') and_gate=QuantumCircuit(3,1) # Create a quantum circuit with 3 qubits and 1 classical bit and_gate.ccx(0,1,2) and_gate.measure(2,0) and_gate.draw(output='mpl') or_gate=QuantumCircuit(3,1) # Create a quantum circuit with 3 qubits and 1 classical bit or_gate.cx(1,2) or_gate.cx(0,2) or_gate.ccx(0,1,2) or_gate.measure(2,0) or_gate.draw(output='mpl') xor_gate=QuantumCircuit(3,1) # Create a quantum circuit with 3 qubits and 1 classical bit xor_gate.cx(0,2) xor_gate.cx(1,2) xor_gate.measure(2,0) xor_gate.draw(output='mpl') # Write your code here myxor_gate=QuantumCircuit(3) # Create a quantum circuit with 3 qubits and 1 classical bit myxor_gate.cx(0,2) myxor_gate.cx(1,2) sudokucheck = QuantumCircuit(9) sudokucheck = sudokucheck.compose(myxor_gate,[0,1,5]) # Check if v_0 = v_1 sudokucheck = sudokucheck.compose(myxor_gate,[2,3,6]) # Check if v_2 = v_3 sudokucheck = sudokucheck.compose(myxor_gate,[0,2,7]) # Check if v_0 = v_2 sudokucheck = sudokucheck.compose(myxor_gate,[1,3,8]) # Check if v_1 = v_3 sudokucheck.mct([5,6,7,8],4) # Take the AND of all the upper results sudokucheck.draw('mpl') # Write your code here oracle = QuantumCircuit(9) oracle.x(4) oracle.h(4) oracle = oracle.compose(sudokucheck, [0,1,2,3,4,5,6,7,8]) oracle.draw('mpl') # Write your code here uncompute = QuantumCircuit(9) uncompute = uncompute.compose(oracle, [0,1,2,3,4,5,6,7,8]) uncompute = uncompute.compose(myxor_gate,[1,3,8]) uncompute = uncompute.compose(myxor_gate,[0,2,7]) uncompute = uncompute.compose(myxor_gate,[2,3,6]) uncompute = uncompute.compose(myxor_gate,[0,1,5]) uncompute.h(4) uncompute.x(4) uncompute.draw('mpl') # Write a code to construct the diffuser operator for the problem def diffuser_operator(n): diffuse = QuantumCircuit(n) controlbit = [] # This will help to list all the control bits for for i in range(n): diffuse.h(i) # First layer of hadamard gates diffuse.x(i) # Layer of X gates if i>0: controlbit.append(i) diffuse.h(0) diffuse.mcx(control_qubits=controlbit, target_qubit=[0]) # applied C^nX diffuse.h(0) for i in range(n): diffuse.x(i) # The second last layer of X gates diffuse.h(i) # The last layer of hadamard gates return diffuse n = 4 diffuser_circuit = diffuser_operator(4) diffuser_circuit.draw('mpl') # Write your code here to put all the pieces together as a single circuit # pi/4 x sqrt{2^4}=pi/4 which is approximately 3. So we will apply the operator = uncompute + diffuser_operator 3 times grover_search = QuantumCircuit(9,4) for i in range(4): grover_search.h(i) for i in range(3): grover_search = grover_search.compose(uncompute, [0,1,2,3,4,5,6,7,8]) # apply the uncompute operator grover_search = grover_search.compose(diffuser_circuit, [0,1,2,3]) # then apply the diffuser operator grover_search.measure([0,1,2,3],[0,1,2,3]) grover_search.draw('mpl') # Write a code to run the final circuit and plot the results to see if there are any satisfying assignments result = execute(grover_search, backend).result() counts = result.get_counts(grover_search) plot_histogram(counts) # List down the satisfying assignments and verify for yourself if they are correct # Write your code here fake_kolkata = FakeKolkata() fake_guadalupe = FakeGuadalupe() fake_kolkata_noisemodel = NoiseModel.from_backend(fake_kolkata) # Created a noisemodel from FakeKolkata backend fake_guadalupe_noisemodel = NoiseModel.from_backend(fake_guadalupe) # Created a noisemodel from FakeGuadalupe backend # simulate with fakekoklkata backend simulate_fake_kolkata = AerSimulator(noise_model = fake_kolkata_noisemodel) fake_kolkata_circ= transpile(grover_search,simulate_fake_kolkata) fake_kolkata_counts = simulate_fake_kolkata.run(fake_kolkata_circ,shots=1000).result().get_counts() plot_histogram(fake_kolkata_counts) # Simulate with fakeguadalupe bakcend simulate_fake_guadalupe = AerSimulator(noise_model = fake_guadalupe_noisemodel) fake_guadalupe_circ= transpile(grover_search,simulate_fake_guadalupe) fake_guadalupe_counts = simulate_fake_guadalupe.run(fake_guadalupe_circ,shots=1000).result().get_counts() plot_histogram(fake_guadalupe_counts) # Write your code here
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
geduardo
%matplotlib notebook import pew pew.init() screen=pew.Pix() # First we set variables of the game: # The snake will be represented by a list of (x,y) coordinates. The last element of the list (snake[-1]) will # represent the head of the snake. The 0th element of the list will be the last pixel of the tail. # Let's create the list by setting the initial position of the head at (3,3): snake=[(3,3)] # Now we create a variable to store the speed of the movement: game_speed=5 # We also have to define the initial velocity of the snake. Let's set it to move in the x direction by 1 pixel. dx, dy= 1, 0 # First we create and endless loop for the movement of the snake while True: x,y=snake[-1] # We store the current position of the head in two variables x and y. screen.pixel(x, y, 3) # This command turns on the pixel (x,y) with the maximum brightnes (3) to print on # on the screen the current position of the head pew.show(screen) # Lights up the active pixels on the screen. We need to pew.show(screen) each frame of the game. pew.tick(1/game_speed) # Sets the refresh rate. When bigger "game_speed" the lower the refresh rate and the game # runs faster # Now we have to check for user input by looking which keys are pressed. Depending on which keys are pressed the velocity of # of the snake will change. keys=pew.keys() # Return a number telling which keys (or buttons) have been pressed since the # last check. The number can then be filtered with the ``&`` operator and # the ``K_X``, ``K_DOWN``, ``K_LEFT``, ``K_RIGHT``, ``K_UP``, and ``K_O`` # constants to see whether any of the keys was pressed. if keys & pew.K_UP and dy == 0: dx, dy = 0, -1 # When the snake is moving in x and wee press UP the velocity of the snake changes to go up in the screen. # Note that in the pew-pew screen the index of the top row is 0 and the index of the bottom row is 7. # This explains why we have dy=-1 when we press UP. The rest of the keys follow a similar logic. elif keys & pew.K_LEFT and dx == 0: dx, dy = -1, 0 elif keys & pew.K_RIGHT and dx == 0: dx, dy = 1, 0 elif keys & pew.K_DOWN and dy == 0: dx, dy = 0, 1 # Now we calculate the next position of the snake's head: x=(x+dx)%8 y=(y+dy)%8 # We insert %8 to apply mod 8 to the coordinates, so when we pass through one of the walls we restart the counting and # appear in the other side of the screen. # We add to the list representing our snake a the next position of the head. snake.append((x,y)) #We delete from the list the last position of the snake (in this case the head) and turn of that pixel (x,y)=snake.pop(0) screen.pixel(x,y,0) import pew pew.init() screen=pew.Pix() snake=[(3,3)] game_speed=5 dx, dy= 1, 0 while True: x,y=snake[-1] screen.pixel(x, y, 3) pew.show(screen) pew.tick(1/game_speed) keys=pew.keys() if keys & pew.K_UP and dy == 0: dx, dy = 0, -1 elif keys & pew.K_LEFT and dx == 0: dx, dy = -1, 0 elif keys & pew.K_RIGHT and dx == 0: dx, dy = 1, 0 elif keys & pew.K_DOWN and dy == 0: dx, dy = 0, 1 #To implement the crashing mechanism we first have to get rid from the periodic screen, so we remove %8 x=(x+dx) y=(y+dy) #Now add an if condition that breaks the while loop if any of the coordinates for the new head goes out from the grid. if x >7 or y > 7 or x < 0 or y < 0: # We create a loop for turning of all the pixels that forms the screen. for (i,j) in snake: screen.pixel(i,j,0) break snake.append((x,y)) (x,y)=snake.pop(0) screen.pixel(x,y,0) # Now that we are out the loop we show the "Game Over" screen: text = pew.Pix.from_text("Game over!") for dx in range(-8, text.width): screen.blit(text, -dx, 1) pew.show(screen) pew.tick(1 / 12) from aether import QuantumCircuit, simulate def qrand(nbits): # We import the necessary elements form the aether library circ= QuantumCircuit(1,1) # We create a circuit with 1 qubit register and 1 classical bit register circ.h(0) # We apply the Hadamard gate to the qubit (note that by default the qubits are already intializated at 0) circ.measure(0, 0) # We make a measurement in the qubit and we store the result in the classical bit val = simulate(circ, shots=nbits, get='memory') # We simulate three times the circuit and we store the results in a list # We create a string with the binary number to use the function int() to obtain the integer b='' for i in range(nbits): b+= str(val[i]) # Trnsform the string into an int integ=int(b,2) # Return the integer return integ import pew from aether import QuantumCircuit, simulate # We define the function that we just created at the beginning of our code def qrand(nbits): circ= QuantumCircuit(1,1) circ.h(0) circ.measure(0, 0) val = simulate(circ, shots=nbits, get='memory') b='' for i in range(nbits): b+= str(val[i]) integ=int(b,2) return integ pew.init() screen=pew.Pix() snake=[(3,3)] game_speed=5 dx, dy= 1, 0 # We must define the initial position of the apple: apple_x, apple_y = 6, 6 screen.pixel(apple_x, apple_y, 3) while True: x,y=snake[-1] screen.pixel(x, y, 3) pew.show(screen) pew.tick(1/game_speed) keys=pew.keys() if keys & pew.K_UP and dy == 0: dx, dy = 0, -1 elif keys & pew.K_LEFT and dx == 0: dx, dy = -1, 0 elif keys & pew.K_RIGHT and dx == 0: dx, dy = 1, 0 elif keys & pew.K_DOWN and dy == 0: dx, dy = 0, 1 x=(x+dx) y=(y+dy) # We need to add the condition that if the next position of the snake's head is in the snake's body the player dies if (x,y) in snake or x >7 or y > 7 or x < 0 or y < 0: # We create a loop for turning of all the pixels that forms the screen. for (i,j) in snake: screen.pixel(i,j,0) break snake.append((x,y)) # In this loop we implement the generation of the apples each time the next position of the snake's head # lies into the current position of the apple if x == apple_x and y == apple_y: screen.pixel(apple_x, apple_y, 0) # We try the random generation of the apple until the apple appears out of the snake apple_x, apple_y = snake[0] while (apple_x, apple_y) in snake: apple_x=qrand(3) apple_y=qrand(3) screen.pixel(apple_x, apple_y, 2) # We also increase the velocity of the game each time the snake eats an apple gm_sp += 0.2 # Otherwise we remove the tail of the snake else: x, y = snake.pop(0) screen.pixel(x, y, 0) text = pew.Pix.from_text("Game over!") for dx in range(-8, text.width): screen.blit(text, -dx, 1) pew.show(screen) pew.tick(1 / 12) import pew from aether import QuantumCircuit, simulate def qrand(nbits): circ= QuantumCircuit(1,1) circ.h(0) circ.measure(0, 0) val = simulate(circ, shots=nbits, get='memory') b='' for i in range(nbits): b+= str(val[i]) integ=int(b,2) return integ pew.init() screen=pew.Pix() l=True # We initialize a boolean that will help us to reset the initial conditions of the game while True: #Now we put the condition of reseting the initial variables only if l=True if l: game_speed=5 points=0 # We initialize a variable to count the points snake = [(3,3)] dx, dy = 1, 0 apple_x, apple_y = 6, 6 screen.pixel(apple_x, apple_y, 3) l=False while True: x,y=snake[-1] screen.pixel(x, y, 3) pew.show(screen) pew.tick(1/game_speed) keys=pew.keys() if keys & pew.K_UP and dy == 0: dx, dy = 0, -1 elif keys & pew.K_LEFT and dx == 0: dx, dy = -1, 0 elif keys & pew.K_RIGHT and dx == 0: dx, dy = 1, 0 elif keys & pew.K_DOWN and dy == 0: dx, dy = 0, 1 x=(x+dx) y=(y+dy) if (x,y) in snake or x >7 or y > 7 or x < 0 or y < 0: for (i,j) in snake: screen.pixel(i,j,0) break snake.append((x,y)) if x == apple_x and y == apple_y: screen.pixel(apple_x, apple_y, 0) apple_x, apple_y = snake[0] while (apple_x, apple_y) in snake: apple_x=qrand(3) apple_y=qrand(3) screen.pixel(apple_x, apple_y, 2) game_speed += 0.2 # We add one to the points counter each time we eat an apple points=points+1 else: x, y = snake.pop(0) screen.pixel(x, y, 0) l=True # We set l to True to restart to the initial variables in the next iteration #Now let's display the points in the screen: text = pew.Pix.from_text('Points: ' + str(points)) for dx in range(-8, text.width): screen.blit(text, -dx, 1) pew.show(screen) pew.tick(1 / 12) text = pew.Pix.from_text("Game over!") for dx in range(-8, text.width): screen.blit(text, -dx, 1) pew.show(screen) pew.tick(1 / 12)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.visualization.timeline import draw as timeline_draw from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeBoeblingen backend = FakeBoeblingen() ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) circ = transpile(ghz, backend, scheduling_method="asap") timeline_draw(circ)
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 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. """ The Iterative Quantum Phase Estimation Algorithm. See https://arxiv.org/abs/quant-ph/0610214 """ import logging import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.quantum_info import Pauli from qiskit.aqua import Operator, AquaError from qiskit.aqua import Pluggable, PluggableType, get_pluggable_class from qiskit.aqua.utils import get_subsystem_density_matrix from qiskit.aqua.algorithms import QuantumAlgorithm logger = logging.getLogger(__name__) class IQPE(QuantumAlgorithm): """ The Iterative Quantum Phase Estimation algorithm. See https://arxiv.org/abs/quant-ph/0610214 """ PROP_NUM_TIME_SLICES = 'num_time_slices' PROP_EXPANSION_MODE = 'expansion_mode' PROP_EXPANSION_ORDER = 'expansion_order' PROP_NUM_ITERATIONS = 'num_iterations' CONFIGURATION = { 'name': 'IQPE', 'description': 'Iterative Quantum Phase Estimation for Quantum Systems', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'IQPE_schema', 'type': 'object', 'properties': { PROP_NUM_TIME_SLICES: { 'type': 'integer', 'default': 1, 'minimum': 1 }, PROP_EXPANSION_MODE: { 'type': 'string', 'default': 'suzuki', 'oneOf': [ {'enum': [ 'suzuki', 'trotter' ]} ] }, PROP_EXPANSION_ORDER: { 'type': 'integer', 'default': 2, 'minimum': 1 }, PROP_NUM_ITERATIONS: { 'type': 'integer', 'default': 1, 'minimum': 1 } }, 'additionalProperties': False }, 'problems': ['energy'], 'depends': [ {'pluggable_type': 'initial_state', 'default': { 'name': 'ZERO', }, }, ], } def __init__(self, operator, state_in, num_time_slices=1, num_iterations=1, expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=False): """ Constructor. Args: operator (Operator): the hamiltonian Operator object state_in (InitialState): the InitialState pluggable component representing the initial quantum state num_time_slices (int): the number of time slices num_iterations (int): the number of iterations expansion_mode (str): the expansion mode (trotter|suzuki) expansion_order (int): the suzuki expansion order shallow_circuit_concat (bool): indicate whether to use shallow (cheap) mode for circuit concatenation """ self.validate(locals()) super().__init__() self._operator = operator self._state_in = state_in self._num_time_slices = num_time_slices self._num_iterations = num_iterations self._expansion_mode = expansion_mode self._expansion_order = expansion_order self._shallow_circuit_concat = shallow_circuit_concat self._state_register = None self._ancillary_register = None self._pauli_list = None self._ret = {} self._setup() @classmethod def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance. Args: params: parameters dictionary algo_input: EnergyInput instance """ if algo_input is None: raise AquaError("EnergyInput instance is required.") operator = algo_input.qubit_op iqpe_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) num_time_slices = iqpe_params.get(IQPE.PROP_NUM_TIME_SLICES) expansion_mode = iqpe_params.get(IQPE.PROP_EXPANSION_MODE) expansion_order = iqpe_params.get(IQPE.PROP_EXPANSION_ORDER) num_iterations = iqpe_params.get(IQPE.PROP_NUM_ITERATIONS) # Set up initial state, we need to add computed num qubits to params init_state_params = params.get(Pluggable.SECTION_KEY_INITIAL_STATE) init_state_params['num_qubits'] = operator.num_qubits init_state = get_pluggable_class(PluggableType.INITIAL_STATE, init_state_params['name']).init_params(params) return cls(operator, init_state, num_time_slices=num_time_slices, num_iterations=num_iterations, expansion_mode=expansion_mode, expansion_order=expansion_order) def _setup(self): self._pauli_list = self._operator.get_flat_pauli_list() self._ret['translation'] = sum([abs(p[0]) for p in self._pauli_list]) self._ret['stretch'] = 0.5 / self._ret['translation'] # translate the operator self._operator._simplify_paulis() translation_op = Operator([ [ self._ret['translation'], Pauli( np.zeros(self._operator.num_qubits), np.zeros(self._operator.num_qubits) ) ] ]) translation_op._simplify_paulis() self._operator += translation_op # stretch the operator for p in self._pauli_list: p[0] = p[0] * self._ret['stretch'] if len(self._pauli_list) == 1: slice_pauli_list = self._pauli_list else: if self._expansion_mode == 'trotter': slice_pauli_list = self._pauli_list else: slice_pauli_list = Operator._suzuki_expansion_slice_pauli_list(self._pauli_list, 1, self._expansion_order) self._slice_pauli_list = slice_pauli_list def construct_circuit(self, k=None, omega=0, measurement=False): """Construct the kth iteration Quantum Phase Estimation circuit. For details of parameters, please see Fig. 2 in https://arxiv.org/pdf/quant-ph/0610214.pdf. Args: k (int): the iteration idx. omega (float): the feedback angle. measurement (bool): Boolean flag to indicate if measurement should be included in the circuit. Returns: QuantumCircuit: the quantum circuit per iteration """ k = self._num_iterations if k is None else k a = QuantumRegister(1, name='a') q = QuantumRegister(self._operator.num_qubits, name='q') self._ancillary_register = a self._state_register = q qc = QuantumCircuit(q) qc += self._state_in.construct_circuit('circuit', q) # hadamard on a[0] qc.add_register(a) qc.u2(0, np.pi, a[0]) # controlled-U qc_evolutions = Operator.construct_evolution_circuit( self._slice_pauli_list, -2 * np.pi, self._num_time_slices, q, a, unitary_power=2 ** (k - 1), shallow_slicing=self._shallow_circuit_concat ) if self._shallow_circuit_concat: qc.data += qc_evolutions.data else: qc += qc_evolutions # global phase due to identity pauli qc.u1(2 * np.pi * self._ancilla_phase_coef * (2 ** (k - 1)), a[0]) # rz on a[0] qc.u1(omega, a[0]) # hadamard on a[0] qc.u2(0, np.pi, a[0]) if measurement: c = ClassicalRegister(1, name='c') qc.add_register(c) # qc.barrier(self._ancillary_register) qc.measure(self._ancillary_register, c) return qc def _estimate_phase_iteratively(self): """Iteratively construct the different order of controlled evolution circuit to carry out phase estimation.""" self._ret['top_measurement_label'] = '' omega_coef = 0 # k runs from the number of iterations back to 1 for k in range(self._num_iterations, 0, -1): omega_coef /= 2 if self._quantum_instance.is_statevector: qc = self.construct_circuit(k, -2 * np.pi * omega_coef, measurement=False) result = self._quantum_instance.execute(qc) complete_state_vec = result.get_statevector(qc) ancilla_density_mat = get_subsystem_density_matrix( complete_state_vec, range(self._operator.num_qubits) ) ancilla_density_mat_diag = np.diag(ancilla_density_mat) max_amplitude = max(ancilla_density_mat_diag.min(), ancilla_density_mat_diag.max(), key=abs) x = np.where(ancilla_density_mat_diag == max_amplitude)[0][0] else: qc = self.construct_circuit(k, -2 * np.pi * omega_coef, measurement=True) measurements = self._quantum_instance.execute(qc).get_counts(qc) if '0' not in measurements: if '1' in measurements: x = 1 else: raise RuntimeError('Unexpected measurement {}.'.format(measurements)) else: if '1' not in measurements: x = 0 else: x = 1 if measurements['1'] > measurements['0'] else 0 self._ret['top_measurement_label'] = '{}{}'.format(x, self._ret['top_measurement_label']) omega_coef = omega_coef + x / 2 logger.info('Reverse iteration {} of {} with measured bit {}'.format(k, self._num_iterations, x)) return omega_coef def _compute_energy(self): # check for identify paulis to get its coef for applying global phase shift on ancilla later num_identities = 0 self._pauli_list = self._operator.get_flat_pauli_list() for p in self._pauli_list: if np.all(np.logical_not(p[1].z)) and np.all(np.logical_not(p[1].x)): num_identities += 1 if num_identities > 1: raise RuntimeError('Multiple identity pauli terms are present.') self._ancilla_phase_coef = p[0].real if isinstance(p[0], complex) else p[0] self._ret['phase'] = self._estimate_phase_iteratively() self._ret['top_measurement_decimal'] = sum([t[0] * t[1] for t in zip( [1 / 2 ** p for p in range(1, self._num_iterations + 1)], [int(n) for n in self._ret['top_measurement_label']] )]) self._ret['energy'] = self._ret['phase'] / self._ret['stretch'] - self._ret['translation'] def _run(self): self._compute_energy() return self._ret
https://github.com/QPower-Research/QPowerAlgo
QPower-Research
import numpy as np from sklearn.datasets.samples_generator import make_blobs from qiskit.aqua.utils import split_dataset_to_data_and_labels from sklearn import svm from utility import breast_cancer_pca from matplotlib import pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 n = 2 # number of principal components kept training_dataset_size = 20 testing_dataset_size = 10 sample_Total, training_input, test_input, class_labels = breast_cancer_pca(training_dataset_size, testing_dataset_size, n) data_train, _ = split_dataset_to_data_and_labels(training_input) data_test, _ = split_dataset_to_data_and_labels(test_input) print (f"data_train[0].shape: {data_train[0].shape}" ) print (f"data_train[1].shape: {data_train[1].shape}" ) # We use the function of scikit learn to generate linearly separable blobs centers = [(2.5,0),(0,2.5)] x, y = make_blobs(n_samples=100, centers=centers, n_features=2,random_state=0,cluster_std=0.5) fig,ax=plt.subplots(1,2,figsize=(12,4)) ax[0].scatter(data_train[0][:,0],data_train[0][:,1],c=data_train[1]) ax[0].set_title('Breast Cancer dataset'); ax[1].scatter(x[:,0],x[:,1],c=y) ax[1].set_title('Blobs linearly separable'); plt.scatter(data_train[0][:,0],data_train[0][:,1],c=data_train[1]) plt.title('Breast Cancer dataset'); model= svm.LinearSVC() model.fit(data_train[0], data_train[1]) #small utility function # some utility functions def make_meshgrid(x, y, h=.02): x_min, x_max = x.min() - 1, x.max() + 1 y_min, y_max = y.min() - 1, y.max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) return xx, yy def plot_contours(ax, clf, xx, yy, **params): Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) out = ax.contourf(xx, yy, Z, **params) return out accuracy_train = model.score(data_train[0], data_train[1]) accuracy_test = model.score(data_test[0], data_test[1]) X0, X1 = data_train[0][:, 0], data_train[0][:, 1] xx, yy = make_meshgrid(X0, X1) Z = model.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) fig,ax=plt.subplots(1,2,figsize=(15,5)) ax[0].contourf(xx, yy, Z, cmap=plt.cm.coolwarm) ax[0].scatter(data_train[0][:,0], data_train[0][:,1], c=data_train[1]) ax[0].set_title('Accuracy on the training set: '+str(accuracy_train)); ax[1].contourf(xx, yy, Z, cmap=plt.cm.coolwarm) ax[1].scatter(data_test[0][:,0], data_test[0][:,1], c=data_test[1]) ax[1].set_title('Accuracy on the test set: '+str(accuracy_test)); clf = svm.SVC(gamma = 'scale') clf.fit(data_train[0], data_train[1]); accuracy_train = clf.score(data_train[0], data_train[1]) accuracy_test = clf.score(data_test[0], data_test[1]) X0, X1 = data_train[0][:, 0], data_train[0][:, 1] xx, yy = make_meshgrid(X0, X1) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) fig,ax=plt.subplots(1,2,figsize=(15,5)) ax[0].contourf(xx, yy, Z, cmap=plt.cm.coolwarm) ax[0].scatter(data_train[0][:,0], data_train[0][:,1], c=data_train[1]) ax[0].set_title('Accuracy on the training set: '+str(accuracy_train)); ax[1].contourf(xx, yy, Z, cmap=plt.cm.coolwarm) ax[1].scatter(data_test[0][:,0], data_test[0][:,1], c=data_test[1]) ax[1].set_title('Accuracy on the test set: '+str(accuracy_test)); import qiskit as qk # Creating Qubits q = qk.QuantumRegister(2) # Creating Classical Bits c = qk.ClassicalRegister(2) circuit = qk.QuantumCircuit(q, c) circuit.draw('mpl') # Initialize empty circuit circuit = qk.QuantumCircuit(q, c) # Hadamard Gate on the first Qubit circuit.h(q[0]) # CNOT Gate on the first and second Qubits circuit.cx(q[0], q[1]) # Measuring the Qubits circuit.measure(q, c) circuit.draw('mpl') # Using Qiskit Aer's Qasm Simulator: Define where do you want to run the simulation. simulator = qk.BasicAer.get_backend('qasm_simulator') # Simulating the circuit using the simulator to get the result job = qk.execute(circuit, simulator, shots=100) result = job.result() # Getting the aggregated binary outcomes of the circuit. counts = result.get_counts(circuit) print (counts) from qiskit.aqua.components.feature_maps import SecondOrderExpansion feature_map = SecondOrderExpansion(feature_dimension=2, depth=1) x = np.array([0.6, 0.3]) #feature_map.construct_circuit(x) print(feature_map.construct_circuit(x)) from qiskit.aqua.algorithms import QSVM qsvm = QSVM(feature_map, training_input, test_input) #from qiskit.aqua import run_algorithm, QuantumInstance from qiskit.aqua import algorithm, QuantumInstance from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=10598, seed_transpiler=10598) result = qsvm.run(quantum_instance) plt.scatter(training_input['Benign'][:,0], training_input['Benign'][:,1]) plt.scatter(training_input['Malignant'][:,0], training_input['Malignant'][:,1]) length_data = len(training_input['Benign']) + len(training_input['Malignant']) print("size training set: {}".format(length_data)) #print("Matrix dimension: {}".format(result['kernel_matrix_training'].shape)) print("testing success ratio: ", result['testing_accuracy']) test_set = np.concatenate((test_input['Benign'], test_input['Malignant'])) y_test = qsvm.predict(test_set, quantum_instance) plt.scatter(test_set[:, 0], test_set[:,1], c=y_test) plt.show() plt.scatter(test_input['Benign'][:,0], test_input['Benign'][:,1]) plt.scatter(test_input['Malignant'][:,0], test_input['Malignant'][:,1]) plt.show()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits to represent the uncertainty num_uncertainty_qubits = 3 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # construct circuit for uncertainty model uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high) ) # plot probability distribution x = uncertainty_model.values y = uncertainty_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.show() # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 1.438 strike_price_2 = 2.584 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, strike_price_2 - strike_price_1] f_min = 0 f_max = strike_price_2 - strike_price_1 bull_spread_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective bull_spread = bull_spread_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value (normalized to the [0, 1] interval) exact_value = np.dot(uncertainty_model.probabilities, y) exact_delta = sum( uncertainty_model.probabilities[np.logical_and(x >= strike_price_1, x <= strike_price_2)] ) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread, objective_qubits=[num_uncertainty_qubits], post_processing=bull_spread_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 0, 0] offsets = [0, 1, 0] f_min = 0 f_max = 1 bull_spread_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # no approximation necessary, hence no rescaling factor # construct the A operator by stacking the uncertainty model and payoff function together bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval) print("Exact delta: \t%.4f" % exact_delta) print("Estimated value:\t%.4f" % result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit import execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qrx = QuantumRegister(3, 'x') qry = QuantumRegister(1, 'y') cr = ClassicalRegister(3, '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") sim = AerSimulator() job = execute(qc, backend = sim, shots = 1000) result = job.result() counts = result.get_counts(qc) print("Counts: ", counts) plot_histogram(counts)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import itertools import numpy as np from functools import partial, reduce from qiskit import BasicAer, QuantumRegister, execute from qiskit.quantum_info import Pauli from qiskit_aqua import Operator, get_aer_backend from qiskit_aqua.components.initial_states import Custom from scipy.optimize import minimize np.set_printoptions(precision=3, suppress=True) def pauli_x(qubit, coeff): eye = np.eye((n_qubits)) return Operator([[coeff, Pauli(np.zeros(n_qubits), eye[qubit])]]) n_qubits = 2 Hm = reduce(lambda x, y: x+y, [pauli_x(i, 1) for i in range(n_qubits)]) Hm.to_matrix() def pauli_z(qubit, coeff): eye = np.eye((n_qubits)) return Operator([[coeff, Pauli(eye[qubit], np.zeros(n_qubits))]]) def product_pauli_z(q1, q2, coeff): eye = np.eye((n_qubits)) return Operator([[coeff, Pauli(eye[q1], np.zeros(n_qubits)) * Pauli(eye[q2], np.zeros(n_qubits))]]) J = np.array([[0,1],[0,0]]) Hc = reduce(lambda x,y:x+y, [product_pauli_z(i,j, -J[i,j]) for i,j in itertools.product(range(n_qubits), repeat=2)]) Hc.to_matrix() n_iter = 10 # number of iterations of the optimization procedure p = 2 beta = np.random.uniform(0, np.pi*2, p) gamma = np.random.uniform(0, np.pi*2, p) init_state_vect = [1 for i in range(2**n_qubits)] init_state = Custom(n_qubits, state_vector=init_state_vect) qr = QuantumRegister(n_qubits) circuit_init = init_state.construct_circuit('circuit', qr) def evolve(hamiltonian, angle, quantum_registers): return hamiltonian.evolve(None, angle, 'circuit', 1, quantum_registers=quantum_registers, expansion_mode='suzuki', expansion_order=3) def create_circuit(qr, gamma, beta, p): circuit_evolv = reduce(lambda x,y: x+y, [evolve(Hm, beta[i], qr) + evolve(Hc, gamma[i], qr) for i in range(p)]) circuit = circuit_init + circuit_evolv return circuit def evaluate_circuit(gamma_beta, qr, p): n = len(gamma_beta)//2 circuit = create_circuit(qr, gamma_beta[:n], gamma_beta[n:], p) return np.real(Hc.eval("matrix", circuit, get_aer_backend('statevector_simulator'))[0]) evaluate = partial(evaluate_circuit, qr=qr, p=p) result = minimize(evaluate, np.concatenate([gamma, beta]), method='L-BFGS-B') result circuit = create_circuit(qr, result['x'][:p], result['x'][p:], p) backend = BasicAer.get_backend('statevector_simulator') job = execute(circuit, backend) state = np.asarray(job.result().get_statevector(circuit)) print(np.absolute(state)) print(np.angle(state)) Z0 = pauli_z(0, 1) Z1 = pauli_z(1, 1) print(Z0.eval("matrix", circuit, get_aer_backend('statevector_simulator'))[0]) print(Z1.eval("matrix", circuit, get_aer_backend('statevector_simulator'))[0])
https://github.com/bibscore/qiskit_kindergarten
bibscore
import qiskit qiskit.__qiskit_version__ #initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load our saved IBMQ accounts. IBMQ.load_account() nQubits = 14 # number of physical qubits a = 101 # the hidden integer whose bitstring is 1100101 # make sure that a can be represented with nQubits a = a % 2**(nQubits) # Creating registers # qubits for querying the oracle and finding the hidden integer qr = QuantumRegister(nQubits) # for recording the measurement on qr cr = ClassicalRegister(nQubits) circuitName = "BernsteinVazirani" bvCircuit = QuantumCircuit(qr, cr) # Apply Hadamard gates before querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Apply barrier so that it is not optimized by the compiler bvCircuit.barrier() # Apply the inner-product oracle for i in range(nQubits): if (a & (1 << i)): bvCircuit.z(qr[i]) else: bvCircuit.iden(qr[i]) # Apply barrier bvCircuit.barrier() #Apply Hadamard gates after querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Measurement bvCircuit.barrier(qr) bvCircuit.measure(qr, cr) bvCircuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1000 results = execute(bvCircuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') shots = 1000 bvCompiled = transpile(bvCircuit, backend=backend, optimization_level=1) job_exp = execute(bvCircuit, backend=backend, shots=shots) job_monitor(job_exp) results = job_exp.result() answer = results.get_counts(bvCircuit) threshold = int(0.01 * shots) #the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} #filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) #number of counts removed filteredAnswer['other_bitstrings'] = removedCounts #the removed counts is assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """PauliOp Class""" from math import pi from typing import Dict, List, Optional, Set, Union, cast import numpy as np from scipy.sparse import spmatrix from qiskit import QuantumCircuit from qiskit.circuit import Instruction, ParameterExpression from qiskit.circuit.library import RXGate, RYGate, RZGate, XGate, YGate, ZGate from qiskit.circuit.library.generalized_gates import PauliGate from qiskit.opflow.exceptions import OpflowError from qiskit.opflow.list_ops.summed_op import SummedOp from qiskit.opflow.list_ops.tensored_op import TensoredOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector from qiskit.utils.deprecation import deprecate_func class PauliOp(PrimitiveOp): """Deprecated: Class for Operators backed by Terra's ``Pauli`` module.""" primitive: Pauli @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, primitive: Pauli, coeff: Union[complex, ParameterExpression] = 1.0) -> None: """ Args: primitive: The Pauli which defines the behavior of the underlying function. coeff: A coefficient multiplying the primitive. Raises: TypeError: invalid parameters. """ if not isinstance(primitive, Pauli): raise TypeError(f"PauliOp can only be instantiated with Paulis, not {type(primitive)}") super().__init__(primitive, coeff=coeff) def primitive_strings(self) -> Set[str]: return {"Pauli"} @property def num_qubits(self) -> int: return len(self.primitive) def add(self, other: OperatorBase) -> OperatorBase: if not self.num_qubits == other.num_qubits: raise ValueError( "Sum over operators with different numbers of qubits, {} and {}, is not well " "defined".format(self.num_qubits, other.num_qubits) ) if isinstance(other, PauliOp) and self.primitive == other.primitive: return PauliOp(self.primitive, coeff=self.coeff + other.coeff) # pylint: disable=cyclic-import from .pauli_sum_op import PauliSumOp if ( isinstance(other, PauliOp) and isinstance(self.coeff, (int, float, complex)) and isinstance(other.coeff, (int, float, complex)) ): return PauliSumOp( SparsePauliOp(self.primitive, coeffs=[self.coeff]) + SparsePauliOp(other.primitive, coeffs=[other.coeff]) ) if isinstance(other, PauliSumOp) and isinstance(self.coeff, (int, float, complex)): return PauliSumOp(SparsePauliOp(self.primitive, coeffs=[self.coeff])) + other return SummedOp([self, other]) def adjoint(self) -> "PauliOp": return PauliOp(self.primitive.adjoint(), coeff=self.coeff.conjugate()) def equals(self, other: OperatorBase) -> bool: if isinstance(other, PauliOp) and self.coeff == other.coeff: return self.primitive == other.primitive # pylint: disable=cyclic-import from .pauli_sum_op import PauliSumOp if isinstance(other, PauliSumOp): return other == self return False def _expand_dim(self, num_qubits: int) -> "PauliOp": return PauliOp(Pauli("I" * num_qubits).expand(self.primitive), coeff=self.coeff) def tensor(self, other: OperatorBase) -> OperatorBase: # Both Paulis if isinstance(other, PauliOp): return PauliOp(self.primitive.tensor(other.primitive), coeff=self.coeff * other.coeff) # pylint: disable=cyclic-import from .pauli_sum_op import PauliSumOp if isinstance(other, PauliSumOp): new_primitive = SparsePauliOp(self.primitive).tensor(other.primitive) return PauliSumOp(new_primitive, coeff=self.coeff * other.coeff) from .circuit_op import CircuitOp if isinstance(other, CircuitOp): return self.to_circuit_op().tensor(other) return TensoredOp([self, other]) def permute(self, permutation: List[int]) -> "PauliOp": """Permutes the sequence of Pauli matrices. Args: permutation: A list defining where each Pauli should be permuted. The Pauli at index j of the primitive should be permuted to position permutation[j]. Returns: A new PauliOp representing the permuted operator. For operator (X ^ Y ^ Z) and indices=[1,2,4], it returns (X ^ I ^ Y ^ Z ^ I). Raises: OpflowError: if indices do not define a new index for each qubit. """ pauli_string = self.primitive.__str__() length = max(permutation) + 1 # size of list must be +1 larger then its max index new_pauli_list = ["I"] * length if len(permutation) != self.num_qubits: raise OpflowError( "List of indices to permute must have the same size as Pauli Operator" ) for i, index in enumerate(permutation): new_pauli_list[-index - 1] = pauli_string[-i - 1] return PauliOp(Pauli("".join(new_pauli_list)), self.coeff) def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(PauliOp, new_self) if front: return other.compose(new_self) # Both Paulis if isinstance(other, PauliOp): product = new_self.primitive.dot(other.primitive) return PrimitiveOp(product, coeff=new_self.coeff * other.coeff) # pylint: disable=cyclic-import from .pauli_sum_op import PauliSumOp if isinstance(other, PauliSumOp): return PauliSumOp( SparsePauliOp(new_self.primitive).dot(other.primitive), coeff=new_self.coeff * other.coeff, ) # pylint: disable=cyclic-import from ..state_fns.circuit_state_fn import CircuitStateFn from .circuit_op import CircuitOp if isinstance(other, (CircuitOp, CircuitStateFn)): return new_self.to_circuit_op().compose(other) return super(PauliOp, new_self).compose(other) def to_matrix(self, massive: bool = False) -> np.ndarray: OperatorBase._check_massive("to_matrix", True, self.num_qubits, massive) return self.primitive.to_matrix() * self.coeff def to_spmatrix(self) -> spmatrix: """Returns SciPy sparse matrix representation of the Operator. Returns: CSR sparse matrix representation of the Operator. Raises: ValueError: invalid parameters. """ return self.primitive.to_matrix(sparse=True) * self.coeff def __str__(self) -> str: prim_str = str(self.primitive) if self.coeff == 1.0: return prim_str else: return f"{self.coeff} * {prim_str}" def eval( self, front: Optional[ Union[str, Dict[str, complex], np.ndarray, OperatorBase, Statevector] ] = None, ) -> Union[OperatorBase, complex]: if front is None: return self.to_matrix_op() # pylint: disable=cyclic-import from ..list_ops.list_op import ListOp from ..state_fns.circuit_state_fn import CircuitStateFn from ..state_fns.dict_state_fn import DictStateFn from ..state_fns.state_fn import StateFn from .circuit_op import CircuitOp new_front = None # For now, always do this. If it's not performant, we can be more granular. if not isinstance(front, OperatorBase): front = StateFn(front, is_measurement=False) if isinstance(front, ListOp) and front.distributive: new_front = front.combo_fn( [self.eval(front.coeff * front_elem) for front_elem in front.oplist] ) else: if self.num_qubits != front.num_qubits: raise ValueError( "eval does not support operands with differing numbers of qubits, " "{} and {}, respectively.".format(self.num_qubits, front.num_qubits) ) if isinstance(front, DictStateFn): new_dict: Dict[str, complex] = {} corrected_x_bits = self.primitive.x[::-1] corrected_z_bits = self.primitive.z[::-1] for bstr, v in front.primitive.items(): bitstr = np.fromiter(bstr, dtype=int).astype(bool) new_b_str = np.logical_xor(bitstr, corrected_x_bits) new_str = "".join(map(str, 1 * new_b_str)) z_factor = np.prod(1 - 2 * np.logical_and(bitstr, corrected_z_bits)) y_factor = np.prod( np.sqrt(1 - 2 * np.logical_and(corrected_x_bits, corrected_z_bits) + 0j) ) new_dict[new_str] = (v * z_factor * y_factor) + new_dict.get(new_str, 0) # The coefficient consists of: # 1. the coefficient of *this* PauliOp (self) # 2. the coefficient of the evaluated DictStateFn (front) # 3. AND acquires the phase of the internal primitive. This is necessary to # ensure that (X @ Z) and (-iY) return the same result. new_front = StateFn( new_dict, coeff=self.coeff * front.coeff * (-1j) ** self.primitive.phase ) elif isinstance(front, StateFn) and front.is_measurement: raise ValueError("Operator composed with a measurement is undefined.") # Composable types with PauliOp elif isinstance(front, (PauliOp, CircuitOp, CircuitStateFn)): new_front = self.compose(front) # Covers VectorStateFn and OperatorStateFn elif isinstance(front, StateFn): new_front = self.to_matrix_op().eval(front.to_matrix_op()) return new_front def exp_i(self) -> OperatorBase: """Return a ``CircuitOp`` equivalent to e^-iH for this operator H.""" # if only one qubit is significant, we can perform the evolution corrected_x = self.primitive.x[::-1] corrected_z = self.primitive.z[::-1] sig_qubits = np.logical_or(corrected_x, corrected_z) if np.sum(sig_qubits) == 0: # e^I is just a global phase, but we can keep track of it! Should we? # For now, just return identity return PauliOp(self.primitive) if np.sum(sig_qubits) == 1: sig_qubit_index = sig_qubits.tolist().index(True) coeff = ( np.real(self.coeff) if not isinstance(self.coeff, ParameterExpression) else self.coeff ) from .circuit_op import CircuitOp # Y rotation if corrected_x[sig_qubit_index] and corrected_z[sig_qubit_index]: rot_op = CircuitOp(RYGate(2 * coeff)) # Z rotation elif corrected_z[sig_qubit_index]: rot_op = CircuitOp(RZGate(2 * coeff)) # X rotation elif corrected_x[sig_qubit_index]: rot_op = CircuitOp(RXGate(2 * coeff)) # pylint: disable=cyclic-import from ..operator_globals import I left_pad = I.tensorpower(sig_qubit_index) right_pad = I.tensorpower(self.num_qubits - sig_qubit_index - 1) # Need to use overloaded operators here in case left_pad == I^0 return left_pad ^ rot_op ^ right_pad else: from ..evolutions.evolved_op import EvolvedOp return EvolvedOp(self) def to_circuit(self) -> QuantumCircuit: pauli = self.primitive.to_label()[-self.num_qubits :] phase = self.primitive.phase qc = QuantumCircuit(self.num_qubits) if pauli == "I" * self.num_qubits: qc.global_phase = -phase * pi / 2 return qc if self.num_qubits == 1: if pauli != "I": gate = {"X": XGate, "Y": YGate, "Z": ZGate}[pauli] qc.append(gate(), [0]) else: gate = PauliGate(pauli) qc.append(gate, range(self.num_qubits)) if not phase: return qc qc.global_phase = -phase * pi / 2 return qc def to_instruction(self) -> Instruction: # TODO should we just do the following because performance of adding and deleting IGates # doesn't matter? # (Reduce removes extra IGates). # return PrimitiveOp(self.primitive.to_instruction(), coeff=self.coeff).reduce() return self.primitive.to_instruction() def to_pauli_op(self, massive: bool = False) -> "PauliOp": return self
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_qsphere(state)
https://github.com/Axect/QuantumAlgorithms
Axect
from qiskit import QuantumCircuit,Aer, execute from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt def check_computational_basis(basis): n = int(np.log2(len(basis))) qc = QuantumCircuit(n,n) initial_state = np.array(basis) / np.linalg.norm(basis) qc.initialize(initial_state, reversed(range(n))) # Input : LSB -> MSB qc.measure(range(n), reversed(range(n))) # Readout: LSB -> MSB backend = Aer.get_backend('qasm_simulator') counts = execute(qc,backend).result().get_counts().keys() return counts def gen_bases(n): return np.eye(2**n) bases = gen_bases(3) for i in range(bases.shape[0]): basis = bases[i].tolist() print(f"basis: {basis} -> {check_computational_basis(basis)}") def convert_zbasis_to_cbasis(zbasis): """ Converts a basis state in the Z basis to the computational basis Example: Input: [0,0] -> Output: [1,0,0,0] Input: [0,1] -> Output: [0,1,0,0] Input: [1,0] -> Output: [0,0,1,0] Input: [1,1] -> Output: [0,0,0,1] """ n = 2**len(zbasis) # z basis to binary number bin_str = "".join([str(x) for x in zbasis]) num = int(bin_str,2) # binary number to computational basis cbasis = np.zeros(n) cbasis[num] = 1 return cbasis def cswap_test(x): qc = QuantumCircuit(len(x)+1, 1) input_state = convert_zbasis_to_cbasis(x) qc.initialize(input_state, reversed(range(1,len(x)+1))) qc.barrier() qc.h(0) qc.cswap(0,1,2) qc.h(0) qc.measure(0,0) backend = Aer.get_backend('qasm_simulator') return qc, execute(qc,backend).result().get_counts() qc, counts = cswap_test([0,1]) qc.draw(output='mpl', style='iqx') plot_histogram(counts) states = [ [0,0], [0,1], [1,0], [1,1] ] fig, ax = plt.subplots(1,4, figsize=(16,4)) for i, state in enumerate(states): _, counts = cswap_test(state) plot_histogram(counts, ax=ax[i]) ax[i].set_title(f"Input: {state}") plt.tight_layout() plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit 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/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Quantum Fourier Transform Circuit. """ import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua import AquaError from qiskit.aqua.utils.circuit_utils import is_qubit_list class FourierTransformCircuits: @staticmethod def _do_swaps(circuit, qubits): num_qubits = len(qubits) for i in range(num_qubits // 2): circuit.cx(qubits[i], qubits[num_qubits - i - 1]) circuit.cx(qubits[num_qubits - i - 1], qubits[i]) circuit.cx(qubits[i], qubits[num_qubits - i - 1]) @staticmethod def construct_circuit( circuit=None, qubits=None, inverse=False, approximation_degree=0, do_swaps=True ): """ Construct the circuit representing the desired state vector. Args: circuit (QuantumCircuit): The optional circuit to extend from. qubits (QuantumRegister | list of qubits): The optional qubits to construct the circuit with. approximation_degree (int): degree of approximation for the desired circuit inverse (bool): Boolean flag to indicate Inverse Quantum Fourier Transform do_swaps (bool): Boolean flag to specify if swaps should be included to align the qubit order of input and output. The output qubits would be in reversed order without the swaps. Returns: QuantumCircuit. """ if circuit is None: raise AquaError('Missing input QuantumCircuit.') if qubits is None: raise AquaError('Missing input qubits.') else: if isinstance(qubits, QuantumRegister): if not circuit.has_register(qubits): circuit.add_register(qubits) elif is_qubit_list(qubits): for qubit in qubits: if not circuit.has_register(qubit[0]): circuit.add_register(qubit[0]) else: raise AquaError('A QuantumRegister or a list of qubits is expected for the input qubits.') if do_swaps and not inverse: FourierTransformCircuits._do_swaps(circuit, qubits) qubit_range = reversed(range(len(qubits))) if inverse else range(len(qubits)) for j in qubit_range: neighbor_range = range(np.max([0, j - len(qubits) + approximation_degree + 1]), j) if inverse: neighbor_range = reversed(neighbor_range) circuit.u2(0, np.pi, qubits[j]) for k in neighbor_range: lam = 1.0 * np.pi / float(2 ** (j - k)) if inverse: lam *= -1 circuit.u1(lam / 2, qubits[j]) circuit.cx(qubits[j], qubits[k]) circuit.u1(-lam / 2, qubits[k]) circuit.cx(qubits[j], qubits[k]) circuit.u1(lam / 2, qubits[k]) if not inverse: circuit.u2(0, np.pi, qubits[j]) if do_swaps and inverse: FourierTransformCircuits._do_swaps(circuit, qubits) return circuit
https://github.com/Shashankaubaru/NISQ-TDA
Shashankaubaru
import numpy as np import pdb from pdb import set_trace as bp # Import Qiskit from qiskit import QuantumCircuit, QuantumRegister from qiskit import Aer, transpile from qiskit.tools.visualization import plot_histogram, plot_state_city import qiskit.quantum_info as qi from qiskit.providers.aer import AerError # Create circuit myreg = QuantumRegister(16) circ = QuantumCircuit(myreg) circ.h(myreg) circ.cx(0, 1) circ.measure_all() # Initialize a GPU backend # Note that the cloud instance for tutorials does not have a GPU # so this will raise an exception. try: print(Aer.backends()) simulator_gpu = Aer.get_backend('aer_simulator_statevector_gpu') # simulator_gpu.set_options(device='GPU') # bp() circ = transpile(circ, simulator_gpu) # Run and get counts result = simulator_gpu.run(circ).result() counts = result.get_counts(circ) print(len(counts)) except AerError as e: print(e)
https://github.com/anpaschool/QC-School-Fall2020
anpaschool
import numpy as np n_samples = 100 p_1 = 0.2 x_data = np.random.binomial(1, p_1, (n_samples,)) print(x_data) frequency_of_zeros, frequency_of_ones = 0, 0 for x in x_data: if x: frequency_of_ones += 1/n_samples else: frequency_of_zeros += 1/n_samples print(frequency_of_ones+frequency_of_zeros) import matplotlib.pyplot as plt %matplotlib inline p_0 = np.linspace(0, 1, 100) #print(p_0) p_1 = 1-p_0 #print(p_1) fig, ax = plt.subplots() ax.set_xlim(-1.2, 1.2) ax.set_ylim(-1.2, 1.2) ax.spines['left'].set_position('center') ax.spines['bottom'].set_position('center') ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.set_xlabel("$p_0$") ax.xaxis.set_label_coords(1.0, 0.5) ax.set_ylabel("$p_1$") ax.yaxis.set_label_coords(0.5, 1.0) plt.plot(p_0, p_1) p = np.array([[0.7], [0.3]]) np.linalg.norm(p, ord=1) Π_0 = np.array([[1, 0], [0, 0]]) np.linalg.norm(Π_0 @ p, ord=1) Π_1 = np.array([[0, 0], [0, 1]]) np.linalg.norm(Π_1 @ p, ord=1) p = np.array([[.5], [.5]]) M = np.array([[0.7, 0.6], [0.3, 0.4]]) np.linalg.norm(M @ p, ord=1) ϵ = 10e-10 p_0 = np.linspace(ϵ, 1-ϵ, 100) p_1 = 1-p_0 H = -(p_0*np.log2(p_0) + p_1*np.log2(p_1)) fig, ax = plt.subplots() ax.set_xlim(0, 1) ax.set_ylim(0, -np.log2(0.5)) ax.set_xlabel("$p_0$") ax.set_ylabel("$H$") plt.plot(p_0, H) plt.axvline(x=0.5, color='k', linestyle='--') from qiskit import QuantumCircuit, execute,QuantumCircuit, ClassicalRegister, QuantumRegister, Aer from qiskit.visualization import plot_histogram, plot_bloch_vector,plot_bloch_multivector,plot_state_qsphere from math import sqrt, pi import numpy as np %matplotlib inline qc = QuantumCircuit(1) # Create a quantum circuit with one qubit backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit job = execute(qc,backend).result() # Do the simulation, returning the state vector plot_bloch_multivector(job.get_statevector()) # Display the output state vector initial_state = [0,1] # Define initial_state as |1> qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit qc.draw()# Let's view our circuit result = execute(qc,backend).result() # Do the simulation, returning the state vector plot_bloch_multivector(result.get_statevector()) # Display the output state vector out_state = result.get_statevector() print(out_state) # Display the output state vector qc.measure_all() qc.draw() result = execute(qc,backend).result() counts = result.get_counts() plot_histogram(counts) initial_state = [1/sqrt(2), 1j/sqrt(2)] # Define state |q> qc = QuantumCircuit(1) # Must redefine qc qc.initialize(initial_state, 0)# Initialise the 0th qubit in the state `initial_state` qc.h(0) qc.draw() state = execute(qc,backend).result().get_statevector() # Execute the circuit print(state) # Print the result results = execute(qc,backend).result().get_counts() plot_histogram(results) vector = [0,1] qc.initialize(vector, 0) qc = QuantumCircuit(1) # Redefine qc initial_state = [0.+1.j/sqrt(2),1/sqrt(2)+0.j] qc.initialize(initial_state, 0) print(initial_state) qc.draw() state = execute(qc, backend).result().get_statevector() print("Qubit State = " + str(state)) qc.measure_all() qc.draw() state = execute(qc, backend).result().get_statevector() print("State of Measured Qubit = " + str(state)) π = np.pi backend = BasicAer.get_backend('qasm_simulator') q = QuantumRegister(1) c = ClassicalRegister(1) circuit = QuantumCircuit(q, c) circuit.measure(q, c) job = execute(circuit, backend, shots=100) result = job.result() result.get_counts(circuit) backend_statevector = BasicAer.get_backend('statevector_simulator') circuit = QuantumCircuit(q, c) circuit.iden(q[0]) job = execute(circuit, backend_statevector) plot_bloch_multivector(job.result().get_statevector(circuit)) circuit = QuantumCircuit(q, c) circuit.ry(π/2, q[0]) circuit.measure(q, c) job = execute(circuit, backend, shots=100) plot_histogram(job.result().get_counts(circuit)) circuit = QuantumCircuit(q, c) circuit.ry(π/2, q[0]) job = execute(circuit, backend_statevector) plot_bloch_multivector(job.result().get_statevector(circuit)) circuit = QuantumCircuit(q, c) circuit.x(q[0]) circuit.ry(π/2, q[0]) job = execute(circuit, backend_statevector) plot_bloch_multivector(job.result().get_statevector(circuit)) circuit.measure(q, c) job = execute(circuit, backend, shots=100) plot_histogram(job.result().get_counts(circuit)) circuit = QuantumCircuit(q, c) circuit.ry(π/2, q[0]) circuit.ry(π/2, q[0]) circuit.measure(q, c) job = execute(circuit, backend, shots=100) plot_histogram(job.result().get_counts(circuit)) q0 = np.array([[1], [0]]) q1 = np.array([[1], [0]]) np.kron(q0, q1) q = QuantumRegister(2) c = ClassicalRegister(2) circuit = QuantumCircuit(q, c) circuit.h(q[0]) circuit.cx(q[0], q[1]) circuit.measure(q, c) job = execute(circuit, backend, shots=100) plot_histogram(job.result().get_counts(circuit))
https://github.com/abbarreto/qiskit3
abbarreto
pip install qiskit pip install qiskit-ignis import qiskit qiskit.IBMQ.save_account('17efde49764005e8eeb00dd065d44bc208778be72d44b475e508d20504818786f842988b0e506515c78debdd1b0c4b570717863db5e4f85569fb43c4c8626b8a', overwrite = True) qiskit.IBMQ.load_account() import numpy as np import math from qiskit import * nshots = 8192 IBMQ.load_account() #provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_quito') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter def coh_l1(rho): d = rho.shape[0]; C = 0 for j in range(0,d-1): for k in range(j+1,d): C += np.abs(rho[j,k]) return 2*C def predict_jb(rho): return abs(rho[0,0]-rho[1,1]) r00 = 2/3; r01 = 1.33/3; r10 = 1.33/3; r11 = 1/3 # initial state r = math.sqrt((r00-r11)**2 + abs(2*r01)**2) # raio de Bloch th = math.acos((r00-r11)/r) ph = math.acos(2*r01.real/(r*math.sin(th))) # angulos de Bloch r0 = (1+r)/2.; r1 = (1-r)/2. # autovetores print(r, th, ph, r0, r1) # simulation p = np.arange(0,1.1,0.1) d = len(p) Csim = np.zeros(d); Psim = np.zeros(d) for j in range(0,d): pI = (4-3*p[j])/4; pX = p[j]/4; pZ = p[j]/4; pY = p[j]/4 # depolarizing # sequencia: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 # = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Phi_ABCD = [math.sqrt(r0*pI)*math.cos(th/2), math.sqrt(r0*pX)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pZ)*math.cos(th/2), -1j*math.sqrt(r0*pY)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r1*pI)*math.sin(th/2), -math.sqrt(r1*pX)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pZ)*math.sin(th/2), 1j*math.sqrt(r1*pY)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r0*pI)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pX)*math.cos(th/2), -math.sqrt(r0*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), 1j*math.sqrt(r0*pY)*math.cos(th/2), -math.sqrt(r1*pI)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pX)*math.sin(th/2), math.sqrt(r1*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), 1j*math.sqrt(r1*pY)*math.sin(th/2)] qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.initialize(Phi_ABCD, [qr[0],qr[3],qr[2],qr[1]]) qstc = state_tomography_circuits(qc, [qr[1]]) job = qiskit.execute(qstc, backend = simulator, shots=nshots) qstf = StateTomographyFitter(job.result(), qstc) rho_sim = qstf.fit(method='lstsq') Csim[j] = coh_l1(rho_sim) Psim[j] = predict_jb(rho_sim) # theoretical pt = np.arange(0,1.01,0.01) Ct = (1-pt)*(2*1.33/3) Pt = (1-pt)*(1/3) # experiment p = np.arange(0,1.1,0.1); d = len(p) Cexp = np.zeros(d); Pexp = np.zeros(d) jobs_ids = [] for j in range(0,d): pI = (4-3*p[j])/4; pX = p[j]/4; pZ = p[j]/4; pY = p[j]/4 Phi_ABCD = [math.sqrt(r0*pI)*math.cos(th/2), math.sqrt(r0*pX)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pZ)*math.cos(th/2), -1j*math.sqrt(r0*pY)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r1*pI)*math.sin(th/2), -math.sqrt(r1*pX)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pZ)*math.sin(th/2), 1j*math.sqrt(r1*pY)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r0*pI)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pX)*math.cos(th/2), -math.sqrt(r0*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), 1j*math.sqrt(r0*pY)*math.cos(th/2), -math.sqrt(r1*pI)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pX)*math.sin(th/2), math.sqrt(r1*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), 1j*math.sqrt(r1*pY)*math.sin(th/2)] qr = QuantumRegister(4); qc = QuantumCircuit(qr) qc.initialize(Phi_ABCD, [qr[0],qr[3],qr[2],qr[1]]) qstc = state_tomography_circuits(qc, [qr[1]]) job = qiskit.execute(qstc, backend = device, shots=nshots) jobs_ids.append(job.job_id()) print(job.job_id()) job_monitor(job) qstf = StateTomographyFitter(job.result(), qstc) rho_exp = qstf.fit(method='lstsq') Cexp[j] = coh_l1(rho_exp) #Pexp[j] = predict_jb(rho_exp) # sem mitigacao, chip quito, qr[1] import matplotlib from matplotlib import pyplot as plt matplotlib.rcParams.update({'font.size':12}) plt.figure(figsize = (6,4), dpi = 100) plt.plot(pt,Ct,label=r'$C_{l_1}^{the}$') #plt.plot(pt,Pt,label=r'$P_{jb}^{the}$') plt.plot(p,Csim,'*',label=r'$C_{l_1}^{sim}$') #plt.plot(p,Psim,'o',label=r'$P_{jb}^{sim}$') plt.plot(p,Cexp,'^',label=r'$C_{l_1}^{exp}$') #plt.plot(p,Pexp,'+',label=r'$P_{jb}^{exp}$') plt.xlabel(r'$p$') plt.legend() plt.show() # sem mitigacao, chip belem # sem mitigacao, chip manila # sem mitigacao, chip quito, qr[0] f = open("jobs_ids_CS_rho.txt", "w") f.write(str(jobs_ids)) f.close() f = open("jobs_ids_CS_rho.txt","r") list_ids = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() print(list_ids) # error mitigation qr = QuantumRegister(4); qubit_list = [1] meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = qiskit.execute(meas_calibs, backend = device, shots = nshots) print(job.job_id()) job_monitor(job) job = device.retrieve_job('63a124fa05888e2fcb99ab6e') meas_fitter = CompleteMeasFitter(job.result(), state_labels) p = np.arange(0,1.1,0.1); d = len(p) Cexp = np.zeros(d); Pexp = np.zeros(d) for j in range(0,d): job = device.retrieve_job(list_ids[j]) mitigated_results = meas_fitter.filter.apply(job.result()) qstf_exp = StateTomographyFitter(mitigated_results, qstc) rho_exp = qstf_exp.fit(method='lstsq') Cexp[j] = coh_l1(rho_exp) Pexp[j] = predict_jb(rho_exp) # com mitigacao, chip quito, qr[1] import matplotlib from matplotlib import pyplot as plt matplotlib.rcParams.update({'font.size':12}) plt.figure(figsize = (6,4), dpi = 100) plt.plot(pt,Ct,label=r'$C_{l_1}^{the}$')#,color='green') plt.plot(p,Csim,'o',label=r'$C_{l_1}^{sim}$')#,color='blue') plt.plot(p,Cexp,'*',label=r'$C_{l_1}^{exp}$')#,color='orange') #plt.plot(pt,Pt,label=r'$P_{jb}^{the}$') #plt.plot(p,Psim,'o',label=r'$P_{jb}^{sim}$') #plt.plot(p,Pexp,'+',label=r'$P_{jb}^{exp}$') plt.xlabel(r'$p$') plt.legend() plt.savefig('fig_QCS_mixed.pdf') plt.show() # com mitigacao, chip belem # com mitigacao, chip manila # com mitigacao, chip quito, qr[0] # com mitigacao, chip quito # sem mitigacao, chip quito
https://github.com/theflyingrahul/qiskitsummerschool2020
theflyingrahul
#!/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
# You can set a color for all the bars. from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.mappers import ParityMapper from qiskit_nature.second_q.properties import ParticleNumber from qiskit_nature.second_q.transformers import ActiveSpaceTransformer bond_distance = 2.5 # in Angstrom # specify driver driver = PySCFDriver( atom=f"Li 0 0 0; H 0 0 {bond_distance}", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() # specify active space transformation active_space_trafo = ActiveSpaceTransformer( num_electrons=problem.num_particles, num_spatial_orbitals=3 ) # transform the electronic structure problem problem = active_space_trafo.transform(problem) # construct the parity mapper with 2-qubit reduction qubit_mapper = ParityMapper(num_particles=problem.num_particles) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms.ground_state_solvers import GroundStateEigensolver np_solver = NumPyMinimumEigensolver() np_groundstate_solver = GroundStateEigensolver(qubit_mapper, np_solver) np_result = np_groundstate_solver.solve(problem) target_energy = np_result.total_energies[0] print(np_result) from qiskit.circuit.library import EfficientSU2 ansatz = EfficientSU2(num_qubits=4, reps=1, entanglement="linear", insert_barriers=True) ansatz.decompose().draw("mpl", style="iqx") import numpy as np from qiskit.utils import algorithm_globals # fix random seeds for reproducibility np.random.seed(5) algorithm_globals.random_seed = 5 from qiskit.algorithms.optimizers import SPSA optimizer = SPSA(maxiter=100) initial_point = np.random.random(ansatz.num_parameters) from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.primitives import Estimator estimator = Estimator() local_vqe = VQE( estimator, ansatz, optimizer, initial_point=initial_point, ) local_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, local_vqe) local_vqe_result = local_vqe_groundstate_solver.solve(problem) print(local_vqe_result) from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(group="open") # replace by your runtime provider backend = provider.get_backend("ibmq_qasm_simulator") # select a backend that supports the runtime from qiskit_nature.runtime import VQEClient runtime_vqe = VQEClient( ansatz=ansatz, optimizer=optimizer, initial_point=initial_point, provider=provider, backend=backend, shots=1024, measurement_error_mitigation=True, ) # use a complete measurement fitter for error mitigation runtime_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, runtime_vqe) runtime_vqe_result = runtime_vqe_groundstate_solver.solve(problem) print(runtime_vqe_result) runtime_result = runtime_vqe_result.raw_result history = runtime_result.optimizer_history loss = history["energy"] import matplotlib.pyplot as plt plt.rcParams["font.size"] = 14 # plot loss and reference value plt.figure(figsize=(12, 6)) plt.plot(loss + runtime_vqe_result.nuclear_repulsion_energy, label="Runtime VQE") plt.axhline(y=target_energy + 0.2, color="tab:red", ls=":", label="Target + 200mH") plt.axhline(y=target_energy, color="tab:red", ls="--", label="Target") plt.legend(loc="best") plt.xlabel("Iteration") plt.ylabel("Energy [H]") plt.title("VQE energy"); import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
import sympy from sympy import * import numpy as np from numpy import random import math import scipy init_printing(use_unicode=True) from matplotlib import pyplot as plt %matplotlib inline from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum import TensorProduct as tp from mpmath import factorial as fact import io import base64 #from IPython.core.display import display, HTML, clear_output from IPython import * from ipywidgets import interactive, interact, fixed, interact_manual, widgets import csv import importlib import scipy.interpolate from mpl_toolkits.mplot3d import Axes3D, proj3d from itertools import product, combinations from matplotlib.patches import FancyArrowPatch from matplotlib import cm, colors from sympy.functions.special.tensor_functions import KroneckerDelta from scipy.linalg import polar, lapack import mpmath # constantes físicas e = 1.60217662*10**-19 # C (carga elementar) k = 8.9875517923*10**9 # Nm^2/C^2 (constante de Coulomb) eps0 = 8.8541878128*10**-12 #F/m (permissividade do vácuo) mu0 = 1.25663706212*10**-6 # N/A^2 (permeabilidade do vácuo) h = 6.626069*10**-34 # Js (constante de Planck) heV = h/e # em eV hb = h/(2*math.pi) # hbar hbeV = hb/e # em eV c = 2.99792458*10**8 # m/s (velocidade da luz no vácuo) G = 6.6742*10**-11 # Nm^2/kg^2 (constante gravitacional) kB = 1.38065*10**-23 # J/K (constante de Boltzmann) me = 9.109382*10**-31 # kg (massa do elétron) mp = 1.6726219*10**-27 # kg (massa do próton) mn = 1.67492749804*10**-27 # kg (massa do nêutron) mT = 5.9722*10**24 # kg (massa da Terra) mS = 1.98847*10**30 # kg (massa do Sol) u = 1.660538921*10**-27 # kg (unidade de massa atômica) dTS = 1.496*10**11 # m (distância Terra-Sol) rT = 6.3781*10**6 # m (raio da Terra) sSB = 5.670374419*10**-8 # W⋅m−2⋅K−4 (constante de Stefan-Boltzmann) Ri = 10973734.848575922 # m^-1 (constante de Rydberg) al = (k*e**2)/(hb*c) # ~1/137.035999084 (constante de estrutura fina) a0=(hb**2)/(me*k*e**2) # ~ 0.52917710^-10 m (raio de Bohr) ge = 2 # (fator giromagnetico do eletron) gp = 5.58 # (fator giromagnetico do proton) def id(n): '''retorna a matriz identidade nxn''' id = zeros(n,n) for j in range(0,n): id[j,j] = 1 return id #id(2) def pauli(j): '''retorna as matrizes de Pauli''' if j == 1: return Matrix([[0,1],[1,0]]) elif j == 2: return Matrix([[0,-1j],[1j,0]]) elif j == 3: return Matrix([[1,0],[0,-1]]) #pauli(1), pauli(2), pauli(3) def tr(A): '''retorna o traço de uma matriz''' d = A.shape[0] tr = 0 for j in range(0,d): tr += A[j,j] return tr #tr(pauli(1)) def comm(A,B): '''retorna a função comutador''' return A*B-B*A #comm(pauli(1),pauli(2)) def acomm(A,B): '''retorna a função anti-comutador''' return A*B+B*A #acomm(pauli(1),pauli(2)) def cb(n,j): '''retorna um vetor da base padrão de C^n''' vec = zeros(n,1) vec[j] = 1 return vec #cb(2,0) def proj(psi): '''retorna o projeto no vetor psi''' d = psi.shape[0] P = zeros(d,d) for j in range(0,d): for k in range(0,d): P[j,k] = psi[j]*conjugate(psi[k]) return P #proj(cb(2,0)) def bell(j,k): if j == 0 and k == 0: return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))+tp(cb(2,1),cb(2,1))) elif j == 0 and k == 1: return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))+tp(cb(2,1),cb(2,0))) elif j == 1 and k == 0: return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))-tp(cb(2,1),cb(2,0))) elif j == 1 and k == 1: return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))-tp(cb(2,1),cb(2,1))) #bell(0,0), bell(0,1), bell(1,0), bell(1,1) def inner_product(v,w): d = len(v); ip = 0 for j in range(0,d): ip += conjugate(v[j])*w[j] return ip #a,b,c,d = symbols("a b c d"); v = [b,a]; w = [c,d]; inner_product(v,w) def norm(v): d = len(v) return sqrt(inner_product(v,v)) #v = [2,2]; norm(v) def tp(x,y): return tensorproduct(x,y) A = tp(pauli(3),pauli(1)); A
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests PassManagerConfig""" from qiskit import QuantumRegister from qiskit.providers.backend import Backend from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeMelbourne, FakeArmonk, FakeHanoi, FakeHanoiV2 from qiskit.providers.basicaer import QasmSimulatorPy from qiskit.transpiler.coupling import CouplingMap from qiskit.transpiler.passmanager_config import PassManagerConfig class TestPassManagerConfig(QiskitTestCase): """Test PassManagerConfig.from_backend().""" def test_config_from_backend(self): """Test from_backend() with a valid backend. `FakeHanoi` is used in this testcase. This backend has `defaults` attribute that contains an instruction schedule map. """ backend = FakeHanoi() config = PassManagerConfig.from_backend(backend) self.assertEqual(config.basis_gates, backend.configuration().basis_gates) self.assertEqual(config.inst_map, backend.defaults().instruction_schedule_map) self.assertEqual( str(config.coupling_map), str(CouplingMap(backend.configuration().coupling_map)) ) def test_config_from_backend_v2(self): """Test from_backend() with a BackendV2 instance.""" backend = FakeHanoiV2() config = PassManagerConfig.from_backend(backend) self.assertEqual(config.basis_gates, backend.operation_names) self.assertEqual(config.inst_map, backend.instruction_schedule_map) self.assertEqual(config.coupling_map.get_edges(), backend.coupling_map.get_edges()) def test_invalid_backend(self): """Test from_backend() with an invalid backend.""" with self.assertRaises(AttributeError): PassManagerConfig.from_backend(Backend()) def test_from_backend_and_user(self): """Test from_backend() with a backend and user options. `FakeMelbourne` is used in this testcase. This backend does not have `defaults` attribute and thus not provide an instruction schedule map. """ qr = QuantumRegister(4, "qr") initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] backend = FakeMelbourne() config = PassManagerConfig.from_backend( backend, basis_gates=["user_gate"], initial_layout=initial_layout ) self.assertEqual(config.basis_gates, ["user_gate"]) self.assertNotEqual(config.basis_gates, backend.configuration().basis_gates) self.assertIsNone(config.inst_map) self.assertEqual( str(config.coupling_map), str(CouplingMap(backend.configuration().coupling_map)) ) self.assertEqual(config.initial_layout, initial_layout) def test_from_backendv1_inst_map_is_none(self): """Test that from_backend() works with backend that has defaults defined as None.""" backend = FakeHanoi() backend.defaults = lambda: None config = PassManagerConfig.from_backend(backend) self.assertIsInstance(config, PassManagerConfig) self.assertIsNone(config.inst_map) def test_simulator_backend_v1(self): """Test that from_backend() works with backendv1 simulator.""" backend = QasmSimulatorPy() config = PassManagerConfig.from_backend(backend) self.assertIsInstance(config, PassManagerConfig) self.assertIsNone(config.inst_map) self.assertIsNone(config.coupling_map) def test_invalid_user_option(self): """Test from_backend() with an invalid user option.""" with self.assertRaises(TypeError): PassManagerConfig.from_backend(FakeMelbourne(), invalid_option=None) def test_str(self): """Test string output.""" pm_config = PassManagerConfig.from_backend(FakeArmonk()) # For testing remove instruction schedule map it's str output is non-deterministic # based on hash seed pm_config.inst_map = None str_out = str(pm_config) expected = """Pass Manager Config: initial_layout: None basis_gates: ['id', 'rz', 'sx', 'x'] inst_map: None coupling_map: None layout_method: None routing_method: None translation_method: None scheduling_method: None instruction_durations: id(0,): 7.111111111111111e-08 s rz(0,): 0.0 s sx(0,): 7.111111111111111e-08 s x(0,): 7.111111111111111e-08 s measure(0,): 4.977777777777777e-06 s backend_properties: {'backend_name': 'ibmq_armonk', 'backend_version': '2.4.3', 'gates': [{'gate': 'id', 'name': 'id0', 'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)), 'name': 'gate_error', 'unit': '', 'value': 0.00019769550670970334}, {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'name': 'gate_length', 'unit': 'ns', 'value': 71.11111111111111}], 'qubits': [0]}, {'gate': 'rz', 'name': 'rz0', 'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'name': 'gate_error', 'unit': '', 'value': 0}, {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'name': 'gate_length', 'unit': 'ns', 'value': 0}], 'qubits': [0]}, {'gate': 'sx', 'name': 'sx0', 'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)), 'name': 'gate_error', 'unit': '', 'value': 0.00019769550670970334}, {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'name': 'gate_length', 'unit': 'ns', 'value': 71.11111111111111}], 'qubits': [0]}, {'gate': 'x', 'name': 'x0', 'parameters': [{'date': datetime.datetime(2021, 3, 15, 0, 38, 15, tzinfo=tzoffset(None, -14400)), 'name': 'gate_error', 'unit': '', 'value': 0.00019769550670970334}, {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'name': 'gate_length', 'unit': 'ns', 'value': 71.11111111111111}], 'qubits': [0]}], 'general': [], 'last_update_date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'qubits': [[{'date': datetime.datetime(2021, 3, 15, 0, 36, 17, tzinfo=tzoffset(None, -14400)), 'name': 'T1', 'unit': 'us', 'value': 182.6611165336624}, {'date': datetime.datetime(2021, 3, 14, 0, 33, 45, tzinfo=tzoffset(None, -18000)), 'name': 'T2', 'unit': 'us', 'value': 237.8589220110257}, {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'name': 'frequency', 'unit': 'GHz', 'value': 4.971852852405576}, {'date': datetime.datetime(2021, 3, 15, 0, 40, 24, tzinfo=tzoffset(None, -14400)), 'name': 'anharmonicity', 'unit': 'GHz', 'value': -0.34719293148282626}, {'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)), 'name': 'readout_error', 'unit': '', 'value': 0.02400000000000002}, {'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)), 'name': 'prob_meas0_prep1', 'unit': '', 'value': 0.0234}, {'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)), 'name': 'prob_meas1_prep0', 'unit': '', 'value': 0.024599999999999955}, {'date': datetime.datetime(2021, 3, 15, 0, 35, 20, tzinfo=tzoffset(None, -14400)), 'name': 'readout_length', 'unit': 'ns', 'value': 4977.777777777777}]]} approximation_degree: None seed_transpiler: None timing_constraints: None unitary_synthesis_method: default unitary_synthesis_plugin_config: None target: None """ self.assertEqual(str_out, expected)
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
Sanjay-995
import qiskit qiskit.__version__ qiskit.__qiskit_version__ #Import the required packages from qiskit import QuantumCircuit, QuantumRegister,ClassicalRegister,Aer,execute from qiskit.visualization import * qc1=QuantumCircuit(3) ## also comment the 2 NOT gates on qubit 0 and 1 and check the third qubit qc1.x(0) qc1.x(1) qc1.ccx(0,1,2) qc1.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc1,backend) result=job.result() sv=result.get_statevector() sv.draw(output="latex") # We create 3-qubit mct gate # We have a list of control qubits :0,1 and a target qubit 2. qc2=QuantumCircuit(3) ## also comment the 2 NOT gates on qubit 0 and 1 and check the third qubit qc2.x(0) qc2.x(1) qc2.mct([0,1],2) qc2.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc2,backend) result=job.result() sv=result.get_statevector() sv.draw(output="latex") # We simply create a user-defined object cx from CXGate class # Another way of accessing a CX or NOT gate from qiskit.circuit.library import CXGate qc3=QuantumCircuit(3) cx=CXGate() qc3.append(cx,[0,1]) qc3.draw('mpl') from qiskit.circuit.library import CXGate qc4=QuantumCircuit(3) ccx=CXGate().control() qc4.append(ccx,[0,1,2]) qc4.draw('mpl') from math import pi qc5=QuantumCircuit(2) qc5.cry(pi/2,0,1) qc5.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc5,backend) result=job.result() sv=result.get_statevector() sv.draw(output="latex") #Let's apply a X on the control qubit qc6=QuantumCircuit(2) qc6.x(0) qc6.cry(pi/2,0,1) qc6.draw('mpl') backend=Aer.get_backend('statevector_simulator') job=execute(qc6,backend) result=job.result() sv=result.get_statevector() print("statevector:", sv) sv.draw(output="latex")
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
from qiskit import QuantumCircuit, IBMQ, Aer def qc_ezz(t): qc = QuantumCircuit(2, name = 'e^(-itZZ)') qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1) return qc def qc_exx(t): qc = QuantumCircuit(2, name = 'e^(-itXX)') qc.h([0,1]); qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1); qc.h([0,1]) return qc def qc_eyy(t): qc = QuantumCircuit(2, name = 'e^(-itYY)') qc.sdg([0,1]); qc.h([0,1]); qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1); qc.h([0,1]); qc.s([0,1]) return qc def qc_Bj(t): qc = QuantumCircuit(3, name = 'B_j') qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t) qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2]) qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1]) return qc nshots = 8192 IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') #provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main') device = provider.get_backend('ibmq_jakarta') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.tools.monitor import backend_overview, backend_monitor def qc_psi0(): qc = QuantumCircuit(3, name = 'psi0') qc.x([0,1]) return qc import numpy as np ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1 psi0_ = np.kron(ket1, np.kron(ket1, ket0)); psi0__ = np.kron(ket0, np.kron(ket1, ket1)) # para calcular a fidelidade com o estado da tomografia psi0_.T, psi0__.T import scipy I = np.array([[1,0],[0,1]]); X = np.array([[0,1],[1,0]]); Y = np.array([[0,-1j],[1j,0]]); Z = np.array([[1,0],[0,-1]]) H2 = np.kron(X, X) + np.kron(Y, Y) + np.kron(Z, Z) def UHxxx12_num(t): H = np.kron(H2, I) return scipy.linalg.expm(-1j*t*H) def UHxxx23_num(t): H = np.kron(I, H2) return scipy.linalg.expm(-1j*t*H) #U = UHxxx23_num(math.pi); print(U.shape[0]) from qiskit import quantum_info, execute from qiskit.tools.monitor import job_monitor from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute, IBMQ qr = QuantumRegister(7) qubit_list = [5, 3, 1] # os qubits para os quais aplicaremos calibracao de medidas meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = execute(meas_calibs, backend = device, shots = nshots) job_monitor(job) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels) t = math.pi for j in range(0, 8): # muda o No. de passos de Trotter # teórico U12 = UHxxx12_num(t/(j+1)); U23 = UHxxx23_num(t/(j+1)) B = np.dot(U12, U23); U = np.linalg.matrix_power(B, j+1); psit = np.dot(U, psi0_) F_teo = quantum_info.state_fidelity(psi0_, psit) # circuit q qc = QuantumCircuit(7) qc.x([5, 3]) # initial state qc_Bj_ = qc_Bj(t/(j+1)) for k in range(0, j+1): qc.append(qc_Bj_, [5, 3, 1]) qstc = state_tomography_circuits(qc, [5, 3, 1]) # simulação job_sim = execute(qstc, backend = simulator, shots = nshots) qstf_sim = StateTomographyFitter(job_sim.result(), qstc) rho_sim = qstf_sim.fit(method = 'lstsq') F_sim = quantum_info.state_fidelity(psi0__, rho_sim) # experimento job_exp = execute(qstc, backend = device, shots = nshots) job_monitor(job_exp) mitigated_results = meas_fitter.filter.apply(job_exp.result()) qstf_exp = StateTomographyFitter(mitigated_results, qstc) rho_exp = qstf_exp.fit(method = 'lstsq') F_exp = quantum_info.state_fidelity(psi0__, rho_exp) print('No. passos=', j+1, ',F_teo=', F_teo, ',F_sim=', F_sim, ',F_exp=', F_exp)
https://github.com/ukzncqt/QC_Tuts
ukzncqt
!pip install qiskit import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.x(q[0]) qc.barrier(q) qc.measure(q,c) qc.draw() from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1024) res = job.result() res.get_counts() q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) qc.h(q[0]) qc.barrier(q) qc.measure(q,c) qc.draw() job=execute(qc,backend,shots=1024) res=job.result() res.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(res.get_counts()) q = QuantumRegister(1) qc = QuantumCircuit(q) qc.x(q[0]) qc.h(q[0]) qc.draw() backend = BasicAer.get_backend('statevector_simulator') job = execute(qc,backend) res = job.result() vector = res.get_statevector(qc,decimals=3) print(vector) from sympy import Matrix , pprint pprint(Matrix(vector)) from qiskit.tools.visualization import plot_bloch_vector qc1 = QuantumCircuit(q) qc1.iden(q[0]) job = execute(qc1,backend) res =job.result() vector = res.get_statevector(qc1,decimals=3) print(vector) p = np.outer(vector,vector.conj()) px = np.array([[0,1],[1,0]]) py = np.array([[0,-1j],[1j,0]]) pz = np.array([[1,0],[0,-1]]) x = float(np.trace(np.dot(px,p))) y = float(np.trace(np.dot(py,p))) z = float(np.trace(np.dot(pz,p))) vec=[x,y,z] plot_bloch_vector(vec) qc1 = QuantumCircuit(q) qc1.x(q[0]) job = execute(qc1,backend) res = job.result() vector = res.get_statevector(qc1,decimals=3) print(vector) p = np.outer(vector,vector.conj()) x = float(np.trace(np.dot(px,p))) y = float(np.trace(np.dot(py,p))) z = float(np.trace(np.dot(pz,p))) vec = [x,y,z] plot_bloch_vector(vec) qc1 = QuantumCircuit(q) qc1.h(q[0]) job = execute(qc1,backend) res = job.result() vector = res.get_statevector(qc1,decimals=3) print(vector) p = np.outer(vector,vector.conj()) x = float(np.trace(np.dot(px,p))) y = float(np.trace(np.dot(py,p))) z = float(np.trace(np.dot(pz,p))) vec = [x,y,z] plot_bloch_vector(vec) qc1 = QuantumCircuit(q) qc1.h(q[0]) qc1.y(q[0]) job = execute(qc1,backend) res = job.result() vector = res.get_statevector(qc1,decimals=3) print(vector) p = np.outer(vector,vector.conj()) x = float(np.trace(np.dot(px,p))) y = float(np.trace(np.dot(py,p))) z = float(np.trace(np.dot(pz,p))) vec = [x,y,z] plot_bloch_vector(vec) qc1=QuantumCircuit(q) qc1.h(q[0]) qc1.z(q[0]) job=execute(qc1,backend) res=job.result() vector = res.get_statevector(qc1,decimals=3) print(vector) p=np.outer(vector,vector.conj()) x=float(np.trace(np.dot(px,p))) y=float(np.trace(np.dot(py,p))) z=float(np.trace(np.dot(pz,p))) vec=[x,y,z] plot_bloch_vector(vec) qc1 = QuantumCircuit(q) qc1.h(q[0]) qc1.t(q[0]) job = execute(qc1,backend) res = job.result() vector = res.get_statevector(qc1,decimals=3) print(vector) p = np.outer(vector,vector.conj()) x = float(np.trace(np.dot(px,p))) y = float(np.trace(np.dot(py,p))) z = float(np.trace(np.dot(pz,p))) vec = [x,y,z] plot_bloch_vector(vec) qc1 = QuantumCircuit(q) qc1.h(q[0]) qc1.tdg(q[0]) job = execute(qc1,backend) res = job.result() vector = res.get_statevector(qc1,decimals=3) print(vector) p = np.outer(vector,vector.conj()) x = float(np.trace(np.dot(px,p))) y = float(np.trace(np.dot(py,p))) z = float(np.trace(np.dot(pz,p))) vec = [x,y,z] plot_bloch_vector(vec) qc1 = QuantumCircuit(q) qc1.h(q[0]) qc1.s(q[0]) job = execute(qc1,backend) res = job.result() vector = res.get_statevector(qc1,decimals=3) print(vector) p = np.outer(vector,vector.conj()) x = float(np.trace(np.dot(px,p))) y = float(np.trace(np.dot(py,p))) z = float(np.trace(np.dot(pz,p))) vec = [x,y,z] plot_bloch_vector(vec) qc1 = QuantumCircuit(q) qc1.h(q[0]) qc1.sdg(q[0]) job = execute(qc1,backend) res = job.result() vector = res.get_statevector(qc1,decimals=3) print(vector) p = np.outer(vector,vector.conj()) x = float(np.trace(np.dot(px,p))) y = float(np.trace(np.dot(py,p))) z = float(np.trace(np.dot(pz,p))) vec = [x,y,z] plot_bloch_vector(vec) qc1 = QuantumCircuit(q) qc1.u3(np.pi/7,5*np.pi/14,np.pi/8,q[0]) job = execute(qc1,backend) res = job.result() vector = res.get_statevector(qc1,decimals=3) print(vector) pprint(Matrix(vector)) p = np.outer(vector,vector.conj()) x = float(np.trace(np.dot(px,p))) y = float(np.trace(np.dot(py,p))) z = float(np.trace(np.dot(pz,p))) vec = [x,y,z] plot_bloch_vector(vec) q = QuantumRegister(2) qc1 = QuantumCircuit(q) qc1.h(q[0]) qc1.cx(q[0],q[1]) qc1.draw() job = execute(qc1,backend) res = job.result() vector = res.get_statevector(qc1,decimals=3) print(vector) pprint(Matrix(vector)) q = QuantumRegister(2) c = ClassicalRegister(2) qc1 = QuantumCircuit(q,c) qc1.h(q[0]) qc1.cx(q[0],q[1]) qc1.barrier(q) qc1.measure(q,c) from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') job = execute(qc1,backend,shots=1000) res = job.result() counts = res.get_counts() print(counts) plot_histogram(counts) q = QuantumRegister(2) qc = QuantumCircuit(q) qc.ch(q[0],q[1]) qc.draw() q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cy(q[0],q[1]) qc.draw() q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cz(q[0],q[1]) qc.draw() q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cu3(np.pi/3,np.pi/4,np.pi,q[0],q[1]) qc.draw() q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q,c) qc.h(q[0]) qc.cx(q[0],q[1]) qc.cx(q[0],q[2]) qc.barrier(q) qc.measure(q,c) qc.draw() backend = BasicAer.get_backend('qasm_simulator') job = execute(qc,backend,shots=1000) res = job.result() res.get_counts() plot_histogram(res.get_counts()) backend=BasicAer.get_backend('statevector_simulator') job=execute(qc,backend) res=job.result() v=res.get_statevector(qc,decimals=3) pprint(Matrix(v))
https://github.com/kdk/qiskit-timeline-debugger
kdk
from qiskit import QuantumCircuit, transpile, __qiskit_version__ from qiskit.providers import BaseBackend from qiskit.providers.backend import Backend from qiskit.transpiler.basepasses import AnalysisPass, TransformationPass from typing import Optional, Union import logging import warnings from IPython.display import display from qiskit_trebugger.model import TranspilerLoggingHandler from qiskit_trebugger.model import TranspilerDataCollector from qiskit_trebugger.model import TranspilationSequence from qiskit_trebugger.views.widget.timeline_view import TimelineView from .debugger_error import DebuggerError class Debugger: @classmethod def debug( cls, circuit: QuantumCircuit, backend: Optional[Union[Backend, BaseBackend]] = None, optimization_level: Optional[int] = None, **kwargs ): if not isinstance(circuit, QuantumCircuit): raise DebuggerError( "Debugger currently supports single QuantumCircuit only!" ) # Create the view: view = TimelineView() def on_step_callback(step): view.add_step(step) # Prepare the model: transpilation_sequence = TranspilationSequence(on_step_callback) warnings.simplefilter("ignore") transpilation_sequence.general_info = { "Backend": backend.name(), "optimization_level": optimization_level, "Qiskit version": __qiskit_version__["qiskit"], "Terra version": __qiskit_version__["qiskit-terra"], } transpilation_sequence.original_circuit = circuit warnings.simplefilter("default") Debugger._register_logging_handler(transpilation_sequence) transpiler_callback = Debugger._get_data_collector(transpilation_sequence) # Pass the model to the view: view.transpilation_sequence = transpilation_sequence view.update_params(**kwargs) display(view) transpile( circuit, backend, optimization_level=optimization_level, callback=transpiler_callback, **kwargs ) view.update_summary() view.add_class("done") @classmethod def _register_logging_handler(cls, transpilation_sequence): # TODO: Do not depend on loggerDict all_loggers = logging.Logger.manager.loggerDict passes_loggers = { key: value for (key, value) in all_loggers.items() if key.startswith("qiskit.transpiler.passes.") } loggers_map = {} for _pass in AnalysisPass.__subclasses__(): if _pass.__module__ in passes_loggers.keys(): loggers_map[_pass.__module__] = _pass.__name__ for _pass in TransformationPass.__subclasses__(): if _pass.__module__ in passes_loggers.keys(): loggers_map[_pass.__module__] = _pass.__name__ handler = TranspilerLoggingHandler( transpilation_sequence=transpilation_sequence, loggers_map=loggers_map ) logger = logging.getLogger("qiskit.transpiler.passes") logger.setLevel(logging.DEBUG) logger.addHandler(handler) @classmethod def _get_data_collector(cls, transpilation_sequence): return TranspilerDataCollector(transpilation_sequence).transpiler_callback
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/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumCircuit qc = QuantumCircuit(12) qc.cx(0, 1) qc.cx(2, 3) qc.cx(4, 5) qc.cx(6, 7) qc.cx(8, 9) qc.cx(10, 11) qc.cx(11, 10) qc.cx(10, 11) qc.draw("mpl")
https://github.com/bibscore/qiskit_kindergarten
bibscore
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer from qiskit import QuantumCircuit, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 # Constant Oracle const_oracle = QuantumCircuit(n+1) # Random output output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() # Balanced Oracle balanced_oracle = QuantumCircuit(n+1) # Binary string length b_str = "101" # For each qubit in our circuit # we place an X-gate if the corresponding digit in b_str is 1 # or do nothing if the digit is 0 balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() # Creating the controlled-NOT gates # using each input qubit as a control # and the output as a target balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Wrapping the controls in X-gates # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw() # Viewing the output # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(dj_circuit).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018, 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. # pylint: disable=invalid-name """ Visualization function for DAG circuit representation. """ from rustworkx.visualization import graphviz_draw from qiskit.dagcircuit.dagnode import DAGOpNode, DAGInNode, DAGOutNode from qiskit.circuit import Qubit from qiskit.utils import optionals as _optionals from qiskit.exceptions import InvalidFileError from .exceptions import VisualizationError @_optionals.HAS_GRAPHVIZ.require_in_call def dag_drawer(dag, scale=0.7, filename=None, style="color"): """Plot the directed acyclic graph (dag) to represent operation dependencies in a quantum circuit. This function calls the :func:`~rustworkx.visualization.graphviz_draw` function from the ``rustworkx`` package to draw the DAG. Args: dag (DAGCircuit): The dag to draw. scale (float): scaling factor filename (str): file path to save image to (format inferred from name) style (str): 'plain': B&W graph 'color' (default): color input/output/op nodes Returns: PIL.Image: if in Jupyter notebook and not saving to file, otherwise None. Raises: VisualizationError: when style is not recognized. InvalidFileError: when filename provided is not valid Example: .. plot:: :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.visualization import dag_drawer q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) dag_drawer(dag) """ # NOTE: use type str checking to avoid potential cyclical import # the two tradeoffs ere that it will not handle subclasses and it is # slower (which doesn't matter for a visualization function) type_str = str(type(dag)) if "DAGDependency" in type_str: graph_attrs = {"dpi": str(100 * scale)} def node_attr_func(node): if style == "plain": return {} if style == "color": n = {} n["label"] = str(node.node_id) + ": " + str(node.name) if node.name == "measure": n["color"] = "blue" n["style"] = "filled" n["fillcolor"] = "lightblue" if node.name == "barrier": n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "green" if getattr(node.op, "_directive", False): n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "red" if getattr(node.op, "condition", None): n["label"] = str(node.node_id) + ": " + str(node.name) + " (conditional)" n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "lightgreen" return n else: raise VisualizationError("Unrecognized style %s for the dag_drawer." % style) edge_attr_func = None else: register_bit_labels = { bit: f"{reg.name}[{idx}]" for reg in list(dag.qregs.values()) + list(dag.cregs.values()) for (idx, bit) in enumerate(reg) } graph_attrs = {"dpi": str(100 * scale)} def node_attr_func(node): if style == "plain": return {} if style == "color": n = {} if isinstance(node, DAGOpNode): n["label"] = node.name n["color"] = "blue" n["style"] = "filled" n["fillcolor"] = "lightblue" if isinstance(node, DAGInNode): if isinstance(node.wire, Qubit): label = register_bit_labels.get( node.wire, f"q_{dag.find_bit(node.wire).index}" ) else: label = register_bit_labels.get( node.wire, f"c_{dag.find_bit(node.wire).index}" ) n["label"] = label n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "green" if isinstance(node, DAGOutNode): if isinstance(node.wire, Qubit): label = register_bit_labels.get( node.wire, f"q[{dag.find_bit(node.wire).index}]" ) else: label = register_bit_labels.get( node.wire, f"c[{dag.find_bit(node.wire).index}]" ) n["label"] = label n["color"] = "black" n["style"] = "filled" n["fillcolor"] = "red" return n else: raise VisualizationError("Invalid style %s" % style) def edge_attr_func(edge): e = {} if isinstance(edge, Qubit): label = register_bit_labels.get(edge, f"q_{dag.find_bit(edge).index}") else: label = register_bit_labels.get(edge, f"c_{dag.find_bit(edge).index}") e["label"] = label return e image_type = None if filename: if "." not in filename: raise InvalidFileError("Parameter 'filename' must be in format 'name.extension'") image_type = filename.split(".")[-1] return graphviz_draw( dag._multi_graph, node_attr_func, edge_attr_func, graph_attrs, filename, image_type, )
https://github.com/Qiskit/feedback
Qiskit
import numpy as np from IPython.display import Latex from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector, schmidt_decomposition ζ = Statevector([1/np.sqrt(2),0,0,1/np.sqrt(2)]) ζ.draw('latex',prefix='|\\zeta\\rangle = ') ζ_sd = schmidt_decomposition(ζ,[0]) print(ζ_sd) for i, (s,u,v) in enumerate(ζ_sd): print('---') display(Latex(f"$$\\lambda_{i} = {s}$$")) display(u.draw('latex',prefix=f'|u_{i}\\rangle = ')) display(v.draw('latex',prefix=f'|v_{i}\\rangle = ')) w = Statevector([0,1/np.sqrt(3),1/np.sqrt(3),0,1/np.sqrt(3),0,0,0]) w.draw('latex',prefix='|w\\rangle = ') w_sd = schmidt_decomposition(w,[0,1]) for i, (s,u,v) in enumerate(w_sd): print('---') display(Latex(f"$$\\lambda_{i} = {s}$$")) display(u.draw('latex',prefix=f'|u_{i}\\rangle = ')) display(v.draw('latex',prefix=f'|v_{i}\\rangle = ')) Statevector(sum([suv[0]*np.kron(suv[1],suv[2]) for suv in w_sd])) χ = Statevector(np.array([1,0,0,0,1,0,0,0,1])*1/np.sqrt(3),dims=(3,3)) χ.draw('latex', prefix='|\\chi\\rangle = ',max_size=10) w_sd = schmidt_decomposition(χ,[0]) for i, (s,u,v) in enumerate(w_sd): print('---') display(Latex(f"$$\\lambda_{i} = {s}$$")) display(u.draw('latex',prefix=f'|u_{i}\\rangle = ')) display(v.draw('latex',prefix=f'|v_{i}\\rangle = ')) dims = (2,3,4) k = Statevector(np.arange(np.prod(dims)),dims=dims) k.draw('latex',max_size=24) k_sd = schmidt_decomposition(k,[0,2]) for i, (s,u,v) in enumerate(k_sd): print('---') display(Latex(f"$$\\lambda_{i} = {s}$$")) display(u.draw('latex',prefix=f'|u_{i}\\rangle = ')) display(v.draw('latex',prefix=f'|v_{i}\\rangle = ')) Statevector(sum([suv[0]*np.kron(suv[1],suv[2]) for suv in k_sd]),dims=dims).draw('latex',max_size=24) ξ = Statevector.from_label('++') ξ.draw('latex',prefix='|\\xi\\rangle = ') ξ_sd = schmidt_decomposition(ξ,[0]) for i, (s,u,v) in enumerate(ξ_sd): print('---') display(Latex(f"$$\\lambda_{i} = {np.round(s,6)}$$")) display(u.draw('latex',prefix=f'|u_{i}\\rangle = ')) display(v.draw('latex',prefix=f'|v_{i}\\rangle = ')) from schmidt_decomposition_local import schmidt_decomposition as sd_loc ξ_sd = sd_loc(ξ,[0]) for i, (s,u,v) in enumerate(ξ_sd): print('---') display(Latex(f"$$\\lambda_{i} = {np.round(s,6)}$$")) display(u.draw('latex',prefix=f'|u_{i}\\rangle = ')) display(v.draw('latex',prefix=f'|v_{i}\\rangle = '))
https://github.com/GabrielPontolillo/QiskitPBT
GabrielPontolillo
from typing import Sequence from qiskit import QuantumCircuit, transpile from qiskit.providers.basic_provider import BasicSimulator from qiskit.providers import Backend from QiskitPBT.property import Property from QiskitPBT.stats.assert_entangled import AssertEntangled from QiskitPBT.utils import HashableQuantumCircuit from QiskitPBT.stats.assertion import StatisticalAssertion, StandardAssertion, Assertion from QiskitPBT.stats.measurements import Measurements from QiskitPBT.stats.single_qubit_distributions.assert_equal import AssertEqual from QiskitPBT.stats.single_qubit_distributions.assert_different import AssertDifferent from QiskitPBT.stats.assert_most_frequent import AssertMostFrequent from QiskitPBT.stats.utils.corrections import holm_bonferroni_correction from QiskitPBT.stats.execution_optimizer import ExecutionOptimizer class StatisticalAnalysisCoordinator: def __init__(self, number_of_measurements=2000, family_wise_p_value=0.05) -> None: self.assertions_for_property: dict[Property, list[Assertion]] = {} self.results: dict[Property, bool] = {} self.number_of_measurements = number_of_measurements self.family_wise_p_value = family_wise_p_value self.circuits_executed = 0 # for statistics #Assertions def assert_equal(self, property: Property, qubits1: int | Sequence[int], circuit1: QuantumCircuit, qubits2: int | Sequence[int], circuit2: QuantumCircuit, basis = ["x", "y", "z"]): # parse qubits so that assert equals always gets sequences of qubits if not isinstance(qubits1, Sequence): qubits1 = (qubits1, ) if not isinstance(qubits2, Sequence): qubits2 = (qubits2, ) # hack to make circuits in assert equals be usable as dictionary keys (by ref) circ1 = circuit1.copy() circ1.__class__ = HashableQuantumCircuit circ2 = circuit2.copy() circ2.__class__ = HashableQuantumCircuit if property in self.assertions_for_property: self.assertions_for_property[property].append(AssertEqual(qubits1, circ1, qubits2, circ2, basis)) else: self.assertions_for_property[property] = [AssertEqual(qubits1, circ1, qubits2, circ2, basis)] def assert_different(self, property: Property, qubits1: int | Sequence[int], circuit1: QuantumCircuit, qubits2: int | Sequence[int], circuit2: QuantumCircuit, basis = ["x", "y", "z"]): # parse qubits so that assert equals always gets sequences of qubits if not isinstance(qubits1, Sequence): qubits1 = (qubits1, ) if not isinstance(qubits2, Sequence): qubits2 = (qubits2, ) # hack to make circuits in assert equals be usable as dictionary keys (by ref) circ1 = circuit1.copy() circ1.__class__ = HashableQuantumCircuit circ2 = circuit2.copy() circ2.__class__ = HashableQuantumCircuit if property in self.assertions_for_property: self.assertions_for_property[property].append(AssertDifferent(qubits1, circ1, qubits2, circ2, basis)) else: self.assertions_for_property[property] = [AssertDifferent(qubits1, circ1, qubits2, circ2, basis)] def assert_entangled(self, property: Property, qubits: Sequence[int], circuit: QuantumCircuit, basis = ["z"]): # parse qubits so that assert equals always gets sequences of qubits if not isinstance(qubits, Sequence): qubits = (qubits,) # hack to make circuits in assert equals be usable as dictionary keys (by ref) circ = circuit.copy() circ.__class__ = HashableQuantumCircuit if property in self.assertions_for_property: self.assertions_for_property[property].append(AssertEntangled(qubits, circ, basis)) else: self.assertions_for_property[property] = [AssertEntangled(qubits, circ, basis)] def assert_most_frequent(self, property: Property, qubits: int | Sequence[int], circuit: QuantumCircuit, states: str | Sequence[str], basis = ["z"]): # parse qubits so that assert equals always gets sequences of qubits / bitstrings if not isinstance(qubits, Sequence): qubits = (qubits,) if not isinstance(states, Sequence): marked_states = (states, ) # hack to make circuits in assert equals be usable as dictionary keys (by ref) circ = circuit.copy() circ.__class__ = HashableQuantumCircuit if property in self.assertions_for_property: self.assertions_for_property[property].append(AssertMostFrequent(qubits, circ, states, basis)) else: self.assertions_for_property[property] = [AssertMostFrequent(qubits, circ, states, basis)] # Entrypoint for analysis def perform_analysis(self, properties: list[Property], backend: Backend=BasicSimulator()) -> None: execution_optimizer = ExecutionOptimizer() # classical assertion failed dont run quantum for property in properties: if not property.classical_assertion_outcome: self.results[property] = False continue for assertion in self.assertions_for_property[property]: execution_optimizer.add_measurement_configuration(assertion.get_measurement_configuration()) measurements = self._perform_measurements(execution_optimizer, backend) p_values = {} for property in properties: if property.classical_assertion_outcome and property not in self.results: p_values[property] = {} for assertion in self.assertions_for_property[property]: if isinstance(assertion, StatisticalAssertion): p_value = assertion.calculate_p_values(measurements) p_values[property][assertion] = p_value elif not isinstance(assertion, Assertion): raise ValueError("Assertion must be a subclass of Assertion") # perform family wise error rate correction # Ideally, we need to sort all of the p-values from all assertions, then pass back the corrected alpha values to compare them to in a list # Only do Holm Bonferroni Correction if there are p_values to correct (preconditions pass) if p_values: expected_p_values = holm_bonferroni_correction(self.assertions_for_property, p_values, self.family_wise_p_value) # calculate the outcome of each assertion for property in properties: if property not in self.results: self.results[property] = True for assertion in self.assertions_for_property[property]: if isinstance(assertion, StandardAssertion): self.results[property] = (self.results[property] and assertion.calculate_outcome(measurements)) elif isinstance(assertion, StatisticalAssertion): self.results[property] = (self.results[property] and assertion.calculate_outcome(p_values[property][assertion], expected_p_values[property][assertion])) else: raise ValueError("The provided assertions must be a subclass of Assertion") # creates a dictionary of measurements for each assertion, def _perform_measurements(self, execution_optimizer: ExecutionOptimizer, backend: Backend) -> dict[StatisticalAssertion, Measurements]: measurements = Measurements() for circuit in execution_optimizer.get_circuits_to_execute(): # TODO: get counts actually returns (or used to) unparsed bit strings, so if there are 2 quantum registers there is a space in there - this may need some attention # this is necessary for measure to work counts = backend.run(transpile(circuit, backend), shots=self.number_of_measurements).result().get_counts() self.circuits_executed += 1 # get the original circuit, as well as basis measurements, and what assertions it is linked to for measurement_name, original_circuit in execution_optimizer.get_measurement_info(circuit): measurements.add_measurement(original_circuit, measurement_name, counts) return measurements
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
"""The following is python code utilizing the qiskit library that can be run on extant quantum hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding, for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1, results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>). To find the factor, use the equivalence a^r mod 15. From this: (a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15 Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients, gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15, so the result of running shors algorithm to find the prime factors of an integer using quantum hardware are demonstrated. Note, this is not the same as the technical implementation of shor's algorithm described in this section for breaking the discrete log hardness assumption, though the proof of concept remains.""" # Import libraries from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from numpy import pi from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram # Initialize qubit registers qreg_q = QuantumRegister(5, 'q') creg_c = ClassicalRegister(5, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.reset(qreg_q[3]) circuit.reset(qreg_q[4]) # Apply Hadamard transformations to qubit registers circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) # Apply first QFT, modular exponentiation, and another QFT circuit.h(qreg_q[1]) circuit.cx(qreg_q[2], qreg_q[3]) circuit.crx(pi/2, qreg_q[0], qreg_q[1]) circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run the circuit on available quantum hardware and plot histogram from qiskit.tools.monitor import job_monitor job = execute(circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(circuit) plot_histogram(answer) #largest amplitude results correspond with r values used to find the prime factor of N.
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/AbeerVaishnav13/Quantum-Programs
AbeerVaishnav13
from qiskit import * %matplotlib inline from qiskit.tools.visualization import plot_histogram secretnumber = '101101' circuit = QuantumCircuit(6+1, 6) circuit.h([0,1,2,3,4,5]) circuit.x([6]) circuit.h([6]) circuit.barrier() circuit.cx(5, 6) circuit.cx(3, 6) circuit.cx(2, 6) circuit.cx(0, 6) circuit.barrier() circuit.h([0,1,2,3,4,5]) circuit.barrier() circuit.measure([0,1,2,3,4,5], [0,1,2,3,4,5]) circuit.draw('mpl') from matplotlib import style style.use('bmh') style.use('dark_background') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend = simulator, shots = 1).result() counts = result.get_counts() print(counts) plot_histogram(counts)
https://github.com/noamsgl/IBMAscolaChallenge
noamsgl
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import numpy as np filepath = "../datasets/universal_error/AllErrors/U3_4.csv" df = pd.read_csv(filepath) # reorder columns df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'p0_0', 'p0_1', 'p1_0', 'p1_1']] # filter out inf values df = df[np.isfinite] df.info() df.head() sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]}) sns.distplot(df['E'], norm_hist=False, kde=False, bins=50, hist_kws={'alpha': 1}).set(xlabel="'Expected Value", ylabel='Count') df.hist(bins=100, figsize=(20,15), layout=(3,4)); sns.scatterplot(x=df['theta'], y=df['E']); sns.jointplot(x=df['theta'], y=df['E']); sns.scatterplot(x=df['phi'], y=df['E']); sns.scatterplot(x=df['lam'], y=df['E']); sns.scatterplot(x=df['theta'], y=df['phi']); sns.scatterplot(x=df['depol_prob'], y=df['E']); sns.jointplot(x=df['t1'], y=df['E']); sns.jointplot(x=df['t2'], y=df['E']); sns.scatterplot(x=df['t1'], y=df['E']); sns.scatterplot(x=df['t2'], y=df['E']); ### Pair Plots sns.scatterplot(x=df['t2'], y=df['E']); sns.pairplot(data=df);
https://github.com/GlazeDonuts/QSVM
GlazeDonuts
import matplotlib.pyplot as plt import numpy as np from qiskit import Aer from qiskit.ml.datasets import ad_hoc_data, sample_ad_hoc_data, breast_cancer from qiskit.circuit.library import ZZFeatureMap from qiskit.aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import QSVM feature_dim = 2 # Number of input features sample_total, train_data, test_data, labels = ad_hoc_data(training_size=20, test_size=10, n=feature_dim, gap=0.3, plot_data=True) sample_test_data = sample_ad_hoc_data(sample_total, 10, n=feature_dim) data_pts, class2label = split_dataset_to_data_and_labels(sample_test_data) print("Classes and corresponding labels are:") for c in class2label: print(f"Class: {c}, Label: {class2label[c]}") seed = 10598 # Setting seed to ensure reproducable results feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement='linear') qsvm = QSVM(feature_map, train_data, test_data, data_pts[0]) backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed) result = qsvm.run(quantum_instance) print(f"Testing Accuracy: {result['testing_accuracy'] * 100}%") print("Prediction on Datapoints:") print(f"Ground Truth: {map_label_to_class_name(data_pts[1], qsvm.label_to_class)}") print(f"Predictions: {result['predicted_classes']}") print("Trained Kernel Matrix:") kernel_matrix = result['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r') plt.show() feature_dim = 2 # Number of input features sample_total_bc, train_data_bc, test_data_bc, labels_bc = breast_cancer(training_size=20, test_size=10, n=feature_dim, plot_data=True) seed = 10598 # Setting seed to ensure reproducable results feature_map_bc = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement='linear') qsvm_bc = QSVM(feature_map_bc, train_data_bc, test_data_bc) backend = Aer.get_backend('qasm_simulator') quantum_instance_bc = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed) result_bc = qsvm_bc.run(quantum_instance_bc) print(f"Testing Accuracy: {result_bc['testing_accuracy'] * 100}%") print("Trained Kernel Matrix:") kernel_matrix_bc = result_bc['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix_bc),interpolation='nearest',origin='upper',cmap='bone_r') plt.show()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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. """Size pass testing""" import unittest from qiskit import QuantumCircuit, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler.passes import Size from qiskit.test import QiskitTestCase class TestSizePass(QiskitTestCase): """Tests for Depth analysis methods.""" def test_empty_dag(self): """Empty DAG has 0 size""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = Size() _ = pass_.run(dag) self.assertEqual(pass_.property_set["size"], 0) def test_just_qubits(self): """A dag with 8 operations and no classic bits""" qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[1], qr[0]) dag = circuit_to_dag(circuit) pass_ = Size() _ = pass_.run(dag) self.assertEqual(pass_.property_set["size"], 8) def test_depth_one(self): """A dag with operations in parallel and size 2""" qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) dag = circuit_to_dag(circuit) pass_ = Size() _ = pass_.run(dag) self.assertEqual(pass_.property_set["size"], 2) def test_size_control_flow(self): """A DAG with control flow still gives an estimate.""" qc = QuantumCircuit(5, 1) qc.h(0) qc.measure(0, 0) with qc.if_test((qc.clbits[0], True)) as else_: qc.x(1) qc.cx(2, 3) with else_: qc.x(1) with qc.for_loop(range(3)): qc.z(2) with qc.for_loop((4, 0, 1)): qc.z(2) with qc.while_loop((qc.clbits[0], True)): qc.h(0) qc.measure(0, 0) pass_ = Size(recurse=True) pass_(qc) self.assertEqual(pass_.property_set["size"], 19) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.visualization import dag_drawer q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) dag_drawer(dag)
https://github.com/pragyakatyayan/Playing-with-parametrized-quantum-gates
pragyakatyayan
%matplotlib inline %config InlineBackend.figure_format = 'svg' from IPython.display import clear_output from qiskit import QuantumCircuit std_cirq=QuantumCircuit(2) std_cirq.h(0) # Hadamard gate on q0 std_cirq.x(1) # X gate on q1 std_cirq.cx(0,1) # CNOT on q1 controlled on q0 std_cirq.draw('mpl') from qiskit import Aer, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram backend = Aer.get_backend('statevector_simulator') #state = execute(std_cirq,backend).result().get_statevector() results = execute(std_cirq,backend).result().get_counts() plot_histogram(results, color='darkturquoise') from numpy import pi cirq = QuantumCircuit(2) cirq.ry(pi/2, 0) cirq.rx(pi, 0) cirq.rx(pi, 1) cirq.cx(0,1) cirq.draw('mpl') results = execute(cirq,backend).result().get_counts() plot_histogram(results, color='deepskyblue') from qiskit.visualization import plot_state_qsphere sv = Statevector.from_label('00').evolve(cirq) plot_state_qsphere(sv.data, show_state_phases=True) import qiskit qiskit.__qiskit_version__
https://github.com/qiskit-community/qiskit-pocket-guide
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Kraus import numpy as np noise_ops = [np.sqrt(0.9) * np.array([[1, 0], [0, 1]]), np.sqrt(0.1) * np.array([[0, 1], [1, 0]])] kraus = Kraus(noise_ops) qc = QuantumCircuit(2) qc.append(kraus, [0]) qc.append(kraus, [1]) qc.measure_all() qc.draw() from qiskit import Aer, transpile backend = Aer.get_backend("aer_simulator") tqc = transpile(qc, backend) job = backend.run(tqc, shots=1000) result = job.result() counts = result.get_counts(tqc) print(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_circuit_layout from qiskit.tools.monitor import job_monitor from qiskit.providers.fake_provider import FakeVigoV2 import matplotlib.pyplot as plt ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) backend = FakeVigoV2() new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
https://github.com/quantumjim/Qiskit-PyConDE
quantumjim
%matplotlib notebook # define a function that determines a brightness for any given point # uses a seed that is a list of four numbers def get_brightness(x,y,qc,seed): qc.data.clear() # empty the circuit # perform rotations, whose angles depend on x and y qc.rx( (1/8)*(seed[0]*x-seed[1]*y)*pi ,0) qc.ry( (1/16)*(seed[2]*x+seed[3]*y)*pi ,0) # calculate probability for outcome 1 qc.measure(0,0) p = simulate(qc,shots=1000,get='counts')['1']/1000 # return brightness depending on this probability # the chosen values here are fairly arbitrarily if p>0.7: if p<0.8: return 1 elif p<0.9: return 2 else: return 3 else: return 0 from microqiskit import QuantumCircuit, simulate from math import pi from random import random seed = [random() for _ in range(4)] # initialize circuit used by the function qc = QuantumCircuit(1,1) for y in range(50): line = '' for x in range(50): B = get_brightness(x,y,qc,seed) char = (B==0)*'▓▓' + (B==1)*'▒▒' + (B==2)*'░░' + (B==3)*' ' line += char print(line) ########################################################### # Replace this comment with the `get_brightness` function # # if running anywhere other than this notebook # ########################################################### import pew from microqiskit import QuantumCircuit, simulate from math import pi from random import random pew.init() screen = pew.Pix() # initialize circuit qc = QuantumCircuit(1,1) # set a random seed, composed of four numbers seed = [(2*(random()<0.5)-1)*(1+random())/2 for _ in range(4)] # coordinate of the current screen X,Y = 0,0 # loop to allow player to move half a screen while True: # arrow keys move to neighbouring screens keys = pew.keys() if keys!=0: if keys&pew.K_UP: Y -= 4 if keys&pew.K_DOWN: Y += 4 if keys&pew.K_LEFT: X -= 4 if keys&pew.K_RIGHT: X += 4 # loop over all points on the screen, and display the brightness for x in range(8): for y in range(8): B = get_brightness(x+X,y+Y,qc,seed) # coordinate of the player is accounted for also screen.pixel(x,y,B) pew.show(screen) pew.tick(1/6) from qiskit import QuantumCircuit, execute, Aer from math import pi from random import random ########################################################### # This is the function to edit # ########################################################### # define a function that determines a brightness for any given point # uses a seed that is a list of four numbers def get_brightness(x,y,qc,seed): qc.data.clear() # empty the circuit # perform rotations whose angles depend on x and y qc.rx((1/8)*(seed[0]*x-seed[1]*y)*pi,0) qc.ry((1/8)*(seed[2]*x+seed[3]*y**2)*pi+pi,0) # calculate probability for outcome 1 qc.measure(0,0) try: p = execute(qc,Aer.get_backend('qasm_simulator'),shots=1000).result().get_counts()['1']/1000 except: p = 0 # return brightness depending on this probability # the chosen values here are fairly arbitrary if p>0.7: if p<0.8: return 1 elif p<0.9: return 2 else: return 3 else: return 0 ########################################################### # The following uses the above function to create a 50x50 map, and print it in ASCII seed = [random() for _ in range(4)] # initialize circuit used by the function qc = QuantumCircuit(1,1) for y in range(50): line = '' for x in range(50): B = get_brightness(x,y,qc,seed) char = (B==0)*'▓▓' + (B==1)*'▒▒' + (B==2)*'░░' + (B==3)*' ' line += char print(line)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.quantum_info import SparsePauliOp H2_op = SparsePauliOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) from qiskit.circuit.library import TwoLocal from qiskit.algorithms.optimizers import SLSQP ansatz = TwoLocal(3, rotation_blocks=["ry", "rz"], entanglement_blocks="cz", reps=1) optimizer = SLSQP() ansatz.decompose().draw('mpl') from qiskit.primitives import Sampler, Estimator from qiskit.algorithms.state_fidelities import ComputeUncompute estimator = Estimator() sampler = Sampler() fidelity = ComputeUncompute(sampler) k = 3 betas = [33, 33, 33] counts = [] values = [] steps = [] def callback(eval_count, params, value, meta, step): counts.append(eval_count) values.append(value) steps.append(step) from qiskit.algorithms.eigensolvers import VQD vqd = VQD(estimator, fidelity, ansatz, optimizer, k=k, betas=betas, callback=callback) result = vqd.compute_eigenvalues(operator = H2_op) vqd_values = result.optimal_values print(vqd_values) import numpy as np import pylab pylab.rcParams["figure.figsize"] = (12, 8) steps = np.asarray(steps) counts = np.asarray(counts) values = np.asarray(values) for i in range(1,4): _counts = counts[np.where(steps == i)] _values = values[np.where(steps == i)] pylab.plot(_counts, _values, label=f"State {i-1}") pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence for each computed state") pylab.legend(loc="upper right"); from qiskit.algorithms.eigensolvers import NumPyEigensolver from qiskit.opflow import PauliSumOp exact_solver = NumPyEigensolver(k=3) exact_result = exact_solver.compute_eigenvalues(PauliSumOp(H2_op)) ref_values = exact_result.eigenvalues print(f"Reference values: {ref_values}") print(f"VQD values: {vqd_values}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/CynthiaRios/quantum_orchestra
CynthiaRios
![header](./jupyter_images/header.png "Header") ## General Imports from qiskit import QuantumCircuit, execute from qiskit import Aer from shutil import copyfile from qiskit.visualization import plot_histogram from qiskit import IBMQ import qiskit.tools.jupyter import os %qiskit_job_watcher from IPython.display import Audio import wave import numpy as np ## Button Display Imports (Needs installations mentioned above) from IPython.display import display, Markdown, clear_output # widget packages import ipywidgets as widgets from pydub import AudioSegment ![QuantumGates](./jupyter_images/quantumgates.png "Quantum Gates") #Will redo on quentin's computer tomorrow (today) piano_input = [None] * 5 piano = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([piano, piano2, piano3, piano4, piano5]) box guitar_input = [None] * 5 guitar = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([guitar, guitar2, guitar3, guitar4, guitar5]) box bass_input = [None] * 5 bass = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([bass, bass2, bass3, bass4, bass5]) box trumpet_input = [None] * 5 trumpet = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([trumpet, trumpet2, trumpet3, trumpet4, trumpet5]) box def GetGates(piano_input, guitar_input, bass_input, trumpet_input): if (piano.value == 'No Gate'): piano_input[0] = 'n' if (piano.value == 'X-Gate'): piano_input[0] = 'x' if (piano.value == 'Y-Gate'): piano_input[0] = 'y' if (piano.value == 'Z-Gate'): piano_input[0] = 'z' if (piano2.value == 'No Gate'): piano_input[1] = 'n' if (piano2.value == 'X-Gate'): piano_input[1] = 'x' if (piano2.value == 'Y-Gate'): piano_input[1] = 'y' if (piano2.value == 'Z-Gate'): piano_input[1] = 'z' if (piano3.value == 'No Gate'): piano_input[2] = 'n' if (piano3.value == 'X-Gate'): piano_input[2] = 'x' if (piano3.value == 'Y-Gate'): piano_input[2] = 'y' if (piano3.value == 'Z-Gate'): piano_input[2] = 'z' if (piano4.value == 'No Gate'): piano_input[3] = 'n' if (piano4.value == 'X-Gate'): piano_input[3] = 'x' if (piano4.value == 'Y-Gate'): piano_input[3] = 'y' if (piano4.value == 'Z-Gate'): piano_input[3] = 'z' if (piano5.value == 'No Gate'): piano_input[4] = 'n' if (piano5.value == 'X-Gate'): piano_input[4] = 'x' if (piano5.value == 'Y-Gate'): piano_input[4] = 'y' if (piano5.value == 'Z-Gate'): piano_input[4] = 'z' if (guitar.value == 'No Gate'): guitar_input[0] = 'n' if (guitar.value == 'X-Gate'): guitar_input[0] = 'x' if (guitar.value == 'Y-Gate'): guitar_input[0] = 'y' if (guitar.value == 'Z-Gate'): guitar_input[0] = 'z' if (guitar2.value == 'No Gate'): guitar_input[1] = 'n' if (guitar2.value == 'X-Gate'): guitar_input[1] = 'x' if (guitar2.value == 'Y-Gate'): guitar_input[1] = 'y' if (guitar2.value == 'Z-Gate'): guitar_input[1] = 'z' if (guitar3.value == 'No Gate'): guitar_input[2] = 'n' if (guitar3.value == 'X-Gate'): guitar_input[2] = 'x' if (guitar3.value == 'Y-Gate'): guitar_input[2] = 'y' if (guitar3.value == 'Z-Gate'): guitar_input[2] = 'z' if (guitar4.value == 'No Gate'): guitar_input[3] = 'n' if (guitar4.value == 'X-Gate'): guitar_input[3] = 'x' if (guitar4.value == 'Y-Gate'): guitar_input[3] = 'y' if (guitar4.value == 'Z-Gate'): guitar_input[3] = 'z' if (guitar5.value == 'No Gate'): guitar_input[4] = 'n' if (guitar5.value == 'X-Gate'): guitar_input[4] = 'x' if (guitar5.value == 'Y-Gate'): guitar_input[4] = 'y' if (guitar5.value == 'Z-Gate'): guitar_input[4] = 'z' if (bass.value == 'No Gate'): bass_input[0] = 'n' if (bass.value == 'X-Gate'): bass_input[0] = 'x' if (bass.value == 'Y-Gate'): bass_input[0] = 'y' if (bass.value == 'Z-Gate'): bass_input[0] = 'z' if (bass2.value == 'No Gate'): bass_input[1] = 'n' if (bass2.value == 'X-Gate'): bass_input[1] = 'x' if (bass2.value == 'Y-Gate'): bass_input[1] = 'y' if (bass2.value == 'Z-Gate'): bass_input[1] = 'z' if (bass3.value == 'No Gate'): bass_input[2] = 'n' if (bass3.value == 'X-Gate'): bass_input[2] = 'x' if (bass3.value == 'Y-Gate'): bass_input[2] = 'y' if (bass3.value == 'Z-Gate'): bass_input[2] = 'z' if (bass4.value == 'No Gate'): bass_input[3] = 'n' if (bass4.value == 'X-Gate'): bass_input[3] = 'x' if (bass4.value == 'Y-Gate'): bass_input[3] = 'y' if (bass4.value == 'Z-Gate'): bass_input[3] = 'z' if (bass5.value == 'No Gate'): bass_input[4] = 'n' if (bass5.value == 'X-Gate'): bass_input[4] = 'x' if (bass5.value == 'Y-Gate'): bass_input[4] = 'y' if (bass5.value == 'Z-Gate'): bass_input[4] = 'z' if (trumpet.value == 'No Gate'): trumpet_input[0] = 'n' if (trumpet.value == 'X-Gate'): trumpet_input[0] = 'x' if (trumpet.value == 'Y-Gate'): trumpet_input[0] = 'y' if (trumpet.value == 'Z-Gate'): trumpet_input[0] = 'z' if (trumpet2.value == 'No Gate'): trumpet_input[1] = 'n' if (trumpet2.value == 'X-Gate'): trumpet_input[1] = 'x' if (trumpet2.value == 'Y-Gate'): trumpet_input[1] = 'y' if (trumpet2.value == 'Z-Gate'): trumpet_input[1] = 'z' if (trumpet3.value == 'No Gate'): trumpet_input[2] = 'n' if (trumpet3.value == 'X-Gate'): trumpet_input[2] = 'x' if (trumpet3.value == 'Y-Gate'): trumpet_input[2] = 'y' if (trumpet3.value == 'Z-Gate'): trumpet_input[2] = 'z' if (trumpet4.value == 'No Gate'): trumpet_input[3] = 'n' if (trumpet4.value == 'X-Gate'): trumpet_input[3] = 'x' if (trumpet4.value == 'Y-Gate'): trumpet_input[3] = 'y' if (trumpet4.value == 'Z-Gate'): trumpet_input[3] = 'z' if (trumpet5.value == 'No Gate'): trumpet_input[4] = 'n' if (trumpet5.value == 'X-Gate'): trumpet_input[4] = 'x' if (trumpet5.value == 'Y-Gate'): trumpet_input[4] = 'y' if (trumpet5.value == 'Z-Gate'): trumpet_input[4] = 'z' return (piano_input, guitar_input, bass_input, trumpet_input) piano_input, guitar_input, bass_input, trumpet_input = GetGates(piano_input, guitar_input, bass_input, trumpet_input) #minimum user input will just be for them to fill out the create quantum circuit function inthe backend n = 5 #number of gates backend = Aer.get_backend('statevector_simulator') piano_states = [] guitar_states = [] bass_states = [] trumpet_states = [] def CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input): cct = QuantumCircuit(4,1) piano_states = [] guitar_states = [] bass_states = [] trumpet_states = [] for i in range(n-1): cct.h(i-1) cct.barrier() for i in range(n): if piano_input[i-1] == 'x': cct.x(0) if piano_input[i-1] == 'y': cct.y(0) if piano_input[i-1] == 'z': cct.z(0) piano_states.append(execute(cct, backend).result().get_statevector()) if guitar_input[i-1] == 'x': cct.x(1) if guitar_input[i-1] == 'y': cct.y(1) if guitar_input[i-1] == 'z': cct.z(1) guitar_states.append(execute(cct, backend).result().get_statevector()) if bass_input[i-1] == 'x': cct.x(2) if bass_input[i-1] == 'y': cct.y(2) if bass_input[i-1] == 'z': cct.z(2) bass_states.append(execute(cct, backend).result().get_statevector()) if trumpet_input[i-1] == 'x': cct.x(3) if trumpet_input[i-1] == 'y': cct.y(3) if trumpet_input[i-1] == 'z': cct.z(3) trumpet_states.append(execute(cct, backend).result().get_statevector()) cct.barrier() cct.draw('mpl') return piano_states, guitar_states, bass_states, trumpet_states, cct piano_states, guitar_states, bass_states, trumpet_states, cct = CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input) cct.draw(output="mpl") def SeperateArrays(states, vals_real, vals_imaginary): vals = [] for i in range(n+1): vals.append(states[i-1][0]) for i in range(n+1): vals_real.append((states[i-1][0].real)) vals_imaginary.append((states[i-1][0]).imag) return vals_real, vals_imaginary piano_real = [] piano_imaginary = [] piano_vals = [] guitar_real = [] guitar_imaginary = [] guitar_vals = [] bass_real = [] bass_imaginary = [] bass_vals = [] trumpet_real = [] trumpet_imaginary = [] trumpet_vals = [] piano_real, piano_imaginary = SeperateArrays(piano_states, piano_real, piano_imaginary) guitar_real, guitar_imaginary = SeperateArrays(guitar_states, guitar_real, guitar_imaginary) bass_real, bass_imaginary = SeperateArrays(bass_states, bass_real, bass_imaginary) trumpet_real, trumpet_imaginary = SeperateArrays(trumpet_states, trumpet_real, trumpet_imaginary) def MusicalTransformation(real, imaginary): tune_array=[] for i in range(n+1): if(real[i-1] < 0 and imaginary[i-1] > 0): tune_array.append('c') tune_array.append('g') tune_array.append('e') if(real[i-1] < 0 and imaginary[i-1] <= 0): tune_array.append('c') tune_array.append('f') tune_array.append('g') if(real[i-1] < 0 and imaginary[i-1] > 0): tune_array.append('d') tune_array.append('f') tune_array.append('a') if(real[i-1] < 0 and imaginary[i-1] <= 0): tune_array.append('f') tune_array.append('a') tune_array.append('c') if(real[i-1] > 0 and imaginary[i-1] > 0): tune_array.append('g') tune_array.append('b') tune_array.append('d') if(real[i-1] > 0 and imaginary[i-1] < 0): tune_array.append('d') tune_array.append('f') tune_array.append('a') if(real[i-1] > 0 and imaginary[i-1] >= 0): tune_array.append('e') tune_array.append('g') tune_array.append('b') if(real[i-1] > 0 and imaginary[i-1] < 0): tune_array.append('a') tune_array.append('c') tune_array.append('b') if(real[i-1] == 0 and imaginary[i-1] == 0): tune_array.append('n') tune_array.append('n') tune_array.append('n') return tune_array tune_array_piano = MusicalTransformation(piano_real, piano_imaginary) tune_array_guitar = MusicalTransformation(guitar_real, guitar_imaginary) tune_array_bass = MusicalTransformation(bass_real, bass_imaginary) tune_array_trumpet = MusicalTransformation(trumpet_real, trumpet_imaginary) def PlayPianoTune(character, songs): if character == 'a': sound_file = "./Audio/Piano/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Piano/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Piano/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Piano/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Piano/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Piano/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Piano/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayGuitarTune(character, songs): if character == 'a': sound_file = "./Audio/Guitar/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Guitar/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Guitar/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Guitar/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Guitar/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Guitar/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Guitar/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayBassTune(character, songs): if character == 'a': sound_file = "./Audio/Bass/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Bass/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Bass/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Bass/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Bass/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Bass/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Bass/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayTrumpetTune(character, songs): if character == 'a': sound_file = "./Audio/Trumpet/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Trumpet/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Trumpet/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Trumpet/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Trumpet/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Trumpet/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Trumpet/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs piano_song = [] for i in range(len(tune_array_piano)): character = tune_array_piano[i-1] piano_song = PlayPianoTune(character, piano_song) os.remove("./pianosounds.wav") copyfile('./Audio/blank.wav','./pianosounds.wav') for i in range(len(tune_array_piano)): infiles = [piano_song[i-1], "pianosounds.wav"] outfile = "pianosounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() guitar_song = [] for i in range(len(tune_array_guitar)): character = tune_array_piano[i-1] guitar_song = PlayGuitarTune(character, guitar_song) os.remove("./guitarsounds.wav") copyfile('./Audio/blank.wav','./guitarsounds.wav') for i in range(len(tune_array_guitar)): infiles = [guitar_song[i-1], "guitarsounds.wav"] outfile = "guitarsounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() bass_song = [] for i in range(len(tune_array_bass)): character = tune_array_bass[i-1] bass_song = PlayBassTune(character, bass_song) os.remove("./basssounds.wav") copyfile('./Audio/blank.wav','./basssounds.wav') for i in range(len(tune_array_bass)): infiles = [bass_song[i-1], "basssounds.wav"] outfile = "basssounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() trumpet_song = [] for i in range(len(tune_array_trumpet)): character = tune_array_trumpet[i-1] trumpet_song = PlayTrumpetTune(character, trumpet_song) os.remove("./trumpetsounds.wav") copyfile('./Audio/blank.wav','./trumpetsounds.wav') for i in range(len(tune_array_trumpet)): infiles = [trumpet_song[i-1], "trumpetsounds.wav"] outfile = "trumpetsounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() os.remove("./combined.wav") copyfile('./Audio/blank.wav','./combined.wav') os.remove("./combined2.wav") copyfile('./Audio/blank.wav','./combined2.wav') copyfile('./Audio/blank.wav','./output_song.wav') sound1 = AudioSegment.from_file("./trumpetsounds.wav") sound2 = AudioSegment.from_file("./basssounds.wav") combined = sound1.overlay(sound2) combined.export("./combined.wav", format='wav') sound3 = AudioSegment.from_file("./guitarsounds.wav") sound4 = AudioSegment.from_file("./pianosounds.wav") combined2 = sound3.overlay(sound4) combined2.export("./combined2.wav", format='wav') sound5 = AudioSegment.from_file("./combined.wav") sound6 = AudioSegment.from_file("./combined2.wav") output_song = sound5.overlay(sound6) output_song.export("./outputsong.wav", format='wav') sound_file = "./outputsong.wav" Audio(sound_file, autoplay=True) #https://musescore.org/en/download/musescore.msi !pip install music21 !pip install RISE from music21 import * #for Windows OS error #us = environment.UserSettings() #C:\Program Files\MuseScore 3\bin\MuseScore3.exe #us['musicxmlPath'] = "C:\\Program Files\\MuseScore 3\\bin\\MuseScore3.exe" #us['musescoreDirectPNGPath'] = "C:\\Program Files\\MuseScore 3\\bin\\MuseScore3.exe" piano_stream = stream.Stream() guitar_stream = stream.Stream() bass_stream = stream.Stream() trumpet_stream = stream.Stream() note1 = note.Note("A") note2 = note.Note("B") note3 = note.Note("C") note4 = note.Note("D") note5 = note.Note("E") note6 = note.Note("F") note7 = note.Note("G") def append_stream(array, stream): for i in range(n+1): if array[i-1] == 'a': stream.append(note1) if array[i-1] == 'b': stream.append(note2) if array[i-1] == 'c': stream.append(note3) if array[i-1] == 'd': stream.append(note4) if array[i-1] == 'e': stream.append(note5) if array[i-1] == 'f': stream.append(note6) if array[i-1] == 'g': stream.append(note7) return stream piano_stream=append_stream(tune_array_piano, piano_stream) guitar_stream=append_stream(tune_array_guitar, guitar_stream) bass_stream=append_stream(tune_array_bass, bass_stream) trumpet_stream=append_stream(tune_array_trumpet, trumpet_stream) piano_stream.show() guitar_stream.show() bass_stream.show() trumpet_stream.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate from qiskit.converters import dag_to_circuit q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) circuit = dag_to_circuit(dag) circuit.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from math import pi import numpy as np import rustworkx as rx from qiskit_nature.second_q.hamiltonians.lattices import ( BoundaryCondition, HyperCubicLattice, Lattice, LatticeDrawStyle, LineLattice, SquareLattice, TriangularLattice, ) from qiskit_nature.second_q.hamiltonians import FermiHubbardModel num_nodes = 11 boundary_condition = BoundaryCondition.OPEN line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) line_lattice.draw() num_nodes = 11 boundary_condition = BoundaryCondition.PERIODIC line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) line_lattice.draw() line_lattice.draw_without_boundary() num_nodes = 11 boundary_condition = BoundaryCondition.PERIODIC edge_parameter = 1.0 + 1.0j onsite_parameter = 1.0 line_lattice = LineLattice( num_nodes=num_nodes, edge_parameter=edge_parameter, onsite_parameter=onsite_parameter, boundary_condition=boundary_condition, ) set(line_lattice.graph.weighted_edge_list()) line_lattice.to_adjacency_matrix() line_lattice.to_adjacency_matrix(weighted=True) rows = 5 cols = 4 boundary_condition = BoundaryCondition.OPEN square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) square_lattice.draw() rows = 5 cols = 4 boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, ) # open in the x-direction, periodic in the y-direction square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) square_lattice.draw() rows = 5 cols = 4 edge_parameter = (1.0, 1.0 + 1.0j) boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, ) # open in the x-direction, periodic in the y-direction onsite_parameter = 1.0 square_lattice = SquareLattice( rows=rows, cols=cols, edge_parameter=edge_parameter, onsite_parameter=onsite_parameter, boundary_condition=boundary_condition, ) set(square_lattice.graph.weighted_edge_list()) size = (3, 4, 5) boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.OPEN, BoundaryCondition.OPEN, ) cubic_lattice = HyperCubicLattice(size=size, boundary_condition=boundary_condition) # function for setting the positions def indextocoord_3d(index: int, size: tuple, angle) -> list: z = index // (size[0] * size[1]) a = index % (size[0] * size[1]) y = a // size[0] x = a % size[0] vec_x = np.array([1, 0]) vec_y = np.array([np.cos(angle), np.sin(angle)]) vec_z = np.array([0, 1]) return_coord = x * vec_x + y * vec_y + z * vec_z return return_coord.tolist() pos = dict([(index, indextocoord_3d(index, size, angle=pi / 4)) for index in range(np.prod(size))]) cubic_lattice.draw(style=LatticeDrawStyle(pos=pos)) rows = 4 cols = 3 boundary_condition = BoundaryCondition.OPEN triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) triangular_lattice.draw() rows = 4 cols = 3 boundary_condition = BoundaryCondition.PERIODIC triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) triangular_lattice.draw() graph = rx.PyGraph(multigraph=False) # multigraph shoud be False graph.add_nodes_from(range(6)) weighted_edge_list = [ (0, 1, 1.0 + 1.0j), (0, 2, -1.0), (2, 3, 2.0), (4, 2, -1.0 + 2.0j), (4, 4, 3.0), (2, 5, -1.0), ] graph.add_edges_from(weighted_edge_list) # make a lattice general_lattice = Lattice(graph) set(general_lattice.graph.weighted_edge_list()) general_lattice.draw() general_lattice.draw(self_loop=True) general_lattice.draw(self_loop=True, style=LatticeDrawStyle(with_labels=True)) square_lattice = SquareLattice(rows=5, cols=4, boundary_condition=BoundaryCondition.PERIODIC) t = -1.0 # the interaction parameter v = 0.0 # the onsite potential u = 5.0 # the interaction parameter U fhm = FermiHubbardModel( square_lattice.uniform_parameters( uniform_interaction=t, uniform_onsite_potential=v, ), onsite_interaction=u, ) ham = fhm.second_q_op().simplify() print(ham) graph = rx.PyGraph(multigraph=False) # multiigraph shoud be False graph.add_nodes_from(range(6)) weighted_edge_list = [ (0, 1, 1.0 + 1.0j), (0, 2, -1.0), (2, 3, 2.0), (4, 2, -1.0 + 2.0j), (4, 4, 3.0), (2, 5, -1.0), ] graph.add_edges_from(weighted_edge_list) general_lattice = Lattice(graph) # the lattice whose weights are seen as the interaction matrix. u = 5.0 # the interaction parameter U fhm = FermiHubbardModel(lattice=general_lattice, onsite_interaction=u) ham = fhm.second_q_op().simplify() print(ham) from qiskit_nature.second_q.problems import LatticeModelProblem num_nodes = 4 boundary_condition = BoundaryCondition.OPEN line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) fhm = FermiHubbardModel( line_lattice.uniform_parameters( uniform_interaction=t, uniform_onsite_potential=v, ), onsite_interaction=u, ) lmp = LatticeModelProblem(fhm) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import JordanWignerMapper numpy_solver = NumPyMinimumEigensolver() qubit_mapper = JordanWignerMapper() calc = GroundStateEigensolver(qubit_mapper, numpy_solver) res = calc.solve(lmp) print(res) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.problems import ElectronicBasis driver = PySCFDriver() driver.run_pyscf() ao_problem = driver.to_problem(basis=ElectronicBasis.AO) print(ao_problem.basis) ao_hamil = ao_problem.hamiltonian print(ao_hamil.electronic_integrals.alpha) from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema qcschema = driver.to_qcschema() basis_transformer = get_ao_to_mo_from_qcschema(qcschema) print(basis_transformer.initial_basis) print(basis_transformer.final_basis) mo_problem = basis_transformer.transform(ao_problem) print(mo_problem.basis) mo_hamil = mo_problem.hamiltonian print(mo_hamil.electronic_integrals.alpha) import numpy as np from qiskit_nature.second_q.operators import ElectronicIntegrals from qiskit_nature.second_q.problems import ElectronicBasis from qiskit_nature.second_q.transformers import BasisTransformer ao2mo_alpha = np.random.random((2, 2)) ao2mo_beta = np.random.random((2, 2)) basis_transformer = BasisTransformer( ElectronicBasis.AO, ElectronicBasis.MO, ElectronicIntegrals.from_raw_integrals(ao2mo_alpha, h1_b=ao2mo_beta), ) from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5") full_problem = driver.run() print(full_problem.molecule) print(full_problem.num_particles) print(full_problem.num_spatial_orbitals) from qiskit_nature.second_q.transformers import FreezeCoreTransformer fc_transformer = FreezeCoreTransformer() fc_problem = fc_transformer.transform(full_problem) print(fc_problem.num_particles) print(fc_problem.num_spatial_orbitals) print(fc_problem.hamiltonian.constants) fc_transformer = FreezeCoreTransformer(remove_orbitals=[4, 5]) fc_problem = fc_transformer.transform(full_problem) print(fc_problem.num_particles) print(fc_problem.num_spatial_orbitals) from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5") full_problem = driver.run() print(full_problem.num_particles) print(full_problem.num_spatial_orbitals) from qiskit_nature.second_q.transformers import ActiveSpaceTransformer as_transformer = ActiveSpaceTransformer(2, 2) as_problem = as_transformer.transform(full_problem) print(as_problem.num_particles) print(as_problem.num_spatial_orbitals) print(as_problem.hamiltonian.electronic_integrals.alpha) as_transformer = ActiveSpaceTransformer(2, 2, active_orbitals=[0, 4]) as_problem = as_transformer.transform(full_problem) print(as_problem.num_particles) print(as_problem.num_spatial_orbitals) print(as_problem.hamiltonian.electronic_integrals.alpha) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/PennyLaneAI/pennylane
PennyLaneAI
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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. """ This module contains functions to load circuits from other frameworks as PennyLane templates. """ from collections import defaultdict from importlib import metadata from sys import version_info # Error message to show when the PennyLane-Qiskit plugin is required but missing. _MISSING_QISKIT_PLUGIN_MESSAGE = ( "Conversion from Qiskit requires the PennyLane-Qiskit plugin. " "You can install the plugin by running: pip install pennylane-qiskit. " "You may need to restart your kernel or environment after installation. " "If you have any difficulties, you can reach out on the PennyLane forum at " "https://discuss.pennylane.ai/c/pennylane-plugins/pennylane-qiskit/" ) # get list of installed plugin converters __plugin_devices = ( defaultdict(tuple, metadata.entry_points())["pennylane.io"] if version_info[:2] == (3, 9) else metadata.entry_points(group="pennylane.io") # pylint:disable=unexpected-keyword-arg ) plugin_converters = {entry.name: entry for entry in __plugin_devices} def from_qiskit(quantum_circuit, measurements=None): r"""Converts a Qiskit `QuantumCircuit <https://docs.quantum.ibm.com/api/qiskit/qiskit.circuit.QuantumCircuit>`_ into a PennyLane :ref:`quantum function <intro_vcirc_qfunc>`. .. note:: This function depends upon the PennyLane-Qiskit plugin. Follow the `installation instructions <https://docs.pennylane.ai/projects/qiskit/en/latest/installation.html>`__ to get up and running. You may need to restart your kernel if you are running in a notebook environment. Args: quantum_circuit (qiskit.QuantumCircuit): a quantum circuit created in Qiskit measurements (None | MeasurementProcess | list[MeasurementProcess]): an optional PennyLane measurement or list of PennyLane measurements that overrides any terminal measurements that may be present in the input circuit Returns: function: The PennyLane quantum function, created based on the input Qiskit ``QuantumCircuit`` object. **Example:** .. code-block:: python import pennylane as qml from qiskit import QuantumCircuit qc = QuantumCircuit(2, 2) qc.rx(0.785, 0) qc.ry(1.57, 1) my_qfunc = qml.from_qiskit(qc) The ``my_qfunc`` function can now be used within QNodes, as a two-wire quantum template. We can also pass ``wires`` when calling the returned template to define which wires it should operate on. If no wires are passed, it will default to sequential wire labels starting at 0. .. code-block:: python dev = qml.device("default.qubit") @qml.qnode(dev) def circuit(): my_qfunc(wires=["a", "b"]) return qml.expval(qml.Z("a")), qml.var(qml.Z("b")) >>> circuit() (tensor(0.70738827, requires_grad=True), tensor(0.99999937, requires_grad=True)) The measurements can also be passed directly to the function when creating the quantum function, making it possible to create a PennyLane circuit with :class:`qml.QNode <pennylane.QNode>`: >>> measurements = [qml.expval(qml.Z(0)), qml.var(qml.Z(1))] >>> circuit = qml.QNode(qml.from_qiskit(qc, measurements), dev) >>> circuit() (tensor(0.70738827, requires_grad=True), tensor(0.99999937, requires_grad=True)) .. note:: The ``measurements`` keyword allows one to add a list of PennyLane measurements that will **override** any terminal measurements present in the ``QuantumCircuit``, so that they are not performed before the operations specified in ``measurements``. ``measurements=None``. If an existing ``QuantumCircuit`` already contains measurements, ``from_qiskit`` will return those measurements, provided that they are not overriden as shown above. These measurements can be used, e.g., for conditioning with :func:`qml.cond() <~.cond>`, or simply included directly within the QNode's return: .. code-block:: python qc = QuantumCircuit(2, 2) qc.rx(np.pi, 0) qc.measure_all() @qml.qnode(dev) def circuit(): # Since measurements=None, the measurements present in the QuantumCircuit are returned. measurements = qml.from_qiskit(qc)() return [qml.expval(m) for m in measurements] >>> circuit() [tensor(1., requires_grad=True), tensor(0., requires_grad=True)] .. note:: The ``measurements`` returned from a ``QuantumCircuit`` are in the computational basis with 0 corresponding to :math:`|0\rangle` and 1 corresponding to :math:`|1 \rangle`. This corresponds to the :math:`|1 \rangle \langle 1|` observable rather than the :math:`Z` Pauli operator. See below for more information regarding how to translate more complex circuits from Qiskit to PennyLane, including handling parameterized Qiskit circuits, mid-circuit measurements, and classical control flows. .. details:: :title: Parameterized Quantum Circuits A Qiskit ``QuantumCircuit`` is parameterized if it contains `Parameter <https://docs.quantum.ibm.com/api/qiskit/qiskit.circuit.Parameter>`__ or `ParameterVector <https://docs.quantum.ibm.com/api/qiskit/qiskit.circuit.ParameterVector>`__ references that need to be given defined values to evaluate the circuit. These can be passed to the generated quantum function as keyword or positional arguments. If we define a parameterized circuit: .. code-block:: python from qiskit.circuit import QuantumCircuit, Parameter angle0 = Parameter("x") angle1 = Parameter("y") qc = QuantumCircuit(2, 2) qc.rx(angle0, 0) qc.ry(angle1, 1) qc.cx(1, 0) Then this circuit can be converted into a differentiable circuit in PennyLane and executed: .. code-block:: python import pennylane as qml from pennylane import numpy as np dev = qml.device("default.qubit") qfunc = qml.from_qiskit(qc, measurements=qml.expval(qml.Z(0))) circuit = qml.QNode(qfunc, dev) Now, ``circuit`` has a signature of ``(x, y)``. The parameters are ordered alphabetically. >>> x = np.pi / 4 >>> y = 0 >>> circuit(x, y) tensor(0.70710678, requires_grad=True) >>> qml.grad(circuit, argnum=[0, 1])(np.pi/4, np.pi/6) (array(-0.61237244), array(-0.35355339)) The ``QuantumCircuit`` may also be parameterized with a ``ParameterVector``. These can be similarly converted: .. code-block:: python from qiskit.circuit import ParameterVector angles = ParameterVector("angles", 2) qc = QuantumCircuit(2, 2) qc.rx(angles[0], 0) qc.ry(angles[1], 1) qc.cx(1, 0) @qml.qnode(dev) def circuit(angles): qml.from_qiskit(qc)(angles) return qml.expval(qml.Z(0)) >>> angles = [3.1, 0.45] >>> circuit(angles) tensor(-0.89966835, requires_grad=True) .. details:: :title: Measurements and Classical Control Flows When ``measurement=None``, all of the measurements performed in the ``QuantumCircuit`` will be returned by the quantum function in the form of a :ref:`mid-circuit measurement <mid_circuit_measurements>`. For example, if we define a ``QuantumCircuit`` with measurements: .. code-block:: python import pennylane as qml from qiskit import QuantumCircuit qc = QuantumCircuit(2, 2) qc.h(0) qc.measure(0, 0) qc.rz(0.24, [0]) qc.cx(0, 1) qc.measure_all() Then we can create a PennyLane circuit that uses this as a sub-circuit, and performs additional operations conditional on the results. We can also calculate standard mid-circuit measurement statistics, like expectation value, on the returned measurements: .. code-block:: python @qml.qnode(qml.device("default.qubit")) def circuit(): # apply the QuantumCircuit and retrieve the measurements mid_measure0, m0, m1 = qml.from_qiskit(qc)() # conditionally apply an additional operation based on the results qml.cond(mid_measure0==0, qml.RX)(np.pi/2, 0) # return the expectation value of one of the mid-circuit measurements, and a terminal measurement return qml.expval(mid_measure0), qml.expval(m1) >>> circuit() (tensor(0.5, requires_grad=True), tensor(0.5, requires_grad=True)) .. note:: The order of mid-circuit measurements returned by `qml.from_qiskit()` in the example above is determined by the order in which measurements appear in the input Qiskit ``QuantumCircuit``. Furthermore, the Qiskit `IfElseOp <https://docs.quantum.ibm.com/api/qiskit/qiskit.circuit.IfElseOp>`__, `SwitchCaseOp <https://docs.quantum.ibm.com/api/qiskit/qiskit.circuit.SwitchCaseOp>`__ and `c_if <https://docs.quantum.ibm.com/api/qiskit/qiskit.circuit.Instruction#c_if>`__ conditional workflows are automatically translated into their PennyLane counterparts during conversion. For example, if we construct a ``QuantumCircuit`` with these workflows: .. code-block:: python qc = QuantumCircuit(4, 1) qc.h(0) qc.measure(0, 0) # Use an `IfElseOp` operation. noop = QuantumCircuit(1) flip_x = QuantumCircuit(1) flip_x.x(0) qc.if_else((qc.clbits[0], True), flip_x, noop, [1], []) # Use a `SwitchCaseOp` operation. with qc.switch(qc.clbits[0]) as case: with case(0): qc.y(2) # Use the `c_if()` function. qc.z(3).c_if(qc.clbits[0], True) qc.measure_all() We can convert the ``QuantumCircuit`` into a PennyLane quantum function using: .. code-block:: python dev = qml.device("default.qubit") measurements = [qml.expval(qml.Z(i)) for i in range(qc.num_qubits)] cond_circuit = qml.QNode(qml.from_qiskit(qc, measurements=measurements), dev) The result is: >>> print(qml.draw(cond_circuit)()) 0: ──H──┤↗├──────────╭||─┤ <Z> 1: ──────║───X───────├||─┤ <Z> 2: ──────║───║──Y────├||─┤ <Z> 3: ──────║───║──║──Z─╰||─┤ <Z> ╚═══╩══╩══╝ """ try: plugin_converter = plugin_converters["qiskit"].load() return plugin_converter(quantum_circuit, measurements=measurements) except KeyError as e: raise RuntimeError(_MISSING_QISKIT_PLUGIN_MESSAGE) from e def from_qiskit_op(qiskit_op, params=None, wires=None): """Converts a Qiskit `SparsePauliOp <https://docs.quantum.ibm.com/api/qiskit/qiskit.quantum_info.SparsePauliOp>`__ into a PennyLane :class:`Operator <pennylane.operation.Operator>`. .. note:: This function depends upon the PennyLane-Qiskit plugin. Follow the `installation instructions <https://docs.pennylane.ai/projects/qiskit/en/latest/installation.html>`__ to get up and running. You may need to restart your kernel if you are running in a notebook environment. Args: qiskit_op (qiskit.quantum_info.SparsePauliOp): a ``SparsePauliOp`` created in Qiskit params (Any): optional assignment of coefficient values for the ``SparsePauliOp``; see the `Qiskit documentation <https://docs.quantum.ibm.com/api/qiskit/qiskit.quantum_info.SparsePauliOp#assign_parameters>`_ to learn more about the expected format of these parameters wires (Sequence | None): optional assignment of wires for the converted ``SparsePauliOp``; if the original ``SparsePauliOp`` acted on :math:`N` qubits, then this must be a sequence of length :math:`N` Returns: Operator: The PennyLane operator, created based on the input Qiskit ``SparsePauliOp`` object. .. note:: The wire ordering convention differs between PennyLane and Qiskit: PennyLane wires are enumerated from left to right, while the Qiskit convention is to enumerate from right to left. This means a ``SparsePauliOp`` term defined by the string ``"XYZ"`` applies ``Z`` on wire 0, ``Y`` on wire 1, and ``X`` on wire 2. For more details, see the `String representation <https://docs.quantum.ibm.com/api/qiskit/qiskit.quantum_info.Pauli>`_ section of the Qiskit documentation for the ``Pauli`` class. **Example** Consider the following script which creates a Qiskit ``SparsePauliOp``: .. code-block:: python from qiskit.quantum_info import SparsePauliOp qiskit_op = SparsePauliOp(["II", "XY"]) The ``SparsePauliOp`` contains two terms and acts over two qubits: >>> qiskit_op SparsePauliOp(['II', 'XY'], coeffs=[1.+0.j, 1.+0.j]) To convert the ``SparsePauliOp`` into a PennyLane :class:`pennylane.operation.Operator`, use: >>> import pennylane as qml >>> qml.from_qiskit_op(qiskit_op) I(0) + X(1) @ Y(0) .. details:: :title: Usage Details You can convert a parameterized ``SparsePauliOp`` into a PennyLane operator by assigning literal values to each coefficient parameter. For example, the script .. code-block:: python import numpy as np from qiskit.circuit import Parameter a, b, c = [Parameter(var) for var in "abc"] param_qiskit_op = SparsePauliOp(["II", "XZ", "YX"], coeffs=np.array([a, b, c])) defines a ``SparsePauliOp`` with three coefficients (parameters): >>> param_qiskit_op SparsePauliOp(['II', 'XZ', 'YX'], coeffs=[ParameterExpression(1.0*a), ParameterExpression(1.0*b), ParameterExpression(1.0*c)]) The ``SparsePauliOp`` can be converted into a PennyLane operator by calling the conversion function and specifying the value of each parameter using the ``params`` argument: >>> qml.from_qiskit_op(param_qiskit_op, params={a: 2, b: 3, c: 4}) ( (2+0j) * I(0) + (3+0j) * (X(1) @ Z(0)) + (4+0j) * (Y(1) @ X(0)) ) Similarly, a custom wire mapping can be applied to a ``SparsePauliOp`` as follows: >>> wired_qiskit_op = SparsePauliOp("XYZ") >>> wired_qiskit_op SparsePauliOp(['XYZ'], coeffs=[1.+0.j]) >>> qml.from_qiskit_op(wired_qiskit_op, wires=[3, 5, 7]) Y(5) @ Z(3) @ X(7) """ try: plugin_converter = plugin_converters["qiskit_op"].load() return plugin_converter(qiskit_op, params=params, wires=wires) except KeyError as e: raise RuntimeError(_MISSING_QISKIT_PLUGIN_MESSAGE) from e def from_qasm(quantum_circuit: str, measurements=None): r""" Loads quantum circuits from a QASM string using the converter in the PennyLane-Qiskit plugin. Args: quantum_circuit (str): a QASM string containing a valid quantum circuit measurements (None | MeasurementProcess | list[MeasurementProcess]): an optional PennyLane measurement or list of PennyLane measurements that overrides the terminal measurements that may be present in the input circuit. Defaults to ``None``, such that all existing measurements in the input circuit are returned. See *Removing terminal measurements* for details. Returns: function: the PennyLane quantum function created based on the QASM string. This function itself returns the mid-circuit measurements plus the terminal measurements by default (``measurements=None``), and returns **only** the measurements from the ``measurements`` argument otherwise. **Example:** .. code-block:: python qasm_code = 'OPENQASM 2.0;' \ 'include "qelib1.inc";' \ 'qreg q[2];' \ 'creg c[2];' \ 'h q[0];' \ 'measure q[0] -> c[0];' \ 'rz(0.24) q[0];' \ 'cx q[0], q[1];' \ 'measure q -> c;' loaded_circuit = qml.from_qasm(qasm_code) >>> print(qml.draw(loaded_circuit)()) 0: ──H──┤↗├──RZ(0.24)─╭●──┤↗├─┤ 1: ───────────────────╰X──┤↗├─┤ Calling the quantum function returns a tuple containing the mid-circuit measurements and the terminal measurements. >>> loaded_circuit() (MeasurementValue(wires=[0]), MeasurementValue(wires=[0]), MeasurementValue(wires=[1])) A list of measurements can also be passed directly to ``from_qasm`` using the ``measurements`` argument, making it possible to create a PennyLane circuit with :class:`qml.QNode <pennylane.QNode>`. .. code-block:: python dev = qml.device("default.qubit") measurements = [qml.var(qml.Y(0))] circuit = qml.QNode(qml.from_qasm(qasm_code, measurements = measurements), dev) >>> print(qml.draw(circuit)()) 0: ──H──┤↗├──RZ(0.24)─╭●─┤ Var[Y] 1: ───────────────────╰X─┤ .. details:: :title: Removing terminal measurements To remove all terminal measurements, set ``measurements=[]``. This removes the existing terminal measurements and keeps the mid-circuit measurements. .. code-block:: python loaded_circuit = qml.from_qasm(qasm_code, measurements=[]) >>> print(qml.draw(loaded_circuit)()) 0: ──H──┤↗├──RZ(0.24)─╭●─┤ 1: ───────────────────╰X─┤ Calling the quantum function returns the same empty list that we originally passed in. >>> loaded_circuit() [] Note that mid-circuit measurements are always applied, but are only returned when ``measurements=None``. This can be exemplified by using the ``loaded_circuit`` without the terminal measurements within a ``QNode``. .. code-block:: python dev = qml.device("default.qubit") @qml.qnode(dev) def circuit(): loaded_circuit() return qml.expval(qml.Z(1)) >>> print(qml.draw(circuit)()) 0: ──H──┤↗├──RZ(0.24)─╭●─┤ 1: ───────────────────╰X─┤ <Z> .. details:: :title: Using conditional operations We can take advantage of the mid-circuit measurements inside the QASM code by calling the returned function within a :class:`qml.QNode <pennylane.QNode>`. .. code-block:: python loaded_circuit = qml.from_qasm(qasm_code) @qml.qnode(dev) def circuit(): mid_measure, *_ = loaded_circuit() qml.cond(mid_measure == 0, qml.RX)(np.pi / 2, 0) return [qml.expval(qml.Z(0))] >>> print(qml.draw(circuit)()) 0: ──H──┤↗├──RZ(0.24)─╭●──┤↗├──RX(1.57)─┤ <Z> 1: ──────║────────────╰X──┤↗├──║────────┤ ╚═════════════════════╝ .. details:: :title: Importing from a QASM file We can also load the contents of a QASM file. .. code-block:: python # save the qasm code in a file import locale from pathlib import Path filename = "circuit.qasm" with Path(filename).open("w", encoding=locale.getpreferredencoding(False)) as f: f.write(qasm_code) with open("circuit.qasm", "r") as f: loaded_circuit = qml.from_qasm(f.read()) The ``loaded_circuit`` function can now be used within a :class:`qml.QNode <pennylane.QNode>` as a two-wire quantum template. .. code-block:: python @qml.qnode(dev) def circuit(x): qml.RX(x, wires=1) loaded_circuit(wires=(0, 1)) return qml.expval(qml.Z(0)) >>> print(qml.draw(circuit)(1.23)) 0: ──H─────────┤↗├──RZ(0.24)─╭●──┤↗├─┤ <Z> 1: ──RX(1.23)────────────────╰X──┤↗├─┤ """ try: plugin_converter = plugin_converters["qasm"].load() except Exception as e: # pragma: no cover raise RuntimeError( # pragma: no cover "Failed to load the qasm plugin. Please ensure that the pennylane-qiskit package is installed." ) from e return plugin_converter(quantum_circuit, measurements=measurements) def from_pyquil(pyquil_program): """Loads pyQuil Program objects by using the converter in the PennyLane-Rigetti plugin. **Example:** >>> program = pyquil.Program() >>> program += pyquil.gates.H(0) >>> program += pyquil.gates.CNOT(0, 1) >>> my_circuit = qml.from_pyquil(program) The ``my_circuit`` template can now be used within QNodes, as a two-wire quantum template. >>> @qml.qnode(dev) >>> def circuit(x): >>> qml.RX(x, wires=1) >>> my_circuit(wires=[1, 0]) >>> return qml.expval(qml.Z(0)) Args: pyquil_program (pyquil.Program): a program created in pyQuil Returns: pennylane_forest.ProgramLoader: a ``pennylane_forest.ProgramLoader`` instance that can be used like a PennyLane template and that contains additional inspection properties """ plugin_converter = plugin_converters["pyquil_program"].load() return plugin_converter(pyquil_program) def from_quil(quil: str): """Loads quantum circuits from a Quil string using the converter in the PennyLane-Rigetti plugin. **Example:** .. code-block:: python >>> quil_str = 'H 0\\n' ... 'CNOT 0 1' >>> my_circuit = qml.from_quil(quil_str) The ``my_circuit`` template can now be used within QNodes, as a two-wire quantum template. >>> @qml.qnode(dev) >>> def circuit(x): >>> qml.RX(x, wires=1) >>> my_circuit(wires=(1, 0)) >>> return qml.expval(qml.Z(0)) Args: quil (str): a Quil string containing a valid quantum circuit Returns: pennylane_forest.ProgramLoader: a ``pennylane_forest.ProgramLoader`` instance that can be used like a PennyLane template and that contains additional inspection properties """ plugin_converter = plugin_converters["quil"].load() return plugin_converter(quil) def from_quil_file(quil_filename: str): """Loads quantum circuits from a Quil file using the converter in the PennyLane-Rigetti plugin. **Example:** >>> my_circuit = qml.from_quil_file("teleportation.quil") The ``my_circuit`` template can now be used within QNodes, as a two-wire quantum template. >>> @qml.qnode(dev) >>> def circuit(x): >>> qml.RX(x, wires=1) >>> my_circuit(wires=(1, 0)) >>> return qml.expval(qml.Z(0)) Args: quil_filename (str): path to a Quil file containing a valid quantum circuit Returns: pennylane_forest.ProgramLoader: a ``pennylane_forest.ProgramLoader`` instance that can be used like a PennyLane template and that contains additional inspection properties """ plugin_converter = plugin_converters["quil_file"].load() return plugin_converter(quil_filename)
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/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Transpiler testing""" import io from logging import StreamHandler, getLogger import unittest.mock import sys from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler import PassManager, TranspilerError from qiskit.transpiler.runningpassmanager import ( DoWhileController, ConditionalController, FlowController, ) from qiskit.test import QiskitTestCase from ._dummy_passes import ( PassA_TP_NR_NP, PassB_TP_RA_PA, PassC_TP_RA_PA, PassD_TP_NR_NP, PassE_AP_NR_NP, PassF_reduce_dag_property, PassI_Bad_AP, PassJ_Bad_NoReturn, PassK_check_fixed_point_property, PassM_AP_NR_NP, ) class SchedulerTestCase(QiskitTestCase): """Asserts for the scheduler.""" def assertScheduler(self, circuit, passmanager, expected): """ Run `transpile(circuit, passmanager)` and check if the passes run as expected. Args: circuit (QuantumCircuit): Circuit to transform via transpilation. passmanager (PassManager): pass manager instance for the transpilation process expected (list): List of things the passes are logging """ logger = "LocalLogger" with self.assertLogs(logger, level="INFO") as cm: out = passmanager.run(circuit) self.assertIsInstance(out, QuantumCircuit) self.assertEqual([record.message for record in cm.records], expected) def assertSchedulerRaises(self, circuit, passmanager, expected, exception_type): """ Run `transpile(circuit, passmanager)` and check if the passes run as expected until exception_type is raised. Args: circuit (QuantumCircuit): Circuit to transform via transpilation passmanager (PassManager): pass manager instance for the transpilation process expected (list): List of things the passes are logging exception_type (Exception): Exception that is expected to be raised. """ logger = "LocalLogger" with self.assertLogs(logger, level="INFO") as cm: self.assertRaises(exception_type, passmanager.run, circuit) self.assertEqual([record.message for record in cm.records], expected) class TestPassManagerInit(SchedulerTestCase): """The pass manager sets things at init time.""" def test_passes(self): """A single chain of passes, with Requests and Preserves, at __init__ time""" circuit = QuantumCircuit(QuantumRegister(1)) passmanager = PassManager( passes=[ PassC_TP_RA_PA(), # Request: PassA / Preserves: PassA PassB_TP_RA_PA(), # Request: PassA / Preserves: PassA PassD_TP_NR_NP(argument1=[1, 2]), # Requires: {}/ Preserves: {} PassB_TP_RA_PA(), ] ) self.assertScheduler( circuit, passmanager, [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassD_TP_NR_NP", "argument [1, 2]", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", ], ) class TestUseCases(SchedulerTestCase): """Combine passes in different ways and checks that passes are run in the right order.""" def setUp(self): super().setUp() self.circuit = QuantumCircuit(QuantumRegister(1)) self.passmanager = PassManager() def test_chain(self): """A single chain of passes, with Requires and Preserves.""" self.passmanager.append(PassC_TP_RA_PA()) # Requires: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Requires: PassA / Preserves: PassA self.passmanager.append(PassD_TP_NR_NP(argument1=[1, 2])) # Requires: {}/ Preserves: {} self.passmanager.append(PassB_TP_RA_PA()) self.assertScheduler( self.circuit, self.passmanager, [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassD_TP_NR_NP", "argument [1, 2]", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", ], ) def test_conditional_passes_true(self): """A pass set with a conditional parameter. The callable is True.""" self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", ], ) def test_conditional_passes_true_fc(self): """A pass set with a conditional parameter (with FlowController). The callable is True.""" self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( ConditionalController( [PassA_TP_NR_NP()], condition=lambda property_set: property_set["property"] ) ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", ], ) def test_conditional_passes_false(self): """A pass set with a conditional parameter. The callable is False.""" self.passmanager.append(PassE_AP_NR_NP(False)) self.passmanager.append( PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) self.assertScheduler( self.circuit, self.passmanager, ["run analysis pass PassE_AP_NR_NP", "set property as False"], ) def test_conditional_and_loop(self): """Run a conditional first, then a loop.""" self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], condition=lambda property_set: property_set["property"], ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ], ) def test_loop_and_conditional(self): """Run a loop first, then a conditional.""" FlowController.remove_flow_controller("condition") FlowController.add_flow_controller("condition", ConditionalController) self.passmanager.append(PassK_check_fixed_point_property()) self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], condition=lambda property_set: not property_set["property_fixed_point"], ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ], ) def test_do_not_repeat_based_on_preservation(self): """When a pass is still a valid pass (because the following passes preserved it), it should not run again.""" self.passmanager.append([PassB_TP_RA_PA(), PassA_TP_NR_NP(), PassB_TP_RA_PA()]) self.assertScheduler( self.circuit, self.passmanager, ["run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA"], ) def test_do_not_repeat_based_on_idempotence(self): """Repetition can be optimized to a single execution when the pass is idempotent.""" self.passmanager.append(PassA_TP_NR_NP()) self.passmanager.append([PassA_TP_NR_NP(), PassA_TP_NR_NP()]) self.passmanager.append(PassA_TP_NR_NP()) self.assertScheduler( self.circuit, self.passmanager, ["run transformation pass PassA_TP_NR_NP"] ) def test_non_idempotent_pass(self): """Two or more runs of a non-idempotent pass cannot be optimized.""" self.passmanager.append(PassF_reduce_dag_property()) self.passmanager.append([PassF_reduce_dag_property(), PassF_reduce_dag_property()]) self.passmanager.append(PassF_reduce_dag_property()) self.assertScheduler( self.circuit, self.passmanager, [ "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run transformation pass PassF_reduce_dag_property", "dag property = 3", ], ) def test_fenced_dag(self): """Analysis passes are not allowed to modified the DAG.""" qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.cx(qr[0], qr[1]) circ.cx(qr[0], qr[1]) circ.cx(qr[1], qr[0]) circ.cx(qr[1], qr[0]) self.passmanager.append(PassI_Bad_AP()) self.assertSchedulerRaises( circ, self.passmanager, ["run analysis pass PassI_Bad_AP", "cx_runs: {(4, 5, 6, 7)}"], TranspilerError, ) def test_analysis_pass_is_idempotent(self): """Analysis passes are idempotent.""" passmanager = PassManager() passmanager.append(PassE_AP_NR_NP(argument1=1)) passmanager.append(PassE_AP_NR_NP(argument1=1)) self.assertScheduler( self.circuit, passmanager, ["run analysis pass PassE_AP_NR_NP", "set property as 1"] ) def test_ap_before_and_after_a_tp(self): """A default transformation does not preserves anything and analysis passes need to be re-run""" passmanager = PassManager() passmanager.append(PassE_AP_NR_NP(argument1=1)) passmanager.append(PassA_TP_NR_NP()) passmanager.append(PassE_AP_NR_NP(argument1=1)) self.assertScheduler( self.circuit, passmanager, [ "run analysis pass PassE_AP_NR_NP", "set property as 1", "run transformation pass PassA_TP_NR_NP", "run analysis pass PassE_AP_NR_NP", "set property as 1", ], ) def test_pass_no_return(self): """Transformation passes that don't return a DAG raise error.""" self.passmanager.append(PassJ_Bad_NoReturn()) self.assertSchedulerRaises( self.circuit, self.passmanager, ["run transformation pass PassJ_Bad_NoReturn"], TranspilerError, ) def test_fixed_point_pass(self): """A pass set with a do_while parameter that checks for a fixed point.""" self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], ) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ], ) def test_fixed_point_fc(self): """A fixed point scheduler with flow control.""" self.passmanager.append( DoWhileController( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], ) ) expected = [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_fixed_point_pass_max_iteration(self): """A pass set with a do_while parameter that checks that the max_iteration is raised.""" self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], max_iteration=2, ) self.assertSchedulerRaises( self.circuit, self.passmanager, [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", ], TranspilerError, ) def test_fresh_initial_state(self): """New construction gives fresh instance.""" self.passmanager.append(PassM_AP_NR_NP(argument1=1)) self.passmanager.append(PassA_TP_NR_NP()) self.passmanager.append(PassM_AP_NR_NP(argument1=1)) self.assertScheduler( self.circuit, self.passmanager, [ "run analysis pass PassM_AP_NR_NP", "self.argument1 = 2", "run transformation pass PassA_TP_NR_NP", "run analysis pass PassM_AP_NR_NP", "self.argument1 = 2", ], ) def test_nested_conditional_in_loop(self): """Run a loop with a nested conditional.""" nested_conditional = [ ConditionalController( [PassA_TP_NR_NP()], condition=lambda property_set: property_set["property"] >= 5 ) ] self.passmanager.append( [PassK_check_fixed_point_property()] + nested_conditional + [PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], ) expected = [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ] self.assertScheduler(self.circuit, self.passmanager, expected) class DoXTimesController(FlowController): """A control-flow plugin for running a set of passes an X amount of times.""" def __init__(self, passes, options, do_x_times=0, **_): self.do_x_times = do_x_times() super().__init__(passes, options) def __iter__(self): for _ in range(self.do_x_times): yield from self.passes class TestControlFlowPlugin(SchedulerTestCase): """Testing the control flow plugin system.""" def setUp(self): super().setUp() self.passmanager = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_control_flow_plugin(self): """Adds a control flow plugin with a single parameter and runs it.""" FlowController.add_flow_controller("do_x_times", DoXTimesController) self.passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3) self.assertScheduler( self.circuit, self.passmanager, [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ], ) def test_callable_control_flow_plugin(self): """Removes do_while, then adds it back. Checks max_iteration still working.""" controllers_length = len(FlowController.registered_controllers) FlowController.remove_flow_controller("do_while") self.assertEqual(controllers_length - 1, len(FlowController.registered_controllers)) FlowController.add_flow_controller("do_while", DoWhileController) self.assertEqual(controllers_length, len(FlowController.registered_controllers)) self.passmanager.append( [PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_while=lambda property_set: True, max_iteration=2, ) self.assertSchedulerRaises( self.circuit, self.passmanager, [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ], TranspilerError, ) def test_remove_nonexistent_plugin(self): """Tries to remove a plugin that does not exist.""" self.assertRaises(KeyError, FlowController.remove_flow_controller, "foo") def test_bad_conditional(self): """Flow controller are not allowed to modify the property set.""" def bad_condition(property_set): property_set["property"] = "forbidden write" self.passmanager.append(PassA_TP_NR_NP(), condition=bad_condition) self.assertRaises(TranspilerError, self.passmanager.run, self.circuit) class TestDumpPasses(SchedulerTestCase): """Testing the passes method.""" def test_passes(self): """Dump passes in different FlowControllerLinear""" passmanager = PassManager() passmanager.append(PassC_TP_RA_PA()) passmanager.append(PassB_TP_RA_PA()) expected = [ {"flow_controllers": {}, "passes": [PassC_TP_RA_PA()]}, {"flow_controllers": {}, "passes": [PassB_TP_RA_PA()]}, ] self.assertEqual(expected, passmanager.passes()) def test_passes_in_linear(self): """Dump passes in the same FlowControllerLinear""" passmanager = PassManager( passes=[ PassC_TP_RA_PA(), PassB_TP_RA_PA(), PassD_TP_NR_NP(argument1=[1, 2]), PassB_TP_RA_PA(), ] ) expected = [ { "flow_controllers": {}, "passes": [ PassC_TP_RA_PA(), PassB_TP_RA_PA(), PassD_TP_NR_NP(argument1=[1, 2]), PassB_TP_RA_PA(), ], } ] self.assertEqual(expected, passmanager.passes()) def test_control_flow_plugin(self): """Dump passes in a custom flow controller.""" passmanager = PassManager() FlowController.add_flow_controller("do_x_times", DoXTimesController) passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3) expected = [ {"passes": [PassB_TP_RA_PA(), PassC_TP_RA_PA()], "flow_controllers": {"do_x_times"}} ] self.assertEqual(expected, passmanager.passes()) def test_conditional_and_loop(self): """Dump passes with a conditional and a loop.""" passmanager = PassManager() passmanager.append(PassE_AP_NR_NP(True)) passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], condition=lambda property_set: property_set["property_fixed_point"], ) expected = [ {"passes": [PassE_AP_NR_NP(True)], "flow_controllers": {}}, { "passes": [ PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property(), ], "flow_controllers": {"condition", "do_while"}, }, ] self.assertEqual(expected, passmanager.passes()) class StreamHandlerRaiseException(StreamHandler): """Handler class that will raise an exception on formatting errors.""" def handleError(self, record): raise sys.exc_info() class TestLogPasses(QiskitTestCase): """Testing the log_passes option.""" def setUp(self): super().setUp() logger = getLogger() self.addCleanup(logger.setLevel, logger.level) logger.setLevel("DEBUG") self.output = io.StringIO() logger.addHandler(StreamHandlerRaiseException(self.output)) self.circuit = QuantumCircuit(QuantumRegister(1)) def assertPassLog(self, passmanager, list_of_passes): """Runs the passmanager and checks that the elements in passmanager.property_set['pass_log'] match list_of_passes (the names).""" passmanager.run(self.circuit) self.output.seek(0) # Filter unrelated log lines output_lines = self.output.readlines() pass_log_lines = [x for x in output_lines if x.startswith("Pass:")] for index, pass_name in enumerate(list_of_passes): self.assertTrue(pass_log_lines[index].startswith("Pass: %s -" % pass_name)) def test_passes(self): """Dump passes in different FlowControllerLinear""" passmanager = PassManager() passmanager.append(PassC_TP_RA_PA()) passmanager.append(PassB_TP_RA_PA()) self.assertPassLog(passmanager, ["PassA_TP_NR_NP", "PassC_TP_RA_PA", "PassB_TP_RA_PA"]) def test_passes_in_linear(self): """Dump passes in the same FlowControllerLinear""" passmanager = PassManager( passes=[ PassC_TP_RA_PA(), PassB_TP_RA_PA(), PassD_TP_NR_NP(argument1=[1, 2]), PassB_TP_RA_PA(), ] ) self.assertPassLog( passmanager, [ "PassA_TP_NR_NP", "PassC_TP_RA_PA", "PassB_TP_RA_PA", "PassD_TP_NR_NP", "PassA_TP_NR_NP", "PassB_TP_RA_PA", ], ) def test_control_flow_plugin(self): """Dump passes in a custom flow controller.""" passmanager = PassManager() FlowController.add_flow_controller("do_x_times", DoXTimesController) passmanager.append([PassB_TP_RA_PA(), PassC_TP_RA_PA()], do_x_times=lambda x: 3) self.assertPassLog( passmanager, [ "PassA_TP_NR_NP", "PassB_TP_RA_PA", "PassC_TP_RA_PA", "PassB_TP_RA_PA", "PassC_TP_RA_PA", "PassB_TP_RA_PA", "PassC_TP_RA_PA", ], ) def test_conditional_and_loop(self): """Dump passes with a conditional and a loop""" passmanager = PassManager() passmanager.append(PassE_AP_NR_NP(True)) passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], condition=lambda property_set: property_set["property_fixed_point"], ) self.assertPassLog(passmanager, ["PassE_AP_NR_NP"]) class TestPassManagerReuse(SchedulerTestCase): """The PassManager instance should be reusable.""" def setUp(self): super().setUp() self.passmanager = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_chain_twice(self): """Run a chain twice.""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) self.assertScheduler(self.circuit, self.passmanager, expected) def test_conditional_twice(self): """Run a conditional twice.""" self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) expected = [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", ] self.assertScheduler(self.circuit, self.passmanager, expected) self.assertScheduler(self.circuit, self.passmanager, expected) def test_fixed_point_twice(self): """A fixed point scheduler, twice.""" self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], do_while=lambda property_set: not property_set["property_fixed_point"], ) expected = [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ] self.assertScheduler(self.circuit, self.passmanager, expected) self.assertScheduler(self.circuit, self.passmanager, expected) class TestPassManagerChanges(SchedulerTestCase): """Test PassManager manipulation with changes""" def setUp(self): super().setUp() self.passmanager = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_replace0(self): """Test passmanager.replace(0, ...).""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.replace(0, PassB_TP_RA_PA()) expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_replace1(self): """Test passmanager.replace(1, ...).""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.replace(1, PassC_TP_RA_PA()) expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_remove0(self): """Test passmanager.remove(0).""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.remove(0) expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_remove1(self): """Test passmanager.remove(1).""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.remove(1) expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_remove_minus_1(self): """Test passmanager.remove(-1).""" self.passmanager.append(PassA_TP_NR_NP()) self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.remove(-1) expected = ["run transformation pass PassA_TP_NR_NP"] self.assertScheduler(self.circuit, self.passmanager, expected) def test_setitem(self): """Test passmanager[1] = ...""" self.passmanager.append(PassC_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager.append(PassB_TP_RA_PA()) # Request: PassA / Preserves: PassA self.passmanager[1] = PassC_TP_RA_PA() expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager, expected) def test_replace_with_conditional(self): """Replace a pass with a conditional pass.""" self.passmanager.append(PassE_AP_NR_NP(False)) self.passmanager.append(PassB_TP_RA_PA()) self.passmanager.replace( 1, PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) expected = ["run analysis pass PassE_AP_NR_NP", "set property as False"] self.assertScheduler(self.circuit, self.passmanager, expected) def test_replace_error(self): """Replace a non-existing index.""" self.passmanager.append(PassB_TP_RA_PA()) with self.assertRaises(TranspilerError): self.passmanager.replace(99, PassA_TP_NR_NP()) class TestPassManagerSlicing(SchedulerTestCase): """test PassManager slicing.""" def setUp(self): super().setUp() self.passmanager = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_empty_passmanager_length(self): """test len(PassManager) when PassManager is empty""" length = len(self.passmanager) expected_length = 0 self.assertEqual(length, expected_length) def test_passmanager_length(self): """test len(PassManager) when PassManager is not empty""" self.passmanager.append(PassA_TP_NR_NP()) self.passmanager.append(PassA_TP_NR_NP()) length = len(self.passmanager) expected_length = 2 self.assertEqual(length, expected_length) def test_accessing_passmanager_by_index(self): """test accessing PassManager's passes by index""" self.passmanager.append(PassB_TP_RA_PA()) self.passmanager.append(PassC_TP_RA_PA()) new_passmanager = self.passmanager[1] expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_accessing_passmanager_by_index_with_condition(self): """test accessing PassManager's conditioned passes by index""" self.passmanager.append(PassF_reduce_dag_property()) self.passmanager.append( [PassK_check_fixed_point_property(), PassA_TP_NR_NP(), PassF_reduce_dag_property()], condition=lambda property_set: True, do_while=lambda property_set: not property_set["property_fixed_point"], ) new_passmanager = self.passmanager[1] expected = [ "run analysis pass PassG_calculates_dag_property", "set property as 8 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 6", "run analysis pass PassG_calculates_dag_property", "set property as 6 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 5", "run analysis pass PassG_calculates_dag_property", "set property as 5 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 4", "run analysis pass PassG_calculates_dag_property", "set property as 4 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 3", "run analysis pass PassG_calculates_dag_property", "set property as 3 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", "run analysis pass PassG_calculates_dag_property", "set property as 2 (from dag.property)", "run analysis pass PassK_check_fixed_point_property", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassF_reduce_dag_property", "dag property = 2", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_accessing_passmanager_by_range(self): """test accessing PassManager's passes by range""" self.passmanager.append(PassC_TP_RA_PA()) self.passmanager.append(PassB_TP_RA_PA()) self.passmanager.append(PassC_TP_RA_PA()) self.passmanager.append(PassD_TP_NR_NP()) new_passmanager = self.passmanager[1:3] expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_accessing_passmanager_by_range_with_condition(self): """test accessing PassManager's passes by range with condition""" self.passmanager.append(PassB_TP_RA_PA()) self.passmanager.append(PassE_AP_NR_NP(True)) self.passmanager.append( PassA_TP_NR_NP(), condition=lambda property_set: property_set["property"] ) self.passmanager.append(PassB_TP_RA_PA()) new_passmanager = self.passmanager[1:3] expected = [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_accessing_passmanager_error(self): """testing accessing a pass item not in list""" self.passmanager.append(PassB_TP_RA_PA()) with self.assertRaises(IndexError): self.passmanager = self.passmanager[99] class TestPassManagerConcatenation(SchedulerTestCase): """test PassManager concatenation by + operator.""" def setUp(self): super().setUp() self.passmanager1 = PassManager() self.passmanager2 = PassManager() self.circuit = QuantumCircuit(QuantumRegister(1)) def test_concatenating_passmanagers(self): """test adding two PassManagers together""" self.passmanager1.append(PassB_TP_RA_PA()) self.passmanager2.append(PassC_TP_RA_PA()) new_passmanager = self.passmanager1 + self.passmanager2 expected = [ "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_concatenating_passmanagers_with_condition(self): """test adding two pass managers with condition""" self.passmanager1.append(PassE_AP_NR_NP(True)) self.passmanager1.append(PassB_TP_RA_PA()) self.passmanager2.append( PassC_TP_RA_PA(), condition=lambda property_set: property_set["property"] ) self.passmanager2.append(PassB_TP_RA_PA()) new_passmanager = self.passmanager1 + self.passmanager2 expected = [ "run analysis pass PassE_AP_NR_NP", "set property as True", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, new_passmanager, expected) def test_adding_pass_to_passmanager(self): """test adding a pass to PassManager""" self.passmanager1.append(PassE_AP_NR_NP(argument1=1)) self.passmanager1.append(PassB_TP_RA_PA()) self.passmanager1 += PassC_TP_RA_PA() expected = [ "run analysis pass PassE_AP_NR_NP", "set property as 1", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager1, expected) def test_adding_list_of_passes_to_passmanager(self): """test adding a list of passes to PassManager""" self.passmanager1.append(PassE_AP_NR_NP(argument1=1)) self.passmanager1.append(PassB_TP_RA_PA()) self.passmanager1 += [PassC_TP_RA_PA(), PassB_TP_RA_PA()] expected = [ "run analysis pass PassE_AP_NR_NP", "set property as 1", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassB_TP_RA_PA", "run transformation pass PassC_TP_RA_PA", "run transformation pass PassB_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager1, expected) def test_adding_list_of_passes_to_passmanager_with_condition(self): """test adding a list of passes to a PassManager that have conditions""" self.passmanager1.append(PassE_AP_NR_NP(False)) self.passmanager1.append( PassB_TP_RA_PA(), condition=lambda property_set: property_set["property"] ) self.passmanager1 += PassC_TP_RA_PA() expected = [ "run analysis pass PassE_AP_NR_NP", "set property as False", "run transformation pass PassA_TP_NR_NP", "run transformation pass PassC_TP_RA_PA", ] self.assertScheduler(self.circuit, self.passmanager1, expected) def test_adding_pass_to_passmanager_error(self): """testing adding a non-pass item to PassManager""" with self.assertRaises(TypeError): self.passmanager1 += "not a pass" def test_adding_list_to_passmanager_error(self): """testing adding a list having a non-pass item to PassManager""" with self.assertRaises(TypeError): self.passmanager1 += [PassB_TP_RA_PA(), "not a pass"] if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from docplex.mp.model import Model from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import CobylaOptimizer, MinimumEigenOptimizer from qiskit_optimization.algorithms.admm_optimizer import ADMMParameters, ADMMOptimizer from qiskit_optimization.translators import from_docplex_mp # If CPLEX is installed, you can uncomment this line to import the CplexOptimizer. # CPLEX can be used in this tutorial to solve the convex continuous problem, # but also as a reference to solve the QUBO, or even the full problem. # # from qiskit.optimization.algorithms import CplexOptimizer # define COBYLA optimizer to handle convex continuous problems. cobyla = CobylaOptimizer() # define QAOA via the minimum eigen optimizer qaoa = MinimumEigenOptimizer(QAOA(sampler=Sampler(), optimizer=COBYLA())) # exact QUBO solver as classical benchmark exact = MinimumEigenOptimizer(NumPyMinimumEigensolver()) # to solve QUBOs # in case CPLEX is installed it can also be used for the convex problems, the QUBO, # or as a benchmark for the full problem. # # cplex = CplexOptimizer() # construct model using docplex mdl = Model("ex6") v = mdl.binary_var(name="v") w = mdl.binary_var(name="w") t = mdl.binary_var(name="t") u = mdl.continuous_var(name="u") mdl.minimize(v + w + t + 5 * (u - 2) ** 2) mdl.add_constraint(v + 2 * w + t + u <= 3, "cons1") mdl.add_constraint(v + w + t >= 1, "cons2") mdl.add_constraint(v + w == 1, "cons3") # load quadratic program from docplex model qp = from_docplex_mp(mdl) print(qp.prettyprint()) admm_params = ADMMParameters( rho_initial=1001, beta=1000, factor_c=900, maxiter=100, three_block=True, tol=1.0e-6 ) # define QUBO optimizer qubo_optimizer = exact # qubo_optimizer = cplex # uncomment to use CPLEX instead # define classical optimizer convex_optimizer = cobyla # convex_optimizer = cplex # uncomment to use CPLEX instead # initialize ADMM with classical QUBO and convex optimizer admm = ADMMOptimizer( params=admm_params, qubo_optimizer=qubo_optimizer, continuous_optimizer=convex_optimizer ) # run ADMM to solve problem result = admm.solve(qp) print(result.prettyprint()) plt.plot(result.state.residuals) plt.xlabel("Iterations") plt.ylabel("Residuals") plt.show() # define QUBO optimizer qubo_optimizer = qaoa # define classical optimizer convex_optimizer = cobyla # convex_optimizer = cplex # uncomment to use CPLEX instead # initialize ADMM with quantum QUBO optimizer and classical convex optimizer admm_q = ADMMOptimizer( params=admm_params, qubo_optimizer=qubo_optimizer, continuous_optimizer=convex_optimizer ) # run ADMM to solve problem result_q = admm_q.solve(qp) print(result.prettyprint()) plt.clf() plt.plot(result_q.state.residuals) plt.xlabel("Iterations") plt.ylabel("Residuals") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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.cx(qrx, 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/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) ### replaced x gate ### qc.x(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) ### replaced x gate ### qc.x(1) return qc
https://github.com/pedroripper/qiskit_tutoriais
pedroripper
from qiskit import * circuito = QuantumCircuit(2,2) circuito.draw(output = 'mpl') from qiskit.tools.visualization import plot_bloch_multivector simulator = Aer.get_backend('statevector_simulator') result = execute(circuito, backend = simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector) # Primeiramente o qiskit inicializa os qubits nos estados 0 e 1 circuito = QuantumCircuit(2,2) circuito.x(0) circuito.draw(output = 'mpl') from qiskit.tools.visualization import plot_bloch_multivector simulator = Aer.get_backend('statevector_simulator') result = execute(circuito, backend = simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector) circuito.y(0) circuito.draw(output = 'mpl') from qiskit.tools.visualization import plot_bloch_multivector simulator = Aer.get_backend('statevector_simulator') result = execute(circuito, backend = simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector) # No tutorial sobre as portas Rx, Ry e Rz vimos que usando a porta Ry para rotacionar o qubit em pi/2 conseguimos # o estado |+> import math circuito.ry(math.pi/2,1) circuito.draw(output = 'mpl') from qiskit.tools.visualization import plot_bloch_multivector simulator = Aer.get_backend('statevector_simulator') result = execute(circuito, backend = simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector) # Agora aplicando a porta Z circuito.z(1) circuito.draw(output = 'mpl') from qiskit.tools.visualization import plot_bloch_multivector simulator = Aer.get_backend('statevector_simulator') result = execute(circuito, backend = simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector) circuito.id(1) circuito.draw(output = 'mpl') from qiskit.tools.visualization import plot_bloch_multivector simulator = Aer.get_backend('statevector_simulator') result = execute(circuito, backend = simulator).result() statevector = result.get_statevector() plot_bloch_multivector(statevector)
https://github.com/AmanSinghBhogal/NasaNEO_Classification
AmanSinghBhogal
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/liudingshan/QiskitGrovers
liudingshan
import qiskit as qis from qiskit.tools.visualization import plot_bloch_multivector import matplotlib.pyplot as plt from qiskit.tools.visualization import plot_histogram import math as math # Define Registers qr = qis.QuantumRegister(4) cr = qis.ClassicalRegister(4) # Make Circuit circuit = qis.QuantumCircuit(qr, cr) # Make Gates and Circuit Additions circuit.h(qr[0]) circuit.crz(math.pi/2, qr[1], qr[0]) circuit.crz(math.pi/4, qr[2], qr[0]) circuit.crz(math.pi/8, qr[3], qr[0]) circuit.barrier circuit.h(qr[1]) circuit.crz(math.pi/2, qr[2], qr[1]) circuit.crz(math.pi/4, qr[3], qr[1]) circuit.h(qr[2]) circuit.crz(math.pi/2, qr[3], qr[2]) circuit.h(qr[3]) # Choose Unitary Simulator simulator = qis.Aer.get_backend('unitary_simulator') # Get Unitary Results (Multiplication of all Gates/Additions) result = qis.execute(circuit, backend=simulator).result() unitary = result.get_unitary() # Plot Unitary Results print(unitary) # Choose Statevector Simulator simulator = qis.Aer.get_backend('statevector_simulator') # Get Statevector Results result = qis.execute(circuit, backend=simulator).result() statevector = result.get_statevector() # Plot Statevector Results plot_bloch_multivector(statevector) # Measure Qubits to Classical circuit.measure(qr, cr) # Print Circuit (Along w/ Measurements) #print(circuit) circuit.draw(output='mpl') # Choose Qasm Simulator simulator = qis.Aer.get_backend('qasm_simulator') # Get Qasm Results result = qis.execute(circuit, backend=simulator).result() # Plot Qasm Measurements plot_histogram(result.get_counts(circuit)) plt.show() print()